method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
c7146fee-7f06-4b08-9c9c-f27946726cf6
4
@SuppressWarnings("unchecked") public static LinkedHashMap<String,Object> gvHashSO(LinkedHashMap<String,Object> array, String key) { if (array == null) return new LinkedHashMap<String,Object>(); Object retObj = gv(array,key); LinkedHashMap<String,Object> hm = new LinkedHashMap<String,Object>(); if (retObj instanceof LinkedHashMap) { try { hm = (LinkedHashMap<String,Object>) retObj; } catch (Throwable e) { return hm; } } else { if (retObj != null) array_push(hm,retObj); } return hm; }
78cab73a-7b24-4788-9b45-f132c55d48b4
6
public int peak(int [] arrA,int low, int high, int size){ int mid = (low+high)/2; if((mid==0||arrA[mid]>=arrA[mid-1]) && (arrA[mid]>=arrA[mid+1]||mid==size-1)){ return mid; } else if(mid>0 && arrA[mid]<arrA[mid-1]) return peak(arrA,low,mid-1,size); else return peak(arrA,mid+1,high,size); }
45f7a45c-03d5-4aa7-baa2-0a0432a0d3b9
5
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); try { if(request.getParameter("page").equalsIgnoreCase("createquestion")){ String questionid=CommonResource.getNextId("question"); String question=request.getParameter("questionname"); String category=request.getParameter("Category"); String option1=request.getParameter("option1"); String option2=request.getParameter("option2"); String option3=request.getParameter("option3"); String option4=request.getParameter("option4"); String answer=request.getParameter("answer"); QuestionBean q=new QuestionBean(); q.setQuestionid(questionid); q.setQuestion(question); q.setCategory(category); q.setOption1(option1); q.setOption2(option2); q.setOption3(option3); q.setOption4(option4); q.setAnswer(answer); QuestionDAO.createQuestion(q); response.sendRedirect("/OTTS/jsp/CreateQuestion.jsp"); } if(request.getParameter("page").equalsIgnoreCase("delete")) { String questionid = request.getParameter("QuestionId"); QuestionBean a = new QuestionBean(); a.setQuestionid(questionid); QuestionDAO b = new QuestionDAO(); QuestionBean obj1 = b.DeleteQuestions(a); getServletContext() .getRequestDispatcher("/jsp/Success.jsp").forward( request, response); } if(request.getParameter("page").equalsIgnoreCase("update")) { String questionid = request.getParameter("QuestionId"); String question = request.getParameter("Question"); String category = request.getParameter("Category"); String option1 = request.getParameter("Option1"); String option2= request.getParameter("Option2"); String option3 = request.getParameter("Option3"); String option4 = request.getParameter("Option4"); String answer = request.getParameter("answer"); QuestionBean a = new QuestionBean(); a.setQuestionid(questionid); a.setQuestion(question); a.setCategory(category); a.setOption1(option1); a.setOption2(option2); a.setOption3(option3); a.setOption4(option4); a.setAnswer(answer); QuestionDAO b = new QuestionDAO(); QuestionBean obj1 = b.UpdateQuestions(a); getServletContext() .getRequestDispatcher("/jsp/Success.jsp").forward( request, response); } if(request.getParameter("page").equalsIgnoreCase("view")){ String qid=request.getParameter("QuestionId"); QuestionBean v =new QuestionBean(); QuestionDAO obj = new QuestionDAO(); String total = obj.viewQuestion(qid); PrintWriter out=response.getWriter(); response.setContentType("text/html"); out.println("<table border=1><thead><tr>"); out.println("<th><B>QUESTION_ID</B></th>"); out.println("<th><B>QUESTION</B></th>"); out.println("<TH><B>CATEGORY</B></TH>"); out.println("<th><B>OPTION1</B></th>"); out.println("<th><B>OPTION2</B></th>"); out.println("<th><B>OPTION3</B></th>"); out.println("<th><B>OPTION4</B></th>"); out.println("<th><B>ANSWER</B></th><</tr></thead>"); out.println("<tr><td>"); out.println(obj.getquestionid()); out.println("</td>"); out.println("<td>"); out.println(obj.getquestion()); out.println("</td>"); out.println("<td>"); out.println(obj.getcategory()); out.println("</td>"); out.println("<td>"); out.println(obj.getoption1()); out.println("</td>"); out.println("<td>"); out.println(obj.getoption2()); out.println("</td>"); out.println("<td>"); out.println(obj.getoption3()); out.println("</td>"); out.println("<td>"); out.println(obj.getoption4()); out.println("</td>"); out.println("<td>"); out.println(obj.getanswer()); out.println("</td>"); out.println("</tr>"); out.println("</table>"); out.println("<a href=http://localhost:8080/OnlineTestTakingSystem/jsp/adminlogin.jsp> Go Back To Main Page</a>"); //getServletContext().getRequestDispatcher("/jsp/Success.jsp").forward(request, response); } } catch (Exception e) { } finally { } }
dc2d689a-d638-4537-a3de-26f26a7ce22e
6
public static String encode(double latitude, double longitude){ double[] lat_interval = {-90.0 , 90.0}; double[] lon_interval = {-180.0, 180.0}; StringBuilder geohash = new StringBuilder(); boolean is_even = true; int bit = 0, ch = 0; while(geohash.length() < precision){ double mid = 0.0; if(is_even){ mid = (lon_interval[0] + lon_interval[1]) / 2; if (longitude > mid){ ch |= bits[bit]; lon_interval[0] = mid; } else { lon_interval[1] = mid; } } else { mid = (lat_interval[0] + lat_interval[1]) / 2; if(latitude > mid){ ch |= bits[bit]; lat_interval[0] = mid; } else { lat_interval[1] = mid; } } is_even = is_even ? false : true; if (bit < 4){ bit ++; } else { geohash.append(_base32[ch]); bit =0; ch = 0; } } return geohash.toString(); }
d1ef1a82-b205-4c7c-871f-3b66512512f0
7
public Mes(int i, boolean bis) { if (i == 3 || i == 5 || i == 8 || i == 10) { n = 30; } else if (i == 1) { if (bis == false) { n = 28; } else { n = 29; } } else { n = 31; } dia = new Dias[n]; for (int j = 0; j < n; j++) { dia[j] = new Dias(); } }
2b7fcf62-9cfd-4c96-9c71-d7d56c8b7388
7
private void validate() throws ScheduleException { // For each team... for ( NFLTeam team : NFLTeam.values() ) { // ...make sure it has its schedule loaded. NFLMatchup[] schedule = matchups.get(team); if ( null == schedule ) { scheduleNotLoaded(team); } // For each week in its schedule... int bye = -1;; for ( int week = 0; week < MAX_WEEK; week++ ) { NFLMatchup matchup = schedule[week]; // ... if it is null it could be a bye week. Keep // track to make sure it has exactly one bye week. if ( null == matchup ) { if ( -1 != bye ) { LOG.warn("Multiple bye weeks for team (likely incomplete schedule): {}", team); scheduleNotLoaded(team); } byes.put(team, week); bye = week; continue; } // The same matchup should be loaded under the opposing team. NFLTeam opponent = matchup.getOpponent(team); if ( !matchup.equals(getMatchup(opponent, matchup.getWeek())) ) { String msg = String.format("Opposing schedules do not match (%s/%s, week %d", team, opponent, week); LOG.warn(msg); throw new InvalidScheduleException(msg); } } // After we've iterated over the matchups for the team, we // can also ensure that at least one bye week was loaded. if ( null == byes.get(team) ) { String msg = "Invalid schedule (no bye week) for team: " + team; LOG.warn(msg); throw new InvalidScheduleException(msg); } } }
7661bdab-596a-4bda-8c72-bf9328005a44
1
@Override protected void logBindInfo(Method method) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("绑定" + getDescription() + "到方法[" + method + "]成功"); } }
9934a937-b455-416f-8b57-d2c97e739161
5
protected boolean storeRegistrationID(Sim_event ev, List list) { boolean result = false; if (ev == null || list == null) { return result; } Object obj = ev.get_data(); if (obj instanceof Integer) { Integer id = (Integer) obj; list.add(id); result = true; if (record_) { write("Registering", id.intValue(), GridSim.clock()); System.out.println(); System.out.println(super.get_name() + ": registering " + GridSim.getEntityName(id)); for (int i = 0; i < list.size() ; i++) { System.out.println(super.get_name() + ": list["+ i +"] = " + GridSim.getEntityName((Integer) list.get(i)) ); } System.out.println(); } } return result; }
41bd1d8d-4020-48ef-a574-08c52276fdb7
2
public void deleteUser(String userEmail) { initConnection(); PreparedStatement sqlStatement = null; try { //Prepare Statement sqlStatement = (PreparedStatement) connection.prepareStatement("DELETE FROM users WHERE email= ?;"); sqlStatement.setString(1, userEmail); //Execute Prepared Statement sqlStatement.executeUpdate(); //TODO: Remove debug System.out.println("Deleting user with: [" + sqlStatement.toString() + "]"); } catch(Exception ex) { System.out.println("Problem executing SQL statement [" + sqlStatement.toString() + "] in RegisterService.java"); ex.printStackTrace(); } finally { try { //Finally close stuff to return connection to pool for reuse sqlStatement.close(); connection.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } } }
f7530215-2f7a-4704-a2bf-01cf543ca2b7
7
private Map<Integer, List<Integer>> createDAG(String sentence) { Map<Integer, List<Integer>> dag = new HashMap<Integer, List<Integer>>(); TrieNode trie = wordDict.getTrie(); int N = sentence.length(); int i = 0, j = 0; TrieNode p = trie; while (i < N) { char ch = sentence.charAt(j); if (p.childs.containsKey(ch)) { p = p.childs.get(ch); if (p.childs.containsKey(' ')) { if (!dag.containsKey(i)) { List<Integer> value = new ArrayList<Integer>(); dag.put(i, value); value.add(j); } else dag.get(i).add(j); } j += 1; if (j >= N) { i += 1; j = i; p = trie; } } else { p = trie; i += 1; j = i; } } for (i = 0; i < N; ++i) { if (!dag.containsKey(i)) { List<Integer> value = new ArrayList<Integer>(); value.add(i); dag.put(i, value); } } return dag; }
f6fa5775-10ab-4512-819a-d62a0892d8ef
3
public Object tooltip(Coord c,boolean again){ if(tip != null) return(tip); if(tips != null && !tips.equals("")){ tip = RichText.render(tips,200); } return(tip); }
e057d032-c2e3-469e-9a9d-34d4733c2e0e
0
public String getMsgID() { return msgID; }
05c0d649-a267-42b2-8ef1-a2816e682172
8
private void installLookAndFeel() { if (fLFName != null) { UIManager.LookAndFeelInfo[] lfInfos = UIManager.getInstalledLookAndFeels(); if (lfInfos != null) { for (int i = 0; i < lfInfos.length; i++) { if (lfInfos[i].getName().equals(fLFName)) { try { UIManager.setLookAndFeel(lfInfos[i].getClassName()); } catch (ClassNotFoundException e) {} catch (InstantiationException e) {} catch (IllegalAccessException e) {} catch (UnsupportedLookAndFeelException e) {} break; } } } } }
191a817f-d63e-4405-a2a8-119c322b0f71
2
public static void main(String[] args) throws IOException { System.out.println(new Date()); Features feat = new Features(50,50); feat.integralImages(feat.FACES, feat.numbFaces, feat.integralFaces); for(int i = 0; i < 2; i++){ for (int j = 0; j < 4; j+=2) { System.out.println(i + " " + j + " " + feat.getSingleFeat(feat.integralFaces, 0, Feat.Shape.VERT3, new Pair(i, j), new Pair(i+2, j))); } } /* feat.integralImages(feat.NONFACES, feat.numbNonFaces, feat.integralNonFaces); feat.generateFeat(feat.integralFaces, true); feat.generateFeat(feat.integralNonFaces, false); List<Feat> myfeats = feat.result; System.out.println(new Date()); System.out.println(myfeats.size()); */ }
d7879ebf-0a50-4158-9781-0951ef1aa42c
4
public void clickChooseCharacters(Scanner kb, ArrayList<MainMenuHeroSlot> heroies) { //Print out prompt System.out.println("Please input what type of heroes you would like to use one by one"); for(int i = 0; i < Constants.heroNames.length; i++) System.out.println(" - " + Constants.heroNames[i]); //Pick 3 characters for(int heroes = 1; heroes < 4;){ try{ //Get hero from character factory Character character1 = CharacterFactory.create().buyCharacter(kb.next()); //Don't allow wrong spelling to make default character if(character1.getDesc().equalsIgnoreCase("Default")) throw new EmptyStackException(); //create hero slot MainMenuHeroSlot temp = new MainMenuHeroSlot(); //add new hero to the hero slot temp.SwapHero(character1); //add hero slot to the array list heroies.add(temp); System.out.println("Character " + heroes + " picked"); //If passes test of "not default" then increment heroes++; //Testing what was made //System.out.println(character1.toString()); }catch(Exception e){ System.out.println("Failed to pick that hero, please try again."); } } gumballMachine.setState(gumballMachine.hasChosenCharactersState()); kb.nextLine(); }
aa4ba505-a018-458c-bb33-d2922f00f3e1
3
private UserBean createUserBean(ResultSet result){ try { //gebe null zurück, falls kein User vorhanden ist if (result == null || result.getFetchSize() < 0){ return null; }else{ UserBean user = new UserBean(); user.setId(result.getInt("id")); user.setActive(result.getInt("active") == 1); user.setActivationKey(result.getInt("activationKey")); user.setEmail(result.getString("email")); user.setName(result.getString("name")); user.setPassword(result.getString("password")); user.setRole(result.getString("role")); return user; } } catch (SQLException ex) { Logger.getLogger(FilmothekModel.class.getName()).log(Level.SEVERE, null, ex); return null; } }
4adc3266-ca74-4580-9de6-fbbfc550a00a
4
public void run() { //Guarda el tiempo actual del sistema tiempoActual = System.currentTimeMillis(); //Ciclo principal del Applet. Actualiza y despliega en pantalla la animación hasta que el Applet sea cerrado while (true) { if (!pausa && !instrucciones) { actualiza(); checaColision(); } repaint(); //Hace una pausa de 200 milisegundos try { Thread.sleep(60); } catch (InterruptedException ex) { // no hace nada } } }
afde8f8d-140c-48d4-a34f-c49fcd60ea9f
8
private void decodeGroup(String serviceName, OMMFilterEntry serviceFilterEntry) { byte[] group = null; byte[] mergedToGroup = null; OMMState groupStatus = null; // Get Group, MergedToGroup and Status from the payload OMMData serviceFilterEntryData = serviceFilterEntry.getData(); for (Iterator<?> eliter = ((OMMElementList)serviceFilterEntryData).iterator(); eliter .hasNext();) { OMMElementEntry entry = (OMMElementEntry)eliter.next(); OMMData data = entry.getData(); if (entry.getName().equals(RDMService.Group.Group)) { group = ((OMMDataBuffer)data).getBytes().clone(); } else if (entry.getName().equals(RDMService.Group.MergedToGroup)) { mergedToGroup = ((OMMDataBuffer)data).getBytes().clone(); } else if (entry.getName().equals(RDMService.Group.Status)) { groupStatus = (OMMState)data; } } if (group != null) { // First we need to merge groups OMMItemGroup fromGroup = OMMItemGroup.create(group); if (mergedToGroup != null) { OMMItemGroup toGroup = OMMItemGroup.create(mergedToGroup); _itemGroupManager.mergeGroup(serviceName, fromGroup, toGroup); fromGroup = toGroup; System.out.println(_instanceName + " Merged group " + fromGroup + " in " + serviceName + " to group " + toGroup); } // Then we apply status to the group if (groupStatus != null) { _itemGroupManager.applyStatus(serviceName, fromGroup, groupStatus); } } }
f5f53caa-3394-4422-b64f-40c375a6c7c1
9
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof CountrylanguagePK)) { return false; } CountrylanguagePK other = (CountrylanguagePK) object; if ((this.countryCode == null && other.countryCode != null) || (this.countryCode != null && !this.countryCode.equals(other.countryCode))) { return false; } if ((this.language == null && other.language != null) || (this.language != null && !this.language.equals(other.language))) { return false; } return true; }
a9057f14-db27-465c-844e-71f910279e9f
0
public static void main(String[] args) { Ex3 e = new Ex3(); D1.main(args); }
788fc182-8c09-48ae-9fbb-e00adefaa08a
2
public HiloBean loadId(HiloBean oCliente) throws NumberFormatException { try { if (request.getParameter("id") != null) { oCliente.setId(Integer.parseInt(request.getParameter("id"))); } else { oCliente.setId(0); } } catch (NumberFormatException e) { throw new NumberFormatException("Controller: Error: Load: Formato de datos en parámetros incorrecto " + e.getMessage()); } return oCliente; }
1b65e23f-3b53-4ff3-a740-be687d4f29b9
4
public List<Ban> searchBans(String search, boolean reverse) { List<Ban> result = new ArrayList<Ban>(); if (search == null || search.isEmpty()) { result.addAll(bans.values()); } else { // compile regex to search... Pattern searchPattern = Pattern.compile(search); for (String n : bans.keySet()) { if (searchPattern.matcher(n).matches()) { result.add(bans.get(n)); } } } Collections.sort(result, new BanComparator(reverse)); return result; }
f0067d14-3174-45bf-b3cb-cf29ee176145
1
public static void insertTva(String tva, float taux) throws SQLException { String query = ""; try { query = "INSERT INTO TVA (TVALIBELLE,TVATX) VALUES (?,?) "; PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query); pStatement.setString(1, tva); pStatement.setFloat(2, taux); pStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(RequetesTva.class.getName()).log(Level.SEVERE, null, ex); } }
86d250c3-5f77-430d-b4be-fd5ea71e8838
7
BitSet[] computeRows() { HashMap<Short,BitSet> sets = new HashMap<Short,BitSet>(); for (int i=all.nextSetBit(0);i>=0;i=all.nextSetBit(i+1)) { sets.put( (short)i, (BitSet)all.clone() ); } for ( int i=0;i<sections.size();i++ ) { Section s = sections.get(i); if ( s.state==SectionState.merged && getBooleanOption(Options.HIDE_MERGED) ) { for (int j=all.nextSetBit(0);j>=0;j=all.nextSetBit(j+1)) adjustSet( sets, all, (short)j ); } else { Set<Short> keys = s.lists.keySet(); Iterator<Short> iter = keys.iterator(); while ( iter.hasNext() ) { short key = iter.next(); FragList fl = s.lists.get( key ); BitSet bs = fl.getShared(); adjustSet( sets, bs, key ); } } } Set<Short> bsKeys = sets.keySet(); HashSet<BitSet> map = new HashSet<BitSet>(); Iterator<Short> iter2 = bsKeys.iterator(); while ( iter2.hasNext() ) { Short v = iter2.next(); map.add( sets.get(v) ); } BitSet[] barray = new BitSet[map.size()]; map.toArray(barray); return barray; }
59aafa54-7398-4b58-a2f9-7f7737b7396d
7
@Override public void mouseDragged(MouseEvent e) { if (e.isConsumed() || (selectedTask == null)) { return; } Graphics2D g2 = (Graphics2D)chart.getGraphics(); g2.setXORMode(Color.WHITE); g2.draw(new Line2D.Double(selectedPoint, lastPoint)); lastPoint = e.getPoint(); Object hoverTask = chart.getTaskAtPoint(lastPoint); if ((hoverTask == null) || (hoverTask == selectedTask)) { if (targetBounds != null) { g2.draw(targetBounds); } targetBounds = null; } else if (hoverTask != targetTask) { if (targetBounds != null) { g2.draw(targetBounds); } targetTask = hoverTask; targetBounds = chart.getTaskBounds(targetTask, chart.getRow(lastPoint.getY()), 0, 0); targetBounds.setRect(targetBounds.getX()-1.0, targetBounds.getY()-1.0, targetBounds.getWidth()+2.0, targetBounds.getHeight()+2.0); g2.draw(targetBounds); } g2.draw(new Line2D.Double(selectedPoint, lastPoint)); g2.setPaintMode(); e.consume(); }
d6cbe30f-70b3-4494-9386-60fa847e4ca5
2
public void releaseVM(SlaveVM vm) { System.out.println("DEBUG: VM " + vm.getId() + " is available again"); vm.setState(VMState.WAITING); this.vmsInUse.remove(vm); this.vmsAvailable.add(vm); final int id = vm.getId(); Thread timeout = new Thread() { public void run() { try { Thread.sleep(ResourcePool.VM_TIMEOUT); } catch (InterruptedException e) { } synchronized (vmsAvailable) { // always keep one VM alive if (availableVMCount() > 1) { removeVM(allVms.get(id)); } } } }; timeout.start(); }
f7d03776-629e-4b94-a945-bce475183e81
9
public void actionPerformed(ActionEvent paramActionEvent) { try { if (paramActionEvent.getActionCommand().compareTo("title") == 0) { if (this.minimized) { setMinimized(false); return; } setMinimized(true); return; } if (paramActionEvent.getActionCommand().compareTo("P:down") == 0) { this.ScrollThread = new UtilityThread(50, this, getClass().getMethod("stepDown", null), false); this.ScrollThread.start(); return; } if (paramActionEvent.getActionCommand().compareTo("R:down") == 0) { if (this.ScrollThread != null) { this.ScrollThread.politeStop(); return; } } else { if (paramActionEvent.getActionCommand().compareTo("P:up") == 0) { this.ScrollThread = new UtilityThread(50, this, getClass().getMethod("stepUp", null), false); this.ScrollThread.start(); return; } if (paramActionEvent.getActionCommand().compareTo("R:up") != 0) return; if (this.ScrollThread == null) return; this.ScrollThread.politeStop(); } return; } catch (NoSuchMethodException localNoSuchMethodException) { localNoSuchMethodException.printStackTrace(); System.err.println("PaletteSection: Some idiot programmer mistyped something in the Palette scrolling code."); } }
aeac5036-bb78-4721-a35f-e14756e9dc42
6
public GUIController(WorldFrame<T> parent, GridPanel disp, DisplayMap displayMap, ResourceBundle res) { resources = res; display = disp; parentFrame = parent; this.displayMap = displayMap; makeControls(); occupantClasses = new TreeSet<Class>(new Comparator<Class>() { public int compare(Class a, Class b) { return a.getName().compareTo(b.getName()); } }); World<T> world = parentFrame.getWorld(); Grid<T> gr = world.getGrid(); for (Location loc : gr.getOccupiedLocations()) addOccupant(gr.get(loc)); for (String name : world.getOccupantClasses()) try { occupantClasses.add(Class.forName(name)); } catch (Exception ex) { ex.printStackTrace(); } timer = new Timer(INITIAL_DELAY, new ActionListener() { public void actionPerformed(ActionEvent evt) { step(); } }); display.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent evt) { Grid<T> gr = parentFrame.getWorld().getGrid(); Location loc = display.locationForPoint(evt.getPoint()); if (loc != null && gr.isValid(loc) && !isRunning()) { display.setCurrentLocation(loc); locationClicked(); } } }); stop(); }
5303c212-a81a-40ee-b2a0-69efe8d8e45a
8
public static void main(String args[]){ int a = 0; while(a == 0){ int d = Integer.parseInt(JOptionPane.showInputDialog("Choose your decision:\n1 - Add a Girl\n2- Save to DB\n3- Load from DB\n4- List Items\n5- Exit")); if(d == 1){ String name = JOptionPane.showInputDialog("Input Name:"); String img = "images\\" + name + ".jpg"; String alt = JOptionPane.showInputDialog("Input character's alternate name:"); holder = new Girl(name, img, alt); insert(holder); } else if(d == 2){ try{ saveToFile(); }catch(Exception e){ System.out.println("Error in saving file"); } } else if(d == 3){ try{ loadFromFile(); }catch(Exception e){ System.out.println("Error from loading the file."); } } else if(d == 4){ listItem(); } else if(d == 5){ a = 1; } } }
ad2700c7-a13d-447d-ba92-b8cf2d914a5d
8
static void runFlowAnalyzes(OptFunctionNode fn, Node[] statementNodes) { int paramCount = fn.fnode.getParamCount(); int varCount = fn.fnode.getParamAndVarCount(); int[] varTypes = new int[varCount]; // If the variable is a parameter, it could have any type. for (int i = 0; i != paramCount; ++i) { varTypes[i] = Optimizer.AnyType; } // If the variable is from a "var" statement, its typeEvent will be set // when we see the setVar node. for (int i = paramCount; i != varCount; ++i) { varTypes[i] = Optimizer.NoType; } Block[] theBlocks = buildBlocks(statementNodes); if (DEBUG) { ++debug_blockCount; System.out.println("-------------------"+fn.fnode.getFunctionName()+" "+debug_blockCount+"--------"); System.out.println(toString(theBlocks, statementNodes)); } reachingDefDataFlow(fn, statementNodes, theBlocks, varTypes); typeFlow(fn, statementNodes, theBlocks, varTypes); if (DEBUG) { for (int i = 0; i < theBlocks.length; i++) { System.out.println("For block " + theBlocks[i].itsBlockID); theBlocks[i].printLiveOnEntrySet(fn); } System.out.println("Variable Table, size = " + varCount); for (int i = 0; i != varCount; i++) { System.out.println("["+i+"] type: "+varTypes[i]); } } for (int i = paramCount; i != varCount; i++) { if (varTypes[i] == Optimizer.NumberType) { fn.setIsNumberVar(i); } } }
c0c7ed58-a1ad-4070-b08c-3ccb7d791143
7
public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // this is simple... we parse out the [xx] bit first then compare to // the last line. String line = reader.readLine(); List<Double> list = new ArrayList<Double>(); while (line != null) { if (line.length() > 0 && line.charAt(0) == '[' && line.endsWith(";")) { // System.out.println("TREE:"+line); list.clear(); StringTokenizer st = new StringTokenizer(line.trim(), "[]"); st.nextToken(); String thisLine = st.nextToken(); // now we parse trees... only we don't really. We just // pull numbers after : pullNumbers(thisLine, list); } else if (!list.isEmpty()) { Collections.sort(list); for (double d : list) { System.out.print(d + "\t"); } System.out.println(); list.clear(); } line = reader.readLine(); } // System.out.println(count); } catch (Exception e) { e.printStackTrace(); } }
b2ec0690-2e09-44cb-9d14-470e25b87a34
2
private void loadFromFile(File f) throws ImageProcessingException, IOException { filename = f.getName(); filepath = f.getParent(); filesize = f.length(); filedate = f.lastModified(); Metadata metadata = ImageMetadataReader.readMetadata(f); Directory directory = metadata.getDirectory(ExifSubIFDDirectory.class); imagedate = directory .getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL).getTime(); directory = metadata.getDirectory(JpegDirectory.class); try { imagewidth = directory.getInt(JpegDirectory.TAG_JPEG_IMAGE_WIDTH); imageheight = directory.getInt(JpegDirectory.TAG_JPEG_IMAGE_HEIGHT); } catch (MetadataException e) { directory = metadata.getDirectory(ExifSubIFDDirectory.class); try { imagewidth = directory .getInt(ExifSubIFDDirectory.TAG_EXIF_IMAGE_WIDTH); imageheight = directory .getInt(ExifSubIFDDirectory.TAG_EXIF_IMAGE_HEIGHT); } catch (MetadataException e1) { // TODO Auto-generated catch block e.printStackTrace(); e1.printStackTrace(); } } }
72c83ec6-953a-4535-ad65-c04bb5cfd420
2
public synchronized void stop(HTSMsg msg, int clientId){ Subscription s = getSubscription((Long) msg.get("subscriptionId"), clientId); HTSPServerConnection c = monitor.getServerConnection(s.serverConnectionId); msg.put("subscriptionId", s.serverSubscriptionId); try { c.send(msg); } catch (IOException e) { try { monitor.getClient(clientId).unsubscribe((Long) msg.get("subscriptionId")); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } }
a9ffdd77-5840-4747-9a02-e2532beafe38
4
public static void main(String[] args) { System.out.println("Begin: RankSumNoReplacementSimulate"); int numberOfSamples = 100000; for( int n = 2; true; n++ ) { // Generate random rank sums RankSumNoReplacementSimulate rss = new RankSumNoReplacementSimulate(numberOfSamples, n); // Show mean / variance for all values for( int nt = 1; nt <= rss.n; nt++ ) { double mu = rss.mean(nt); double muSample = rss.sampleMean(nt); double muErr = (mu != 0 ? Math.abs(mu - muSample) / mu : 0); double sigmaSample = Math.sqrt(rss.sampleVariance(nt)); double sigma = Math.sqrt(rss.variance(nt)); double simgaErr = (sigma != 0 ? Math.abs(sigma - sigmaSample) / sigma : 0); System.out.println("N:" + n + "\tNT:" + nt + "\tmu:" + mu + "\tmuSample:" + muSample + "\terr%:" + muErr + "\t|\tsigma:" + sigma + "\tsigmaSample:" + sigmaSample + "\terr%:" + simgaErr); } } // System.out.println("End: RankSumNoReplacementSimulate"); }
a80c2d64-a114-492f-8fe0-11e7a7bf2344
1
public boolean isBombed(int x, int y) { return (sea[x][y] == HIT || sea[x][y] == MISS); }
2f18f09e-c983-4ae8-9005-1cbe50f08451
4
public void saveTileSet() { if (canvas.getMap().getTileSet().getPath() == null) { int returnVal = chooser.showSaveDialog(canvas); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); File imagesDir = new File(file.getParent() + File.separator + "images"); imagesDir.mkdir(); copyImagesToImageDir(canvas.getMap().getTileSet().getTiles(), imagesDir); try { fmanager.saveTileSet(file, canvas.getMap().getTileSet()); } catch (Exception e) { JOptionPane.showMessageDialog(mainUserInterface.mainFrame, "Saving tileset failed: " + e.getMessage()); } } } else { File file = new File(canvas.getMap().getTileSet().getPath()); try { fmanager.saveTileSet(file, canvas.getMap().getTileSet()); File imagesDir = new File(file.getParent() + File.separator + "images"); imagesDir.mkdir(); copyImagesToImageDir(canvas.getMap().getTileSet().getTiles(), imagesDir); } catch (Exception e) { JOptionPane.showMessageDialog(mainUserInterface.mainFrame, "Saving tileSet failed: " + e.getMessage()); } } }
d5f2407d-1194-4616-a66e-ac5974785990
5
public static void main(String[] args) { ServerSocket server_sock = null; Socket client_sock = null; // Initialize the server socket MsgDumperCmnDef.WriteDebugSyslog(__FUNC__(), __LINE__(), "Initialize the server socket in MsgDumper daemon..."); try { server_sock = new ServerSocket(MsgDumperCmnDef.SERVER_PORT_NO); } catch (IOException e) { MsgDumperCmnDef.WriteErrorFormatSyslog(__FUNC__(), __LINE__(), "ServerSocket() fail, due to: %s", e.toString()); System.exit(1); } while (true) { MsgDumperCmnDef.WriteDebugSyslog(__FUNC__(), __LINE__(), "Server waits for client's request......"); try { client_sock = server_sock.accept(); } catch (IOException e) { MsgDumperCmnDef.WriteErrorFormatSyslog(__FUNC__(), __LINE__(), "accept() fail, due to: %s", e.toString()); break; } MsgDumperCmnDef.WriteDebugFormatSyslog(__FUNC__(), __LINE__(), "Got a connection request from the remote[%s:%d]......", client_sock.getInetAddress(), client_sock.getPort()); // Create a worker thread to receive the data from the remote site MsgDumperCmnDef.WriteDebugFormatSyslog(__FUNC__(), __LINE__(), "Create another thread to receive the data from the remote[%s]", client_sock.getInetAddress()); Thread client_socket_thread = new Thread(new MsgDumperDaemon(client_sock)); client_socket_thread.start(); } if (server_sock != null) { try { server_sock.close(); server_sock = null; } catch (IOException e) {} } }
7edef268-c469-49ed-8dcd-a3489571076f
4
@Override public boolean join(String n) { boolean accepted = false; try { m_connectionSocket = new Socket(K.ADDRESS_TCP, K.TCP_SERVER_PORT); ObjectOutputStream os = new ObjectOutputStream( m_connectionSocket.getOutputStream()); // Sending join message to the server ... Join join = new Join(n); System.out.println("Sending message to server."); os.writeObject(join); os.flush(); ObjectInputStream is = new ObjectInputStream( m_connectionSocket.getInputStream()); // ... and wait for the reply. Object o = is.readObject(); System.out.println("Server has replied."); // Check server reply if (o instanceof Join) { Join msg = (Join) o; accepted = msg.isAccepted(); } m_connectionSocket.close(); // Check the server reply ... if (accepted) { System.out.println("Connected"); // ... join the multicast group m_multicastSocket = new MulticastSocket(K.UDP_CLIENT_PORT); m_multicastSocket.joinGroup(InetAddress .getByName(K.ADDRESS_UDP)); } else { System.out.println("Connection refused"); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return accepted; }
c2df557a-5f25-4724-9c25-36f9273f5514
7
public static void driveStraightGyro(double power) { double leftMod = 1.0; double rightMod = 1.0; if (!newGyroReadingDriveStraight) { initGyro = gyro.getAngle(); newGyroReadingDriveStraight = true; } if (power < 0) { if ((gyro.getAngle() - initGyro) < -5) { leftMod*=Constants.DT_GYRO_FAST_MOD; rightMod*=Constants.DT_GYRO_SLOW_MOD; } else if ((gyro.getAngle() - initGyro) > 5) { rightMod*=Constants.DT_GYRO_FAST_MOD; leftMod*=Constants.DT_GYRO_SLOW_MOD; } } else if (power < 0) { if ((gyro.getAngle() - initGyro) < -5) { leftMod*=Constants.DT_GYRO_SLOW_MOD; rightMod*=Constants.DT_GYRO_FAST_MOD; } else if ((gyro.getAngle() - initGyro) > 5) { rightMod*=Constants.DT_GYRO_SLOW_MOD; leftMod*=Constants.DT_GYRO_FAST_MOD; } } drive((power * leftMod), (power * rightMod)); }
355a773d-1b7f-4757-8e2d-4c8ab747d122
1
public CycLeaseManager(final CycAccess cycAccess) { //// Preconditions if (cycAccess == null) { throw new InvalidParameterException("cycAccess must not be null"); } logger = Logger.getLogger("org.opencyc.api.CycLeaseManager"); this.cycAccess = cycAccess; }
3b22f920-45ad-42a6-a235-7b36168d858c
8
@Override public void close() throws IOException { if(os != null){ try{ os.flush(); os.close(); os = null; } catch (IOException e ){ e.printStackTrace(); } } if(fs != null){ try{ fs.close(); fs = null; } catch (IOException e ){ e.printStackTrace(); } } if(is != null){ try{ is.close(); is = null; } catch (IOException e ){ e.printStackTrace(); } } if(fi != null){ try{ fi.close(); fi = null; } catch (IOException e ){ e.printStackTrace(); } } connectionInStatus = false; connectionOutStatus = false; }
5fee38e5-d687-4d13-ad0a-0ecc929928c6
0
public void setProducto(Producto producto) { this.producto = producto; }
4b1514f3-3800-4a6c-8b1e-d668aaa0436c
9
public DoubleVectorIndividual createIndividual( final EvolutionState state, int subpop, int index, int thread ) { Individual[] inds = state.population.subpops[subpop].individuals; DoubleVectorIndividual v = (DoubleVectorIndividual)(inds[index].clone()); do { // select three indexes different from each other and from that of the current parent int r0, r1, r2; do { r0 = state.random[thread].nextInt(inds.length); } while( r0 == index ); do { r1 = state.random[thread].nextInt(inds.length); } while( r1 == r0 || r1 == index ); do { r2 = state.random[thread].nextInt(inds.length); } while( r2 == r1 || r2 == r0 || r2 == index ); DoubleVectorIndividual g0 = (DoubleVectorIndividual)(inds[r0]); DoubleVectorIndividual g1 = (DoubleVectorIndividual)(inds[r1]); DoubleVectorIndividual g2 = (DoubleVectorIndividual)(inds[r2]); for(int i = 0; i < v.genome.length; i++) if (state.random[thread].nextBoolean(PF)) v.genome[i] = g0.genome[i] + F * (g1.genome[i] - g2.genome[i]); else v.genome[i] = g0.genome[i] + 0.5 * (F+1) * (g1.genome[i] + g2.genome[i] - 2 * g0.genome[i]); } while(!valid(v)); return v; // no crossover is performed }
60fe071c-2496-4bc5-8d03-f971ede9faf7
0
protected PropertySearchResults(PropertyTree firstNode) { results=new ArrayList<Result>(1); // size 1; guessing there will not be any conflicting values results.add(new Result(firstNode)); sorted=true; totalNodes=1; }
7edefc80-b392-4c51-83cb-4dffc469ec5c
1
public void visit_lxor(final Instruction inst) { stackHeight -= 4; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } stackHeight += 2; }
dbe05a3d-caa8-4322-bd75-8fb7d1137517
9
public SimpleProperty(Class clazz, String name) { this.name = name; Class[] readParams = {}; readMethod = Reflection.getMethod(clazz, "get" + name, readParams); if (readMethod == null) { readMethod = Reflection.getMethod(clazz, "is" + name, readParams); } if (readMethod == null) { String fieldName = Character.toLowerCase(name.charAt(0)) + name.substring(1); field = Reflection.getField(clazz, fieldName); if (field == null) { // throw new RuntimeException("Missing Method: get" + name + " " + fieldName + " " + clazz); } else { field.setAccessible(true); type = field.getType(); } } else { type = readMethod.getReturnType(); } if (type == null && writeMethod != null) { type = writeMethod.getReturnType(); } Class[] writeParams = {type}; writeMethod = Reflection.getMethod(clazz, "set" + name, writeParams); if (writeMethod == null && field == null) { // throw new RuntimeException("Missing Method: set" + name); } if (type != null) { isBoolean = type.equals(Boolean.class) || type.equals(boolean.class); } }
c93d5ee6-c824-4af7-a825-367aa3742796
3
public int getNumberOfFreeCells(){ int sum=0; for(int i=0;i<getX();i++){ for(int u=0;u<getY();u++){ if(this.cells[i][u]==0){ sum++; } } } return sum; }
5d9dad51-29c5-4575-8cc9-ad79851d17fd
7
public ConstructorWrapper findByArgumentTypes(Class<?>... types) { for (ConstructorWrapper wrapper : this.constructorWrappers) { List<ParameterWrapper> parameters = wrapper.parameters(); if (parameters.size() == types.length) { boolean valid = true; for (int i = 0, max = parameters.size(); i < max && valid; i++) { if (parameters.get(i).getType() != types[i]) { valid = false;; } } if (valid) { return wrapper; } } } return null; }
830e0cdb-029f-4267-ad62-90abb6b20b4a
8
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); int testCases = Integer.parseInt(in.readLine().trim()); for (int t = 0; t < testCases; t++) { int[] nm = readInts(in.readLine()); int n = nm[0], m = nm[1]; for (int i = 0; i < m; i++) { int[] uvw = readInts(in.readLine()); int u = uvw[0] - 1, v = uvw[1] - 1, w = uvw[2]; if (u > v) { int aux = u; u = v; v = aux; } arista[i] = new Edge(u, v, w); } E = m; V = n; Arrays.sort(arista, 0, E); long a = KruskalMST(), b = Long.MAX_VALUE; nodes = n; nl = (int) (Math.log(nodes) / Math.log(2)) + 1; for (int i = 0; i < n; i++) G[i] = new ArrayList<>(); for (int i = 0; i < V - 1; i++) { G[MST[i].origen].add(new Edge(MST[i].origen, MST[i].destino, MST[i].peso)); G[MST[i].destino].add(new Edge(MST[i].destino, MST[i].origen, MST[i].peso)); } bfs(0); process(); for (int i = 0; i < E; i++) if (!used[i]) b = Math.min(b, a + arista[i].peso - LCA(arista[i].origen, arista[i].destino)); if (b == Long.MAX_VALUE) b = a; out.append(a + " " + b + "\n"); } System.out.print(out); }
4449e273-9444-42e1-bb50-31f40c2f8307
8
private void mrXMoveLog() { URL busIcon = this.getClass().getResource("Bus.png"); URL taxiIcon = this.getClass().getResource("Taxi.png"); URL tubeIcon = this.getClass().getResource("Underground.png"); URL doubleIcon = this.getClass().getResource("DoubleMove.png"); URL secretIcon = this.getClass().getResource("SecretMove.png"); //makes a tabbed pane for the Mr X move log JTabbedPane moveLog = new JTabbedPane(); //sets location of the Mr X location in relation to the map and sets the size moveLog.setLocation((int) (resizedImageDimensions.getWidth() + 10), 480); moveLog.setSize((int) (window.getContentPane().getWidth() - resizedImageDimensions.getWidth() - 20), (int) (350 * imageScale())); //creates a movesUsed JPanel and sets the size JPanel movesUsed = new JPanel(); movesUsed.setLayout(null); movesUsed.setSize((int) (window.getContentPane().getWidth() - resizedImageDimensions.getWidth() - 20), (int) (350 * imageScale())); //gets the list of used moves ArrayList<Initialisable.TicketType> usedMoves = (ArrayList<Initialisable.TicketType>) visualisable.getMoveList(0); //j acts as a counter variable here //these variables are used to make sure that when the number of moves in the log goes over the panel height, that a new column is started int temp = 0; int x = 0; int j = 0; for(int i = 0; i < usedMoves.size(); i++) { //goes through the list of used moves and adds a new label for each one to the JPanel String type = null; URL iconToDisplay = null; if(usedMoves.get(i) == Initialisable.TicketType.Bus) { type = "Bus"; iconToDisplay = busIcon; } else if (usedMoves.get(i) == Initialisable.TicketType.Taxi) { type = "Taxi"; iconToDisplay = taxiIcon; } else if (usedMoves.get(i) == Initialisable.TicketType.Underground){ type = "Underground"; iconToDisplay = tubeIcon; } else if (usedMoves.get(i) == Initialisable.TicketType.DoubleMove){ type = "Double move"; iconToDisplay = doubleIcon; } else if (usedMoves.get(i) == Initialisable.TicketType.SecretMove) { type = "Secret move"; iconToDisplay = secretIcon; } JLabel move = new JLabel("Move " + String.valueOf(i + 1) + ": " + type); move.setIcon(new ImageIcon(iconToDisplay)); move.setForeground(Color.LIGHT_GRAY); move.setOpaque(true); if((5 + (30 * (i - temp))) > 300 * imageScale()) { temp = i; if(j == 0) x = (int) (window.getContentPane().getWidth() - resizedImageDimensions.getWidth() - 20) / 3; else{ x = (int) (((window.getContentPane().getWidth() - resizedImageDimensions.getWidth() - 20) / 3) + ((window.getContentPane().getWidth() - resizedImageDimensions.getWidth() - 20) / 3)); } j++; } move.setSize(200, 20); move.setLocation(x, 5 + (20 * (i - temp))); move.setVisible(true); movesUsed.add(move); } movesUsed.setBackground(Color.DARK_GRAY); movesUsed.setOpaque(true); //sets the JPanel to be visible movesUsed.setVisible(true); //adds the JPanel to the tabbed pane and sets it to be visible moveLog.add("Mr X Move Log", movesUsed); moveLog.setBackground(Color.LIGHT_GRAY); moveLog.setOpaque(true); moveLog.setVisible(true); //add the tabbed pane to the layered pane and sets the layer to 1 layeredPane.add(moveLog); layeredPane.setLayer(moveLog, 1); }
cdd42018-a46e-41ee-bd26-d17060d3c467
5
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Product product = (Product) o; return number == product.number && !(name != null ? !name.equals(product.name) : product.name != null); }
c5476614-ba14-429f-818d-9affd307ff26
7
private void setWidth() { float missingWidth = 0; float ascent = 0.0f; float descent = 0.0f; if (fontDescriptor != null) { if (fontDescriptor.getMissingWidth() > 0) { missingWidth = fontDescriptor.getMissingWidth() / 1000f; ascent = fontDescriptor.getAscent() / 1000f; descent = fontDescriptor.getDescent() / 1000f; } } if (widths != null) { float[] newWidth = new float[256 - firstchar]; for (int i = 0, max = widths.size(); i < max; i++) { if (widths.elementAt(i) != null) { newWidth[i] = ((Number) widths.elementAt(i)).floatValue() / 1000f; } } font = font.deriveFont(newWidth, firstchar, missingWidth, ascent, descent, cMap); } else if (cidWidths != null) { // cidWidth are already scaled correct to .001 font = font.deriveFont(cidWidths, firstchar, missingWidth, ascent, descent, null); } else if (afm != null) { font = font.deriveFont(afm.getWidths(), firstchar, missingWidth, ascent, descent, cMap); } }
70f7de31-9335-4e62-a701-c9a39d7deabb
9
public void checkParserState( XmlPullParser xpp, int depth, int type, String name, String text, boolean isEmpty, int attribCount ) throws XmlPullParserException, IOException { assertTrue("line number must be -1 or >= 1 not "+xpp.getLineNumber(), xpp.getLineNumber() == -1 || xpp.getLineNumber() >= 1); assertTrue("column number must be -1 or >= 0 not "+xpp.getColumnNumber(), xpp.getColumnNumber() == -1 || xpp.getColumnNumber() >= 0); assertEquals("PROCESS_NAMESPACES", false, xpp.getFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES)); assertEquals("TYPES[getType()]", XmlPullParser.TYPES[type], XmlPullParser.TYPES[xpp.getEventType()]); assertEquals("getType()", type, xpp.getEventType()); assertEquals("getDepth()", depth, xpp.getDepth()); assertEquals("getPrefix()", null, xpp.getPrefix()); assertEquals("getNamespacesCount(getDepth())", 0, xpp.getNamespaceCount(depth)); if(xpp.getEventType() == XmlPullParser.START_TAG || xpp.getEventType() == XmlPullParser.END_TAG) { assertEquals("getNamespace()", "", xpp.getNamespace()); } else { assertEquals("getNamespace()", null, xpp.getNamespace()); } assertEquals("getName()", name, xpp.getName()); if(xpp.getEventType() != XmlPullParser.START_TAG && xpp.getEventType() != XmlPullParser.END_TAG) { assertEquals("getText()", printable(text), printable(xpp.getText())); int [] holderForStartAndLength = new int[2]; char[] buf = xpp.getTextCharacters(holderForStartAndLength); if(buf != null) { String s = new String(buf, holderForStartAndLength[0], holderForStartAndLength[1]); assertEquals("getText(holder)", printable(text), printable(s)); } else { assertEquals("getTextCharacters()", null, text); } } if(type == XmlPullParser.START_TAG) { assertEquals("isEmptyElementTag()", isEmpty, xpp.isEmptyElementTag()); } else { try { xpp.isEmptyElementTag(); fail("isEmptyElementTag() must throw exception if parser not on START_TAG"); } catch(XmlPullParserException ex) { } } assertEquals("getAttributeCount()", attribCount, xpp.getAttributeCount()); }
d8aebbe6-8058-4915-85f1-03e2f7a2f631
6
public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; }
fd48c46c-e08f-47e5-b1b3-65521de8e64e
9
public void draw(UShape ushape, double x, double y, ColorMapper mapper, UParam param, Graphics2D g2d) { final UText shape = (UText) ushape; final FontConfiguration fontConfiguration = shape.getFontConfiguration(); final UFont font = fontConfiguration.getFont(); final Dimension2D dimBack = calculateDimension(StringBounderUtils.asStringBounder(g2d), font, shape.getText()); if (fontConfiguration.containsStyle(FontStyle.BACKCOLOR)) { final Color extended = mapper.getMappedColor(fontConfiguration.getExtendedColor()); if (extended != null) { g2d.setColor(extended); g2d.setBackground(extended); g2d.fill(new Rectangle2D.Double(x, y - dimBack.getHeight() + 1.5, dimBack.getWidth(), dimBack .getHeight())); } } visible.ensureVisible(x, y - dimBack.getHeight() + 1.5); visible.ensureVisible(x + dimBack.getWidth(), y + 1.5); g2d.setFont(font.getFont()); g2d.setColor(mapper.getMappedColor(fontConfiguration.getColor())); g2d.drawString(shape.getText(), (float) x, (float) y); if (fontConfiguration.containsStyle(FontStyle.UNDERLINE)) { final HtmlColor extended = fontConfiguration.getExtendedColor(); if (extended != null) { g2d.setColor(mapper.getMappedColor(extended)); } final Dimension2D dim = calculateDimension(StringBounderUtils.asStringBounder(g2d), font, shape.getText()); final int ypos = (int) (y + 2.5); g2d.setStroke(new BasicStroke((float) 1.3)); g2d.drawLine((int) x, ypos, (int) (x + dim.getWidth()), ypos); g2d.setStroke(new BasicStroke()); } if (fontConfiguration.containsStyle(FontStyle.WAVE)) { final Dimension2D dim = calculateDimension(StringBounderUtils.asStringBounder(g2d), font, shape.getText()); final int ypos = (int) (y + 2.5) - 1; final HtmlColor extended = fontConfiguration.getExtendedColor(); if (extended != null) { g2d.setColor(mapper.getMappedColor(extended)); } for (int i = (int) x; i < x + dim.getWidth() - 5; i += 6) { g2d.drawLine(i, ypos - 0, i + 3, ypos + 1); g2d.drawLine(i + 3, ypos + 1, i + 6, ypos - 0); } } if (fontConfiguration.containsStyle(FontStyle.STRIKE)) { final Dimension2D dim = calculateDimension(StringBounderUtils.asStringBounder(g2d), font, shape.getText()); final FontMetrics fm = g2d.getFontMetrics(font.getFont()); final int ypos = (int) (y - fm.getDescent() - 0.5); final HtmlColor extended = fontConfiguration.getExtendedColor(); if (extended != null) { g2d.setColor(mapper.getMappedColor(extended)); } g2d.setStroke(new BasicStroke((float) 1.5)); g2d.drawLine((int) x, ypos, (int) (x + dim.getWidth()), ypos); g2d.setStroke(new BasicStroke()); } }
ebdad684-5da4-4190-ad4f-2877f34438a4
6
static private Token jj_consume_token(int kind) throws ParseException { Token oldToken; if ((oldToken = token).next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; if (token.kind == kind) { jj_gen++; if (++jj_gc > 100) { jj_gc = 0; for (int i = 0; i < jj_2_rtns.length; i++) { JJCalls c = jj_2_rtns[i]; while (c != null) { if (c.gen < jj_gen) c.first = null; c = c.next; } } } return token; } token = oldToken; jj_kind = kind; throw generateParseException(); }
adb6b3d2-e988-448f-83e6-4b9065a5af65
2
@Test public void testDatabasePool() throws Exception { //test normal operation DataConnectionPool dcp = new DataConnectionPool(1, driver, database, login, password); dcp.getConnectionWrapper().commitAndDiscard(); dcp.getConnectionWrapper().rollbackAndDiscard(); //get several connection wrappers ConnectionWrapper cw1 = dcp.getConnectionWrapper(); ConnectionWrapper cw2 = dcp.getConnectionWrapper(); ConnectionWrapper cw3 = dcp.getConnectionWrapper(); assertNotNull(cw1); assertNotNull(cw2); assertNotNull(cw3); assertTrue(cw1.isTaken()); cw1.discard(); assertFalse(cw1.isTaken()); dcp.cleanUp(); assertTrue(cw1.isTaken()); //test exceptions boolean thrown = false; try { dcp = new DataConnectionPool(1,driver,null,login,password); dcp.cleanUp(); } catch(SQLException e) { thrown = true; } assertTrue("No exception thrown on null database.",thrown); thrown = false; try { dcp = new DataConnectionPool(1,"completely fake driver",database,login,password); dcp.cleanUp(); } catch(SQLException e) { thrown = true; } assertTrue("No exception thrown on fake database.",thrown); }
00b6d05b-4a7c-46fe-a410-1d9e39225131
7
public void transform(int form){ // TODO change form based upon input from user if(currentForm!=4){ timeSinceTransform = 0; if(form == 0){ if (fireFormEnabled){ currentForm = 0; fireOrbs = 0; currentFormDuration = fireFormDuration; fireFormEnabled = false; } } else if (form == 1){ if (lightningFormEnabled){ currentForm = 1; lightningOrbs = 0; currentFormDuration = lightningFormDuration; lightningFormEnabled = false; } } else if (form == 2){ if (windFormEnabled){ currentForm = 2; windOrbs = 0; currentFormDuration = windFormDuration; windFormEnabled = false; speed += windFormVelocityBoost; } } } }
ce4bfab0-a39d-4e65-bf51-841cd35ef74b
9
@Override public String toString() { if (type == NUM) { return "NUM: " + value; } else if (type == CMD) { return "CMD: " + name; } else if (type == UNK) { return "UNK"; } else if (type == EOF) { return "EOF"; } else if (type == NAME) { return "NAME: " + name; } else if (type == CMD) { return "CMD: " + name; } else if (type == STR) { return "STR: (" + name; } else if (type == ARYB) { return "ARY ["; } else if (type == ARYE) { return "ARY ]"; } else { return "some kind of brace (" + type + ")"; } }
fe0fa5da-b658-4938-8906-0c76f1c272ed
7
@Override public void keyTyped(KeyEvent e) { if (consoleInputField != null) { /* User can enter backspaces. */ if (e.getKeyChar() == (char) 8 && consoleInputField.getCmd().length() > 0) { String nev = consoleInputField.getCmd(); nev = nev.substring(0, nev.length() - 1); consoleInputField.setCmd(nev); } else { consoleInputField.appendCmd("" + e.getKeyChar()); } } /* * If game is paused, see if a key was pressed * If it was, unpause (Well technically restart) the game */ else if (isWaitingForKeyPress()) { if (pressCount == 1) { waitForKeyPressEnd(); pressCount = 0; } else { pressCount++; } } /* * If escape is pressed, exit the game unless the * console is open. If it is, close the console */ if (e.getKeyChar() == 27) { if (consoleInputField != null) { removeGui(consoleInputField); consoleInputField = null; } else { System.exit(0); } } }
44c14c7e-33d1-4ee9-8a10-b9ff98c8226c
0
public static <T> T[] concat(T[] first, T[] second) { T[] result = Arrays.copyOf(first, first.length + second.length); System.arraycopy(second, 0, result, first.length, second.length); return result; }
1affe964-15d0-43f0-b21b-faacfa942250
4
private void checkForRemovedMarkers() { markersToRemove.clear(); for (Node node : pane.getChildren()) { if (node instanceof Marker) { if (getSkinnable().getMarkers().keySet().contains(node)) continue; node.setManaged(false); node.removeEventHandler(MouseEvent.MOUSE_PRESSED, mouseEventHandler); node.removeEventHandler(MouseEvent.MOUSE_DRAGGED, mouseEventHandler); node.removeEventHandler(MouseEvent.MOUSE_RELEASED, mouseEventHandler); node.removeEventHandler(TouchEvent.TOUCH_PRESSED, touchEventHandler); node.removeEventHandler(TouchEvent.TOUCH_MOVED, touchEventHandler); node.removeEventHandler(TouchEvent.TOUCH_RELEASED, touchEventHandler); markersToRemove.add(node); } } for (Node node : markersToRemove) pane.getChildren().remove(node); }
b0e20b7b-5a26-4bc6-97e1-19d936b7f6be
8
private boolean r_prelude() { int among_var; int v_1; // repeat, line 36 replab0: while(true) { v_1 = cursor; lab1: do { // (, line 36 // [, line 37 bra = cursor; // substring, line 37 among_var = find_among(a_0, 3); if (among_var == 0) { break lab1; } // ], line 37 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 38 // <-, line 38 slice_from("a~"); break; case 2: // (, line 39 // <-, line 39 slice_from("o~"); break; case 3: // (, line 40 // next, line 40 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_1; break replab0; } return true; }
e5da042e-f712-473d-a759-fc938aafee0c
3
public int search(String docs) { int N = docs.length(); long docsHash = hash(docs, M); if (docsHash == patternHash) return 0; for (int i = M; i < N; i++) { // remove leading digit docsHash = (docsHash + Q - RM * docs.charAt(i-M) % Q) % Q; // add trailing digit docsHash = (docsHash * R + docs.charAt(i)) % Q; // match if (patternHash == docsHash) return i - M + 1; } return N; }
c309c5b6-fc1b-43bb-8d26-d330b60e8b93
2
public static void mergeSort(int x[], int y[]) { int z[] = new int[x.length + y.length]; System.out.print("First Array :\t"); for (int i = 0; i < x.length; i++) { System.out.print(x[i] + " "); z[i] = x[i]; } System.out.print("\nSecond Array :\t"); for (int i = x.length, j = 0; i < z.length; i++, j++) { System.out.print(y[j] + " "); z[i] = y[j]; } System.out.print("\n"); ArrayDemo.sort(z); }
7cf10909-c611-4f97-824e-5b82a4f4fb16
3
int opcode(int op) { if (op == IFNULL) return IFNONNULL; else if (op == IFNONNULL) return IFNULL; else { if (((op - IFEQ) & 1) == 0) return op + 1; else return op - 1; } }
6d7fa4bc-3ce5-4f5e-b98f-035574c2c73b
3
public static void main(String[] args) { EdgeWeightedDigraph G = new EdgeWeightedDigraph(new In(args[0])); int s = Integer.parseInt(args[1]); AcyclicSP sp = new AcyclicSP(G, s); for (int t = 0; t < G.V(); t++) { System.out.print(s + " to " + t + " (" + String.format("%.2f", sp.distTo(t)) + ") : "); if (sp.hasPathTo(t)) for (WeightedDirectedEdge e : sp.pathTo(t)) System.out.print(e + " "); System.out.println(); } }
643d8f0d-d1a9-447c-8aa7-415c2b070c06
6
public void MoonCheck() { CopyOnWriteArrayList<GameObject> objects = state.getMyObjects(); for (int j = 0; j < objects.size(); j++) { for (int i = 0; i < objects.size(); i++) { CollisionResults results = new CollisionResults(); Vector3f opos = objects.get(j).getPosition(); Vector3f odir = objects.get(j).getDirection(); Ray ray = new Ray(opos, odir); rootNode.collideWith(ray, results); for (int k = 0; k < results.size(); k++) { float dist = results.getCollision(k).getDistance(); if (dist < 2 && objects.get(j).type == "beam") { Geometry target = results.getClosestCollision() .getGeometry(); if (target.getName().equals("Moon")) { Moon m1 = new Moon(new sharedstate.Planet(objects .get(i).getSize() / 2), assetManager, earth); Moon m2 = new Moon(new sharedstate.Planet(objects .get(i).getSize() / 2), assetManager, earth); m1.setRotation(); m2.setRotation(); objects.remove(i); return; } } } } } }
9bd6164c-e627-4052-8306-286b26391cb6
7
public void write(int address, int data) { if (this.cache.contains(address)) { this.cache.write(address, data); return; } else { for (int i = 0; i < this.history.length; i++) { if (this.history[i] == address) { // conflict miss int mode = Integer.valueOf(this.cache.getMode(), 2); if (mode < 8) mode += 4; this.cache.setMode(Integer.toBinaryString(mode)); System.out.println("Changing mode to " + Integer.toBinaryString(mode)); this.cache.write(address, data); return; } } //not found so It is first hit miss or capacity miss int mode = Integer.valueOf(this.cache.getMode(), 2); if (mode > 3) mode -= 3; else if (mode < 3) mode++; String newMode = Integer.toBinaryString(mode); while (newMode.length() < 4) newMode = '0' + newMode; this.cache.setMode(newMode); System.out.println("Changing mode to " + newMode); this.cache.write(address,data); return; } }
756ad8e0-ffd0-4028-b325-ae32dbf45b05
4
public static void main(String[] args) { String name = JOptionPane.showInputDialog("Please enter your name"); if (name == null) return; String address = JOptionPane .showInputDialog("Please enter the server address"); if (address == null) return; int port = Integer.parseInt(JOptionPane .showInputDialog("Please enter the portnumber")); if (port == 0) return; Socket s; try { s = new Socket(address, port); InitiateConnectionClient init = new InitiateConnectionClient(s, name); long rndSeed = init.getRndSeed(); String opponentName = init.getOpponentName(); long opponentAttackRandomSeed = opponentName.hashCode(); long localAttackRandomSeed = name.hashCode(); Game local = new Game(26, 10, rndSeed, localAttackRandomSeed); Game opponent = new Game(26, 10, rndSeed, opponentAttackRandomSeed); Network network = new Network(s, local, opponent); new Thread(network).start(); KeyListener keyListener = new KeyListener(local, network); new TetrisTimer(keyListener, 500); new TetrisGui(name, opponentName, local, opponent, keyListener); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Could not connect to " + address + ":" + port + ", quitting..."); } }
dd40aa5c-1965-456e-98ea-347b5f96adb0
2
public void renderEffects(){ for (ArrayList<GameObject> effect: effects) { for (GameObject gameObject : effect) { gameObject.render(); } } }
f3cf1033-aad2-480a-807f-0816783387c5
5
public static void main(String[] args) { /** Hand hand1 = new Rock() ; Hand hand2 = new Paper() ; Hand hand3 = new Scissors() ; System.out.println(hand1 + " beats " + hand1 + "? " + hand1.beats(hand1)) ; System.out.println(hand1 + " beats " + hand2 + "? " + hand1.beats(hand2)) ; System.out.println(hand1 + " beats " + hand3 + "? " + hand1.beats(hand3)) ; System.out.println(hand2 + " beats " + hand1 + "? " + hand2.beats(hand1)) ; System.out.println(hand2 + " beats " + hand2 + "? " + hand2.beats(hand2)) ; System.out.println(hand2 + " beats " + hand3 + "? " + hand2.beats(hand3)) ; System.out.println(hand3 + " beats " + hand1 + "? " + hand3.beats(hand1)) ; System.out.println(hand3 + " beats " + hand2 + "? " + hand3.beats(hand2)) ; System.out.println(hand3 + " beats " + hand3 + "? " + hand3.beats(hand3)) ; */ int input_player = 1; while(input_player != 0){ System.out.println("Enter 1 for Rock"); System.out.println("Enter 2 for Paper"); System.out.println("Enter 3 for Scissors"); System.out.println("Enter 4 for Lizard"); System.out.println("Enter 5 for Spock"); System.out.println("Enter 0 to Quit"); Scanner in = new Scanner(System.in); try{ input_player = in.nextInt(); } catch (java.util.InputMismatchException e){ System.err.println(e+"\n Please enter a number \n"); continue; } Hand hand_player = FuchimiGameRulesTest.toHand(input_player); Hand hand_computer = FuchimiGameRulesTest.toHand((int) (Math.random() * (6-1) + 1)); if(input_player == 0){ System.out.println("Quit Game \n"); break; } else { System.out.println("You chose "+hand_player); System.out.println("Computer chose "+hand_computer); if(hand_player.beats(hand_computer) == null){ System.out.println("Your hand "+ hand_player + " equals "+hand_computer+"\n"); } else if(hand_player.beats(hand_computer)){ System.out.println("You won"); System.out.println("Your hand "+ hand_player + " beats "+hand_computer+"\n"); } else { System.out.println("You lost"); System.out.println("Your hand "+ hand_player + " is beaten by "+hand_computer+"\n"); } } } }
4d64d898-b9d8-4184-a3d9-f4ee7d7fccdb
0
public static boolean isCglibProxy(Object object) { return SpringClassUtils.isCglibProxyClass(object.getClass()); }
42107d9a-c3dd-49c4-9d43-4d4f6a18039a
2
@Override public void setPlayerToTradeWith(int playerIndex) { receiverIndex = playerIndex; if(receiverIndex > -1 && checkForValidTradeValues()) { getTradeOverlay().setTradeEnabled(true); getTradeOverlay().setStateMessage("Trade!"); } else { getTradeOverlay().setTradeEnabled(false); getTradeOverlay().setStateMessage("select a player"); } }
d18c6843-7792-4ad1-ae92-c7d12e5c0f09
5
public void watch( Source source ) { // make sure the source exists: if( source == null ) return; // make sure we aren't already watching this source: if( streamingSources.contains( source ) ) return; ListIterator<Source> iter; Source src; // Make sure noone else is accessing the list of sources: synchronized( listLock ) { // Any currently watched source which is null or playing on the // same channel as the new source should be stopped and removed // from the list. iter = streamingSources.listIterator(); while( iter.hasNext() ) { src = iter.next(); if( src == null ) { iter.remove(); } else if( source.channel == src.channel ) { src.stop(); iter.remove(); } } // Add the new source to the list: streamingSources.add( source ); } }
8bc3d1ac-201a-4737-8c4b-a5baea63c59e
9
private void setSettings() { this.setBorder(new Border() { @Override public Insets getBorderInsets(Component c) { return new Insets(5, 7, 5, 7); } @Override public boolean isBorderOpaque() { return false; } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { if (HintArea.this.isFocusOwner()) { g.setColor(new Color(0x6d96be)); g.drawRect(x, y, width--, height--); } else { g.setColor(new Color(0xa2a2a2)); g.drawRect(x, y, width--, height--); } g.setColor(new Color(0xd0d0d0)); g.drawRect(++x, ++y, --width, --height); } }); this.setWrapStyleWord(true); this.setLineWrap(true); this.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent fe) { if (HintArea.this.selectAll) { HintArea.this.selectAll(); } } @Override public void focusLost(FocusEvent fe) { if (HintArea.this.selectAll) { HintArea.this.setCaretPosition(0); } } }); this.addKeyListener(new KeyListener() { private final int BACKSPACE = 8; private HintArea me = HintArea.this; @Override public void keyPressed(KeyEvent e) { boolean meta = (e.getModifiers() & ActionEvent.META_MASK) == ActionEvent.META_MASK || (e.getModifiers() & ActionEvent.ALT_MASK) == ActionEvent.ALT_MASK; switch (e.getKeyCode()) { case BACKSPACE: if (meta) { int caretPosition = this.me.getCaretPosition(); int startPos; String text = this.me.getText(); char c; for (startPos = caretPosition - 1; startPos > 0; startPos--) { if ((c = text.charAt(startPos)) == '\r' || c == '\n') { break; } } this.me.setText(text.substring(0, startPos) + text.substring(caretPosition, text.length())); this.me.setCaretPosition(startPos); } break; } HintArea.this.layer.repaint(); } @Override public void keyReleased(KeyEvent e) {} @Override public void keyTyped(KeyEvent e) {} }); }
ef68d08b-22af-4cbc-bd50-b8da8f449ad9
4
public void printTree(treeNode rootNode, int orderIndex) { if (rootNode != null) { // System.out.println("Printing tree with root:" + rootNode.value); switch (orderIndex) { case 1: { // In-order printTree(rootNode.leftLeaf, orderIndex); System.out.print(' '); System.out.print(rootNode.value); System.out.print(' '); printTree(rootNode.rightLeaf, orderIndex); break; } case 2: { // Pre-order System.out.print(' '); System.out.print(rootNode.value); System.out.print(' '); printTree(rootNode.leftLeaf, orderIndex); printTree(rootNode.rightLeaf, orderIndex); break; } case 3: { // Post-order printTree(rootNode.leftLeaf, orderIndex); printTree(rootNode.rightLeaf, orderIndex); System.out.print(' '); System.out.print(rootNode.value); System.out.print(' '); break; } default: System.out.println("orderIndex " + orderIndex + " not recognized!\n"); break; } } }
31b5289f-7538-4728-a107-234b5bc6db4a
7
private String readLine() throws IOException { byte[] readBytes = new byte[512]; int readIndex = 0; while (true) { int nextByte = remoteInputStream.read(); if (nextByte == -1) { if (readIndex == 0) { return null; } break; } if (nextByte == 10) { if (!ignoreNextLinefeed) { break; } } ignoreNextLinefeed = false; if (nextByte == 13) { ignoreNextLinefeed = true; break; } if (readIndex == readBytes.length) { /* recopy & enlarge array */ byte[] newReadBytes = new byte[readBytes.length * 2]; System.arraycopy(readBytes, 0, newReadBytes, 0, readBytes.length); readBytes = newReadBytes; } readBytes[readIndex++] = (byte) nextByte; } ByteBuffer byteBuffer = ByteBuffer.wrap(readBytes, 0, readIndex); return Charset.forName("UTF-8").decode(byteBuffer).toString(); }
ced7283d-172b-4e5d-8e47-3b76e519ed2d
4
public static boolean otherCharactersFound(String s, char[] c){ boolean found = false; for (int i=0; i<s.length(); i++) { found = false; for (int j=0; j<c.length; j++) if (s.charAt(i)== c[j]) found = true; if (!found) return true; } return false; }
ba63a29f-8a58-4563-a844-6aa46912b627
5
public static WordSearch loadFromFile(File file) { WordSearch wordSearch = new WordSearch(); BufferedReader reader; List<Character> chars = new ArrayList<>(); try { reader = new BufferedReader(new FileReader(file)); int character; while ((character = reader.read()) != ':') { char c = (char) character; if (Character.isLetter(c)) chars.add(c); } String wordLine = reader.readLine(); wordSearch.words = wordLine.substring(0, wordLine.length() - 1).split(" "); reader.close(); } catch (IOException e) { e.printStackTrace(); } int size = (int) Math.sqrt(chars.size()); char[][] grid = new char[size][size]; int x = 0, y = 0; for (Character c : chars) { grid[x][y++] = c; if (y == size) { x++; y = 0; } } wordSearch.grid = grid; wordSearch.size = size; return wordSearch; }
7c70ad4f-4602-4aae-b57d-3268a1898005
5
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed // TODO add your handling code here: if (v1.size() == 0) { JOptionPane.showMessageDialog(null, "You must enter Author Name to \n save book details"); } else if ((jTextField2.getText().equals(""))) { JOptionPane.showMessageDialog(null, "You must Enter\n Book Name"); } else if (jTextField2.getText().length() > 21) { JOptionPane.showMessageDialog(null, "Maximum Book Name Length is 25 characters"); } else if (!(jTextField3.getText().equals(jTextField4.getText()))) { JOptionPane.showMessageDialog(null, "Total Quentity must be Equal to \n Available Quentity"); } else { try { DB.myConnection().createStatement().executeUpdate("insert into book values ('" + jTextField1.getText() + "','" + jTextField2.getText() + "','" + jTextField3.getText() + "','" + jTextField4.getText() + "','" + librarianId + "','" + cmbRackID.getSelectedItem().toString() + "','" + LoadCategory.getCategoryID(cmbCategory.getSelectedItem().toString()) + "','" + jTextField6.getText() + "','" + LoadPublisher.selectPublisherID(cmbPublisher.getSelectedItem().toString()) + "')"); save_AuthorBook.save_AuthorBook(v1, jTextField1.getText()); } catch (Exception e) { } jTextField2.setText(""); jTextField3.setText(""); jTextField4.setText(""); btnRemove.setEnabled(false); jLabel12.setText(Date1.myDate()); jLabel10.setText(librianName); jTextField1.setText(GenerateBookID.getBookID()); jButton1.setEnabled(true); cmbCategory.setModel(new DefaultComboBoxModel(LoadCategory.selectAllCategory())); cmbRackID.setModel(new DefaultComboBoxModel(LoadRackID.selectAllRackID())); cmbPublisher.setModel(new DefaultComboBoxModel(LoadPublisher.selectAllPublisher())); v2 = LoadAuthor.selectAllAuthor(); jList1.setListData(v2); v1.removeAllElements(); jList3.setListData(v1); jList1.setSelectedIndex(0); jTextField6.setText("Select Book Image"); jTextField2.grabFocus(); } }//GEN-LAST:event_btnSaveActionPerformed
e4279e14-9897-42c3-a0f9-339830454b7c
6
public int getPriority() { switch (getOperatorIndex()) { case 26: case 27: return 500; case 28: case 29: case 30: case 31: return 550; } throw new RuntimeException("Illegal operator"); }
97bd42f9-ca7c-4beb-b756-906bbbc59b18
7
public static final SocksImplementation getImplementation( final ConfigurationFacade configurationFacade, final Socket socket) throws IOException, AccessDeniedException, ProtocolException { final InputStream inputStream = socket.getInputStream(); final int protocol = inputStream.read(); switch (protocol) { case 0x04: if (configurationFacade.isAllowSocks4()) { return new SocksImplementation4(configurationFacade, socket, SocksImplementationFactory.EXECUTOR); } else { try { socket.close(); } catch (final Exception e) { } throw new AccessDeniedException("SOCKS4 is not enabled"); } case 0x05: if (configurationFacade.isAllowSocks5()) { return new SocksImplementation5(configurationFacade, socket, SocksImplementationFactory.EXECUTOR); } else { try { socket.close(); } catch (final Exception e) { } throw new AccessDeniedException("SOCKS5 is not enabled"); } default: try { socket.close(); } catch (final Exception e) { } throw new ProtocolException("Unknown protocol: 0x" + Integer.toHexString(protocol)); } }
9bad0867-a1a9-450a-b1c7-63d03e585e86
4
private void userSave (ArrayList < String > command) { String filename=null; if (command.size()>1) { filename=command.get(1); try { BufferedWriter bw=new BufferedWriter(new FileWriter(command.get(1))); for (int i=0; i<moveHistory.size(); i++) { bw.write(moveHistory.get(i)+" "); } bw.write("\n"); bw.close(); } catch (IOException e) { System.out.println("Error saving - "+e.getMessage()); } } else { for (int i=0; i<moveHistory.size(); i++) { System.out.print(moveHistory.get(i)+" "); } System.out.println(); } }
4510cb9c-ac6c-410d-ae16-53f90e263314
4
@Override public void actionPerformed(ActionEvent e) { if(e.getSource() == inputText) { if(inputText.getText().trim().equals("")) { resetInputField(); return;} /** Look for it every time, if it's not there he's probably offline. */ NetworkSharedUser sendTo = Users.getUserById(targetUserId); if(sendTo == null) { if(targetUserId == -1) { NetworkEvent messageEvent = Events.createNewEvent(ClientContext.clientChannel); BroadcastMessage broadCast = new BroadcastMessage(inputText.getText()); messageEvent.setMessage(broadCast); messageEvent.send(); resetInputField(); } } else { // If the target user id is -1, it's the global channel. NetworkEvent messageEvent = Events.createNewEvent(ClientContext.clientChannel); PrivateMessage pm = new PrivateMessage(targetUserId, inputText.getText()); messageEvent.setMessage(pm); messageEvent.send(); addText("[You]: " + inputText.getText()); resetInputField(); } } }
bf32b9f9-c34d-4ea6-bbda-e2d8a96a42f1
7
public void loadConfigBoard() { try { FileReader reader = new FileReader(boardConfigFile); Scanner in = new Scanner(reader); while (in.hasNext()) { String input = in.nextLine(); String[] tokens = input.split(","); if (input.length() < 1) { throw new BadConfigFormatException("Error with board config file."); } for (int i = 0; i < tokens.length; i++) { if (tokens[i].equalsIgnoreCase("W")) { cells.add(new WalkwayCell(numRows, i)); } else { cells.add(new RoomCell(numRows, i, tokens[i], this.getRoomName(tokens[i]))); // added 4th parameter for graphics } } numRows++; } numColumns = (cells.size() / numRows); } catch (FileNotFoundException e) { System.out.println(e); } catch (BadConfigFormatException e) { System.out.println(e); } catch (Exception e){ e.printStackTrace(); } }
082769ef-8948-47c8-9f15-2f9a51d49fea
8
public static Cons removeVariableTypePropositions(Proposition proposition) { { Keyword testValue000 = proposition.kind; if (testValue000 == Logic.KWD_AND) { { Cons typedeclarations = Stella.NIL; Proposition goalproposition = null; { Stella_Object arg = null; Vector vector000 = proposition.arguments; int index000 = 0; int length000 = vector000.length(); for (;index000 < length000; index000 = index000 + 1) { arg = (vector000.theArray)[index000]; if (BooleanWrapper.coerceWrappedBooleanToBoolean(((Proposition)(arg)).variableTypeP())) { typedeclarations = Cons.cons(arg, typedeclarations); } else if (goalproposition != null) { } else { goalproposition = ((Proposition)(arg)); } } } Proposition.overlayProposition(proposition, goalproposition); return (typedeclarations); } } else if ((testValue000 == Logic.KWD_ISA) || ((testValue000 == Logic.KWD_PREDICATE) || ((testValue000 == Logic.KWD_FUNCTION) || (testValue000 == Logic.KWD_NOT)))) { return (Stella.NIL); } else { } } return (Stella.NIL); }
bb633375-387e-44ab-b019-ee43aa3e6d6c
8
public static Vector2D<Integer> getCrossVector(Vector2D<Float> orig, Vector2D<Float> dest) { int crossX = 0; if (orig.getX().floatValue() < 0f && dest.getX().floatValue() >= 0) { crossX = 1; } else if (orig.getX().floatValue() >= 0f && dest.getX().floatValue() < 0) { crossX = -1; } int crossY = 0; if (orig.getY().floatValue() < 0f && dest.getY().floatValue() >= 0) { crossY = 1; } else if (orig.getY().floatValue() >= 0f && dest.getY().floatValue() < 0) { crossY = -1; } return new Vector2D<Integer>(crossX, crossY); }
f4d0ac7b-ee20-425f-868d-b2e8fd9f726d
9
private void extend(Object component, Object lead, Object row, boolean recursive) { Object anchor = get(component, ":anchor"); if (anchor == null) { set(component, ":anchor", anchor = lead); } char select = 'n'; boolean changed = false; for (Object item = get(component, ":comp"); // anchor - row item != null; item = getNextItem(component, item, recursive)) { if (item == anchor) { select = (select == 'n') ? 'y' : 'r'; } if (item == row) { select = (select == 'n') ? 'y' : 'r'; } if (setBoolean(item, "selected", (select != 'n'), false)) { repaint(component, null, item); changed = true; } if (select == 'r') { select = 'n'; } } if (changed) { invoke(component, row, "action"); } }
0ca40f25-874a-4e27-83c9-599b59df669c
8
final public void Function_statement() throws ParseException { /*@bgen(jjtree) Function_statement */ SimpleNode jjtn000 = new SimpleNode(JJTFUNCTION_STATEMENT); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1)); try { Function_call_expression(); jj_consume_token(SEMICOLON); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } }
f6f5d8b7-01ff-406e-bd49-46e68ea4155d
8
public static boolean computeCell(boolean[][] world, int col, int row) { // liveCell is true if the cell at position (col,row) in world is live boolean liveCell = getCell(world, col, row); // neighbours is the number of live neighbours to cell (col,row) int neighbours = countNeighbours(world, col, row); // we will return this value at the end of the method to indicate whether // cell (col,row) should be live in the next generation boolean nextCell = false; // A live cell with less than two neighbours dies (underpopulation) if (neighbours < 2) nextCell = false; // A live cell with two or three neighbours lives (a balanced population) if (liveCell && (neighbours == 2 || neighbours == 3)) nextCell = true; // A live cell with more than three neighbours dies (overcrowding) if (liveCell && neighbours > 3) nextCell = false; // A dead cell with exactly three live neighbours comes alive if (!liveCell && neighbours == 3) nextCell = true; return nextCell; }
51792d0b-eb2e-4794-b6ed-861fa374e434
3
public ExtGState getExtGState(String namedReference) { ExtGState gsState = null; if (extGStates != null) { Object attribute = library.getObject(extGStates, namedReference); if (attribute instanceof Hashtable) { gsState = new ExtGState(library, (Hashtable) attribute); } else if (attribute instanceof Reference) { gsState = new ExtGState(library, (Hashtable) library.getObject( (Reference) attribute)); } } return gsState; }
cd774338-39da-4081-b1b7-bd8ae64aa60d
4
protected void loadConfig() { // Read config file if (verbose) // Timer.showStdErr("Reading configuration file '" + configFile + "'" // + ((genomeVer != null) && (!genomeVer.isEmpty()) ? ". Genome: '" + genomeVer + "'" : "") // ); config = new Config(genomeVer, configFile, dataDir); // Read configuration if (verbose) Timer.showStdErr("done"); }
4a3837fe-a9b5-4c0d-b5e7-4135333bc950
4
private Node find(Node node, String string) throws KeyNotFoundException { int index = 0; while (index < string.length()) { if (node == null) throw new KeyNotFoundException(); int cmp = node.ch.compareTo(string.charAt(index)); if (cmp < 0) node = node.right; else if (cmp > 0) node = node.left; else { node = node.middle; index++; } } return node; }
8ad2b057-ccb5-4abe-825b-5eecb40df631
2
@Override public void onHitByBullet(final HitByBulletEvent e) { // TODO check if this is needed if(lastState != null) { lastState.update(e); } if (doMove) { move.onHitByBullet(e); } }
94d6a4ba-8c0c-47f2-b5eb-92fb3013ca7e
0
private void log(String text) { textArea.append(text + "\n"); textArea.setCaretPosition(textArea.getDocument().getLength() - 1); }
8407c10d-bfa4-4952-b511-c2b319f6b741
7
public void run() { String theMsg = null; ITupleSpaceConnectorListener theListener = null; while (isRunning) { synchronized(messages) { if (messages.isEmpty()) { theMsg = null; theListener = null; try { messages.wait(); } catch (Exception e) {} } else if (isRunning && !messages.isEmpty()) { theMsg = messages.remove(0); theListener = listeners.remove(0); // System.out.println("XXX "+theMsg+" "+theListener); } } if (isRunning && theMsg != null) { sendMessage(theMsg,theListener); theMsg = null; theListener = null; } } }
07ba296f-b10f-4e93-b974-380ad179ade1
5
public void render(Graphics2D g2d) { for (int row = rowOffset; row < rowOffset + numRowsToDraw; row++) { if (row >= rows) break; for (int col = colOffset; col < colOffset + numColsToDraw; col++) { if (col >= cols) break; if (map[row][col] == 0) continue; g2d.drawImage(getTile(row, col).getImage(), (int) x + col * tileSize, (int) y + row * tileSize, null); } } }
c42d0a9d-f4f5-4045-9a83-763365498144
1
public FrequencyGen(Pair<Integer, Gen<T>> ... generatorPairs) { this.generatorPairs = generatorPairs; this.size = 0; for (int i = 0; i < generatorPairs.length; ++i) { this.size += generatorPairs[i].fst(); } }
27c329d4-9d54-42da-829b-4eb4d51d1c71
5
private final void setMinimumComponentBounds() { for (int i = 0; i < getTComponents().size(); i++) { TComponent c = getTComponents().get(i); if (resizeComponentArray.get(i)) if (isVertical) { if (c.getHeightD() > smallestComponentHeight) smallestComponentHeight = c.getHeightD(); c.setWidth(width - (2 * borderSize)); } else { if (c.getWidthD() > smallestComponentWidth) smallestComponentWidth = c.getWidthD(); c.setHeight(height - (2 * borderSize)); } } calculateTotalMenuLength(); setMenuLayout(); }