method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
0ea0ab54-014f-4d97-916c-7b0136c3a2fb
9
private void placeLightGrenadeNearPlayer() { for (Player p : players) { boolean placed = false; int minX = p.getPosition().getxCoordinate() - 2; int maxX = p.getPosition().getxCoordinate() + 2; int minY = p.getPosition().getyCoordinate() - 2; int maxY = p.getPosition().getyCoordinate() + 2; if (minX < 0) minX = 0; if (minY < 0) minY = 0; while (!placed) { int randomX = minX + (int) Math.round(Math.random() * maxX); int randomY = minY + (int) Math.round(Math.random() * maxY); LightGrenade lg = new LightGrenade(new Position(randomX, randomY)); if (0 < randomX && randomX < 11 && 0 < randomY && randomY < 11 && grid.canHaveAsLightGrenade(lg)){ grid.addElement(lg); placed = true; } } } }
eed89b13-4e68-4fce-8180-b8162c134bdc
1
public boolean connects(RouteLeg routeLeg) { return this.routeLeg.getStartNode().equals(routeLeg.getStartNode()) && this.routeLeg.getEndNode().equals(routeLeg.getEndNode()); }
d268abb0-c999-4505-b8f4-6215d3f51162
8
private void addDependentType(String canonicalName) { Class<?> toAdd = null; try { toAdd = Class.forName(canonicalName); } catch (ClassNotFoundException e) { //System.err.println("Warning: class not found (" + canonicalName + ")"); } if (toAdd != null && Modifier.isPublic(toAdd.getModifiers()) && includeDependentTypes && canonicalName.contains(".") && !typesToProcess.contains(canonicalName) && !typesProcessed.contains(canonicalName)) typesToProcess.add(canonicalName); }
9a1df02a-c782-4bf6-bc4a-eb6574b6065d
6
private void getSample () { // Tell the main thread we getting audio gettingAudio=true; int a,sample,count,total=0; // READ in ISIZE bytes and convert them into ISIZE/2 integers // Doing it this way reduces CPU loading try { while (total<ISIZE) { count=audioMixer.line.read(buffer,0,ISIZE); total=total+count; } } catch (Exception e) { String err=e.getMessage(); JOptionPane.showMessageDialog(null,err,"Rivet", JOptionPane.ERROR_MESSAGE); } // Get the required number of samples for (a=0;a<ISIZE;a=a+2) { sample=(buffer[a]<<8)+buffer[a+1]; // If inputLevel is positive then multiply the sample with it // If it is negative then divide the sample by it if (inputLevel>0) sample=sample*inputLevel; else if (inputLevel<0) sample=sample/Math.abs(inputLevel); // Add this sample to the circular volume buffer addToVolumeBuffer(sample); try { // Put the sample into the output pipe outPipe.writeInt(sample); sampleCounter++; } catch (Exception e) { String err=e.getMessage(); JOptionPane.showMessageDialog(null,err,"Rivet", JOptionPane.ERROR_MESSAGE); } } // The the main thread we have stopped fetching audio gettingAudio=false; }
e1f3795f-e2bd-42c7-8d9a-e479d9f5661a
2
private void centerMouse() { if (robot != null && component.isShowing()) { // Because the convertPointToScreen method // changes the object, make a copy! Point copy = new Point(center.x, center.y); SwingUtilities.convertPointToScreen(copy, component); robot.mouseMove(copy.x, copy.y); } }
ebac1340-08e8-40ef-a39b-00d07c445790
7
public double minDataDLIfDeleted(int index, double expFPRate, boolean checkErr){ //System.out.println("!!!Enter without: "); double[] rulesetStat = new double[6]; // Stats of ruleset if deleted int more = m_Ruleset.size() - 1 - index; // How many rules after? FastVector indexPlus = new FastVector(more); // Their stats // 0...(index-1) are OK for(int j=0; j<index; j++){ // Covered stats are cumulative rulesetStat[0] += ((double[])m_SimpleStats.elementAt(j))[0]; rulesetStat[2] += ((double[])m_SimpleStats.elementAt(j))[2]; rulesetStat[4] += ((double[])m_SimpleStats.elementAt(j))[4]; } // Recount data from index+1 Instances data = (index == 0) ? m_Data : ((Instances[])m_Filtered.elementAt(index-1))[1]; //System.out.println("!!!without: " + data.sumOfWeights()); for(int j=(index+1); j<m_Ruleset.size(); j++){ double[] stats = new double[6]; Instances[] split = computeSimpleStats(j, data, stats, null); indexPlus.addElement(stats); rulesetStat[0] += stats[0]; rulesetStat[2] += stats[2]; rulesetStat[4] += stats[4]; data = split[1]; } // Uncovered stats are those of the last rule if(more > 0){ rulesetStat[1] = ((double[])indexPlus.lastElement())[1]; rulesetStat[3] = ((double[])indexPlus.lastElement())[3]; rulesetStat[5] = ((double[])indexPlus.lastElement())[5]; } else if(index > 0){ rulesetStat[1] = ((double[])m_SimpleStats.elementAt(index-1))[1]; rulesetStat[3] = ((double[])m_SimpleStats.elementAt(index-1))[3]; rulesetStat[5] = ((double[])m_SimpleStats.elementAt(index-1))[5]; } else{ // Null coverage rulesetStat[1] = ((double[])m_SimpleStats.elementAt(0))[0] + ((double[])m_SimpleStats.elementAt(0))[1]; rulesetStat[3] = ((double[])m_SimpleStats.elementAt(0))[3] + ((double[])m_SimpleStats.elementAt(0))[4]; rulesetStat[5] = ((double[])m_SimpleStats.elementAt(0))[2] + ((double[])m_SimpleStats.elementAt(0))[5]; } // Potential double potential = 0; for(int k=index+1; k<m_Ruleset.size(); k++){ double[] ruleStat = (double[])indexPlus.elementAt(k-index-1); double ifDeleted = potential(k, expFPRate, rulesetStat, ruleStat, checkErr); if(!Double.isNaN(ifDeleted)) potential += ifDeleted; } // Data DL of the ruleset without the rule // Note that ruleset stats has already been updated to reflect // deletion if any potential double dataDLWithout = dataDL(expFPRate, rulesetStat[0], rulesetStat[1], rulesetStat[4], rulesetStat[5]); //System.out.println("!!!without: "+dataDLWithout + " |potential: "+ // potential); // Why subtract potential again? To reflect change of theory DL?? return (dataDLWithout - potential); }
25d1c950-84d0-4c10-a606-581f6587a1bf
7
public void plotTrainingScrawl(File trainFile) { theNet.clearTrainingData(); loadTrainingData(trainFile); DisplayGraph[] dispGraph = new DisplayGraph[CypherType.size()]; for (int i = 0; i< dispGraph.length; i++) { dispGraph[i] = new DisplayGraph(CypherType.fromIntToString(i) + " : Scrawl Plot"); } //For each training example add a new plot. //Loads the data from train file //Read the file BufferedReader br = null; String line; int index; String text; int type; int count; try { br = new BufferedReader(new FileReader(trainFile)); //First step to training. load the data. theNet.clearTrainingData(); //Clear the data first. count = 0; while ((line = br.readLine()) != null) { //Add the training example. //format is [English text]:[class] index = line.indexOf(":"); if (index >=0 ) { text = line.substring(0,index); text.replaceAll("[^A-Za-z]+", ""); type = Integer.parseInt(line.substring(index+1,index+2)); // Here we go. theNet.addTrainingExample(text, CypherType.fromInt(type)); double [] tempArray = CryptoNet.getFreqArray(text); dispGraph[type].addTrace("train" + count); for (int i = 0; i <tempArray.length;i++) { dispGraph[type].addPoint("train" + count, i, tempArray[i]); } } else { System.out.println("Bad Line ("+count+") in training data.."); } count++; } br.close(); } //end try catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //Show the graphs. for (int i = 0; i < dispGraph.length; i++) { dispGraph[i].show(); } }
d5de980f-5d82-4e45-ae2a-76994b034aa6
8
public List<Short> getShortList(String path) { List<?> list = getList(path); if (list == null) { return new ArrayList<Short>(0); } List<Short> result = new ArrayList<Short>(); for (Object object : list) { if (object instanceof Short) { result.add((Short) object); } else if (object instanceof String) { try { result.add(Short.valueOf((String) object)); } catch (Exception ex) { } } else if (object instanceof Character) { result.add((short) ((Character) object).charValue()); } else if (object instanceof Number) { result.add(((Number) object).shortValue()); } } return result; }
32208c8e-242f-4baf-bd5d-2820ec647fca
4
public void doesCollide(Drawable i, Drawable s, Window w) //Checks if two objects collide. If they do, it runs the doCollide() method in the Drawable i { if(i.getX() < s.getX()+s.getWidth()){ if(i.getX()+i.getWidth() > s.getX() ) if(i.getY() < s.getY()+s.getHeight()) if(i.getY()+i.getHeight() > s.getY() ) { i.doCollide(s, w); i.setVelocityX(i.getVelocityX()*-1); i.setVelocityY(i.getVelocityY()*-1); } } }
b28fe2cb-7ea3-4bbc-824f-895c5225ddf7
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FightState other = (FightState) obj; if (!Arrays.deepEquals(atkCnt, other.atkCnt)) return false; if (spareDamage != other.spareDamage) return false; if (spareEnemyDamage != other.spareEnemyDamage) return false; return true; }
c5957e81-0df8-422e-9ae2-e3fc2b40b84a
8
public static void main(String[] args) { Cell[][] spreadsheet = new Cell[8][10]; length = spreadsheet[0].length; setSpreadsheetToEmpty(spreadsheet); printSpreadsheet(spreadsheet); String inputFromUser = inputFromUser(); while (!inputFromUser.equalsIgnoreCase("quit")) { int indexOfEquals = inputFromUser.indexOf("="); if (inputFromUser.contains("clear") && inputFromUser.indexOf(" ") != -1) { cellToClear( inputFromUser.substring(inputFromUser.indexOf(" ") + 1), spreadsheet); } else if (inputFromUser.equalsIgnoreCase("clear")) { setSpreadsheetToEmpty(spreadsheet); } else if (indexOfEquals >= 0) { String cellToSet = inputFromUser.substring(0, indexOfEquals) .trim(); String cellVal = inputFromUser.substring(indexOfEquals + 1); int row = getRowNumber(cellToSet); int col = getColNumber(cellToSet); Cell cell = new Cell(cellVal); try { spreadsheet[row][col] = cell; } catch (Exception e) { System.out.println("Index out of bounds."); } } else if (indexOfEquals == -1) { try { String cell = inputFromUser; int row = getRowNumber(cell); int col = getColNumber(cell); System.out.println(spreadsheet[row][col]); } catch (Exception e) { System.out.println("Please Try Again."); } } printSpreadsheet(spreadsheet); inputFromUser = inputFromUser(); } }
b049eeff-93d0-446f-998f-99d8c55f9345
2
public LinkedList<StockPosition> qsort( LinkedList<StockPosition> d, int comparing ) { if (comparing == 0) // 0 means you are sorting by ticker name qsHelpTick( 0, d.size()-1, d ); if (comparing == 1) // 1 means compare by quantity of shares held qsHelpQuant( 0, d.size()-1, d ); return d; }
bcf2f92a-7552-459f-aae4-0b357e6874b2
7
private boolean doAction(final String action, final SceneObject obj) { if(Players.getLocal().getAnimation() == -1 && !Players.getLocal().isMoving()) { if(obj.getLocation().distanceTo() > 5) { Walking.walk(obj.getLocation()); } else { if(!obj.isOnScreen()) { Camera.turnTo(obj); } else { if(obj.interact(action, obj.getDefinition().getName())) { final Timer timeout = new Timer(3000); while(Players.getLocal().getAnimation() == -1 && timeout.isRunning()) { Task.sleep(50); } return true; } } } } return false; }
46626b5b-7280-4281-952c-f35a98c162a4
7
@Override public void rightMultiply(Matrix other) { // TODO Auto-generated method stub for(int i=0;i<4;i++) for(int j=0;j<4;j++) copy[i][j]=0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { for (int k = 0; k < 4; k++) { copy[i][j]=copy[i][j] + this.get(k, i) * other.get(j, k); } } } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { this.set(j, i, copy[i][j]); } } }
eb06c96b-cb7d-4c29-bba9-e0613178bffa
7
public static TcpPollResult hostAvailable(String ip) { int port = 80; try { SocketAddress addr = new InetSocketAddress(ip, port); new Socket().connect(addr, 5000); return TcpPollResult.CONNECTED; } catch (UnknownHostException ex) { return TcpPollResult.UNKNOWN_HOST; } catch (SocketTimeoutException timeoutException) { return TcpPollResult.TIMEOUT; } catch (ConnectException e) { if(e.getCause() instanceof ErrnoException) { ErrnoException errnoException = (ErrnoException)e.getCause(); switch (errnoException.errno) { case 113: return TcpPollResult.NO_ROUTE_TO_HOST; case 111: return TcpPollResult.REFUSED; default: return TcpPollResult.OTHER_ERRNO_EXCEPTION; } } else { return TcpPollResult.OTHER_CONNETION_EXCEPTION; } } catch (IOException ex) { return TcpPollResult.OTHER; } }
4274814f-d215-4bf9-b151-7f1e5c480374
9
public MenuLevel () { super(); int i; int posx; int posy; int index; try { setImg(ImageIO.read(new File("img/background/menu.jpg"))); } catch (IOException e) { e.printStackTrace(); } _title.setBounds(180, 25, 430, 70); _title.setFont(new Font("Arial", Font.BOLD, 45)); add(_title); setLayout(null); String [] listefichiers; File repertoire = new File(path); listefichiers = repertoire.list(); for (i = 0; i < listefichiers.length; ++i){ final int lvl = i + 1; index = listefichiers[i].indexOf("."); String temp = listefichiers[i].substring(index); listefichiers[i] = listefichiers[i].replaceAll(temp, ""); File entree = new File(listefichiers[i]); posx = i % 4; posy = i / 4; if (entree.getName().contentEquals("level" + (i + 1)) && (i + 1) <= Fenetre._level.getMaxLvl()) { BoutonChargement temp1 = new BoutonChargement("Niveau " + (i + 1), 160 + posx * 130, 120 + posy * 70, 100, 50, Fenetre._level.loadHighScore(lvl)); temp1.setOpaque(true); if (Fenetre._level.saveExist(lvl)) { temp1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { int choix = JOptionPane.showConfirmDialog(null, "Il existe une sauvegarde de ce niveau. Voulez-vous la charger ?", "Sauvegarde existante", JOptionPane.YES_NO_OPTION, JOptionPane.DEFAULT_OPTION); if (choix == JOptionPane.OK_OPTION) { Fenetre._level.loadSave(lvl); Fenetre.setState(StateFen.Level); if (_DEBUG) System.out.println("Debut du level sauvegarde " + lvl); } else { Fenetre._level.loadLevel(lvl); Fenetre._level.deleteSave(lvl); Fenetre.setState(StateFen.Level); if (_DEBUG) System.out.println("Debut du level " + lvl); } } }); } else { temp1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Fenetre._level.loadLevel(lvl); Fenetre.setState(StateFen.Level); if (_DEBUG) System.out.println("Debut du level " + lvl); } }); } temp1.setVisible(true); add(temp1); } } _keyListener = new Keyboard(this); addKeyListener(_keyListener); }
ac7c31ad-dc8b-4a20-841f-04f0f9e2d45a
5
public boolean readField(aos.apib.InStream in, aos.apib.Base o,int i) { if ( i > __field_names.length ) return getBaseClassStreamer().readField( in, o, i - __field_names.length - 1 ); AuthenticationRequest v = (AuthenticationRequest)o; switch (i) { case 0: v.id = in.getInt(); break; case 3: in.readBaseClasses(o, this, 0); break; default: if (i >= 0 && i <= 3) break; in.error("Reader for AuthenticationRequest: illegal field number:"+i); return false; } return true; }
94db769d-fc97-4c74-81b0-f640a87fb90f
1
public static ConnectionSingleton getInstance() { if (instance == null) instance = new ConnectionSingleton(); return instance; }
3feb51e6-9151-48d3-b771-db757a94613e
4
public boolean isVariableWLocked(int index) { for (Transaction t: locks.keySet()) { ArrayList<Lock> lockListT = locks.get(t); for (Lock lock: lockListT) { if(lock.getIndex()==index && lock.isWrite()) { return true; } } } return false; }
37821dbb-413d-416d-aa9d-ef990934be4f
7
private static List<Point[]> mergePolygonPointList(int labelCount, Map<Integer, Integer> mergeLabels, List<List<Point>> polygonPointList){ List<Integer> objectLabel = new LinkedList<Integer>(); for(Integer key : mergeLabels.keySet()) { // System.out.println(key+"<-->"+mergeLabels.get(key)); if(key.equals(mergeLabels.get(key))) objectLabel.add(key); } @SuppressWarnings("unchecked") List<Point>[] mergePointList = new List[objectLabel.size()]; for (int j = 0; j < mergePointList.length; j++) mergePointList[j] = new ArrayList<Point>(); // System.out.println(mergePointList.length+" different Objects"); List<Point[]> polygonList = new LinkedList<Point[]>(); for(int objectIndex = 0; objectIndex < mergePointList.length; objectIndex++){ int currentLabel = objectLabel.get(objectIndex); // System.out.println("Object "+objectIndex+", label:"+currentLabel); for(Integer key : mergeLabels.keySet()) if(mergeLabels.get(key).equals(currentLabel)) { mergePointList[objectIndex].addAll(polygonPointList.get(key)); // System.out.println("add "+key); } polygonList.add(mergePointList[objectIndex].toArray(new Point[0])); } for(Point[] polygon : polygonList) Arrays.sort(polygon, new PointCompareXY()); Collections.sort(polygonList, new PointArrayCompareXY()); return polygonList; }
cb58f7ce-c09f-434b-aa0d-cf585e5b514c
8
private List removeAssociatedBends(RadialBond killedBond) { if (bends.isEmpty()) return null; List<AngularBond> list = new ArrayList<AngularBond>(); Atom atomOne = killedBond.getAtom1(); Atom atomTwo = killedBond.getAtom2(); synchronized (bends.getSynchronizationLock()) { for (Iterator i = bends.iterator(); i.hasNext();) { AngularBond aBond = (AngularBond) i.next(); if (aBond.contains(atomOne) && aBond.contains(atomTwo) && (aBond.indexOf(atomOne) == 2 || aBond.indexOf(atomTwo) == 2)) list.add(aBond); } if (list.isEmpty()) return null; for (AngularBond a : list) bends.remove(a); } return list; }
05b6a7e2-f219-4e9d-86b9-e430f6e6ada6
7
protected void eatCombinationOne() { int green = 0; int red = 0; for (Iterator<Plant> it = plants.iterator(); it.hasNext();) { Plant pl = it.next(); if (pl.getType() == Plant.GREEN_PLANT && green < 1) { it.remove(); green++; } if (pl.getType() == Plant.RED_PLANT && red < 1) { it.remove(); red++; } // stops looping than required if (green == 1 && red == 1) { break; } } energy += COMBO_ONE_AMOUNT; System.out.println("The combo 1 " + energy); WorldFrame.log.append("Simple Creature " + getCreautreNumber() + " ate a combination one \n"); }
ed732402-ea13-4564-831f-43710adba823
6
private void recursion1(int depth, int index, ArrayList<String> result, ArrayList<Character> current) { //judge int left = 0; int right = 0; String item = ""; for (char c : current) { if (c == '(') { left++; } else { right++; } if (left > (depth >> 1) || right > (depth >> 1) || left < right) { return; } item += c; } if (left + right == depth) { result.add(item); return; } current.add('('); recursion1(depth, index + 1, result, current); current.remove(current.size() - 1); current.add(')'); recursion1(depth, index + 1, result, current); current.remove(current.size() - 1); }
c746aaad-2a22-43cd-89ed-b9da54d232c4
2
public boolean mineTile(){ if(resources > 0){ resources--; if(resources == 0){ Debug.game(tileType + " tile is depleted of resources and became a grass-tile."); tileType = TileType.GRASS; id = "G"; // TODO: it may be of interest later to *Tiles-- and grassTiles++. // Doesn't seem particularly important, though -- we currently only use // it for the initial consistency check. } return true; } return false; }
99acb55e-6ee5-4f80-b1a7-03c4a330002c
6
public TableCellRenderer getCellRenderer(int row, int column) { TableCellRenderer renderer = (TableCellRenderer) renderers.get(getKey(row, column)); if (renderer == null) { // no renderer specified for the cell, checking if specified for the column... renderer = (TableCellRenderer) renderers.get(getKey(-1, column)); if (renderer == null) { // checking if renderer is specified just for the row ... renderer = (TableCellRenderer) renderers.get(getKey(row, -1)); if (renderer == null){ // checking if renderer specified the whole table renderer = (TableCellRenderer) renderers.get(getKey(-1, -1)); } } } if (renderer != null) { return renderer; } else { TableCellRenderer superRenderer = super.getCellRenderer(row, column); if (alwaysUseYTableCellRenderer && ! (superRenderer instanceof YTableCellRenderer)) { // by default we will force using som YTableCellRenderer so that coloring stuff will work return DEFAULT_RENDERER; } else { return superRenderer; } } }
7af5106f-c991-412e-8c7e-c7a612ebb311
3
synchronized String getLine() { // Write the code that implements this method ... try { while (available == 0) wait(); } catch (InterruptedException exc) { throw new RTError("Buffer.putLine interrupted: "+exc); } String value = buffData[nextToGet]; if (++nextToGet >= size) nextToGet = 0; available--; notifyAll(); return value; }
ab155eb9-0e95-4c57-8de4-e6afd606794d
7
@Override public void iterate(){ matcount += 1; if(matcount >= mat){matcount = 0; calculate(); } if(ages){ if(active){ if(age == 0){age = 1;} else{age += 1;}}else{ age = 0;} if(fades){ if( age >= fade){ purgeState(); age = 0;}} if( age > 1023){ age = 1023; } state = agify(age);} //else{if(active){state = 1;}else{state = 0;}} }
0cd4472b-5181-4d8a-a12c-2934650f5a0f
2
public static void exportSequenceAsSpreadSheet(SegmentedImage[] images, String oName){ Workbook wb = new HSSFWorkbook(); for(SegmentedImage image : images){ dumpImageToSheet(image, wb); } try{ FileOutputStream out = new FileOutputStream(oName + ".xls"); wb.write(out); out.close(); } catch (Exception e){ e.printStackTrace(); } }
f7e18f08-51fb-4e9d-a5b1-cd1c0848fe8a
7
private void setupSelectionGL() { float xoff = this.getX(); float yoff = this.getY(); List<VertexData> ret = new LinkedList<VertexData>(); this.scalingConst = this.fontSize / this.font.getHeight("A"); int aqc = 0; for(int i = 0; i < this.selectionEnd; i++) { String c = this.actualText.substring(i,i+1); if(this.passwordMode) c = ""+this.passwordChar; if(c.equals("\n")) { xoff = this.getX(); yoff += this.fontSize; } else { float w = ( this.scalingConst ) * this.font.getWidth(c) * ( 1 / Settings.get(SetKeys.WIN_ASPECT_RATIO, Float.class) ) * -1.0f; Vertex4[] qp = Utility.generateQuadPoints(xoff, yoff, w, this.fontSize); Vertex2[] st = Utility.generateSTPoints( this.font.getX(c), this.font.getY(c), this.font.getWidth(c), this.font.getHeight(c) ); /* Utility.generateSTPointsFlipped( this.font.getX(c), this.font.getY(c), this.font.getWidth(c), this.font.getHeight(c) ); */ VertexData[] data = Utility.generateQuadData(qp, Colors.NAVY.getGlColor(), st); if(i >= this.selectionStart) { for (int d = 0; d < data.length; d++) { ret.add(data[d]); } aqc++; } xoff += w; } } if (ret.size() >= 0) { //HACK for half cutted letter (dunno how to fix) Vertex4[] qp = Utility.generateQuadPoints(0, 0, 0, 0); Vertex2[] st = Utility.generateSTPoints(0, 0, 0, 0); VertexData[] data = Utility.generateQuadData(qp, Colors.NAVY.getGlColor(), st); for (int d = 0; d < data.length; d++) { ret.add(data[d]); } //END HACK this.selectionArea.setupGL(ret.toArray(new VertexData[1]), Utility.createQuadIndicesInt(aqc)); this.selectionArea.setClippingArea(this.getClippingArea()); Logger.spam( ( "Text dimension: " + this.getWidth() + "/" + this.getHeight() ), "FontObject.setupFontGL" ); } }
527ac0ff-a386-4138-b064-7d39654514b4
2
@Override public TestResult test(Double input, Double... args) { double minValue = args[0]; double maxValue = args[1]; boolean passed = (input >= minValue && input <= maxValue); String message = passed ? null : String.format(messageT,minValue,maxValue); return new TestResult(passed,message); }
272f7ed4-09fa-4def-9deb-64570bb4b088
1
protected void receiveMessageData(IRemoteCallObjectMetaData meta, IRemoteCallObjectData data) throws Exception { if (!meta.getExecCommand().equalsIgnoreCase(ISession.KEEPALIVE_MESSAGE)) { ConnectionInfo info = new ConnectionInfo( this.idConnection, this.getCreationTime(), this.getIdleTimeout(), this.getLastAccessTime(), this.getLastReceiptTime(), this.getRemoteIP(), this.getRemotePort()); fireReceiveMessageEvent(new ReceiveMessageEvent(this, info, meta.getExecCommand(), data.getData())); } }
ff414a5a-5e8d-47c6-a6ac-6614717dcc5c
4
public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || this.length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; }
db4b8e09-6745-4a8a-8e1e-a62d2047c31d
4
public int min(int hori, int verti, int dia) { if (hori <= verti && hori <= dia) { return hori; } else if (verti <= hori && verti <= dia) { return verti; } else { return dia; } }
9039bb6b-ad13-41d4-b8bb-7fd71a5a37a5
6
public void draw(){ BufferStrategy bs = getBufferStrategy(); if(bs == null){ createBufferStrategy(3); return; } Graphics2D g = (Graphics2D) bs.getDrawGraphics(); // g.setColor(Color.DARK_GRAY); g.fillRect(0, 0, dim.width, dim.height); if(kh.isPicureOn()) g.drawImage(image, 0, 0, dim.width, dim.height,null); g.setColor(new Color(0xaa2222)); g.setColor(Color.black); if(kh.isLinesOn()){ for(Point p : box.getEdgePoints(mh.getPoint())){ g.drawLine(p.x, p.y, mh.getX(),mh.getY()); } g.setColor(Color.black); for(int i = 0 ; i < 4; i++){ g.drawLine(mh.getX(), mh.getY(), corenerPoints[i].x, corenerPoints[i].y); } } shadow2.draw(g); box1.draw(g); shadow1.draw(g); box.draw(g); g.setComposite(AlphaComposite.SrcAtop); if(kh.isLightsOn()) g.drawImage(light.getLightMap(),(-dim.width / 2) - (dim.width / 2) + mh.getX(),(-dim.height / 2) - (dim.height/ 2) + mh.getY(),null); // bs.show(); g.dispose(); }
b4ba4a6f-33ac-4068-b936-6b1912ac4f55
1
private static void updateFPS() { if (Time.getTime() - lastFPS > 1000) { System.out.println("FPS: " + fps); fps = 0; lastFPS += 1000; } fps++; }
5365f9e3-2aec-400c-856b-d48980cd8c48
3
private static void sort(int[] array) { for (int i = 1; i < array.length; i++) { for (int j = 0; j < array.length - i; j++) { if (array[j] < array[j + 1]) { array[j] = array[j] ^ array[j + 1]; array[j + 1] = array[j] ^ array[j + 1]; array[j] = array[j] ^ array[j + 1]; } } } }
25e6151d-2d1d-45e1-beed-bc0dc07c6449
9
public static Set<String> addTwoChar( String word ){ //check permission if( word.length() < ADD_TWO_ACCESSIBLE ) return new HashSet<String>(); word = word.toLowerCase(); StringBuilder processBuilder = new StringBuilder( word ); int wordLength = processBuilder.length(); Set<String> returnList = new HashSet<String>(); //processing for (int i = 0; i < wordLength ; i++) { for (String str1 : DOMAIN_NAME_CHAR) { String tmp = new StringBuilder(word).insert(i, str1).toString(); for( int j = i+1 ; j <= wordLength ; j ++ ){ for (String str2 : DOMAIN_NAME_CHAR) { String tmp2 = new StringBuilder(tmp).insert(j+1, str2).toString(); if( !tmp2.matches("^-.*") && !tmp2.matches("^\\_.*") && tmp2.indexOf("-") != (tmp2.length() -1) && tmp2.indexOf("_") != (tmp2.length() -1) ) returnList.add(tmp2); } } } } return returnList; }
d477094a-f14e-4f4a-8d6b-ede28fd105ce
0
public JTextField[] getTextFields() { return textFields; }
201f44fd-c8a7-4b15-883a-29c67aa829e7
0
public Profile(){ emptyString = lambda; transTuringFinal = false; transTuringFinalCheckBox = new JCheckBoxMenuItem("Enable Transitions From Turing Machine Final States"); transTuringFinalCheckBox.setSelected(transTuringFinal); transTuringFinalCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setTransitionsFromTuringFinalStateAllowed(transTuringFinalCheckBox.isSelected()); savePreferences(); } }); turingAcceptByFinalState = true; //default to true, since that was the status before; turingAcceptByFinalStateCheckBox = new JCheckBoxMenuItem("Accept by Final State"); turingAcceptByFinalStateCheckBox.setSelected(turingAcceptByFinalState); turingAcceptByFinalStateCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setAcceptByFinalState(turingAcceptByFinalStateCheckBox.isSelected()); savePreferences(); } }); turingAcceptByHalting = false; //defaults to false, since it was not in previous JFLAP turingAcceptByHaltingCheckBox = new JCheckBoxMenuItem("Accept by Halting"); turingAcceptByHaltingCheckBox.setSelected(turingAcceptByHalting); turingAcceptByHaltingCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setAcceptByHalting(turingAcceptByHaltingCheckBox.isSelected()); savePreferences(); } }); turingAllowStay = false; //defaults to false temporarily since that's how it was before turingAllowStayCheckBox = new JCheckBoxMenuItem("Allow stay for tape head on transition"); turingAllowStayCheckBox.setSelected(turingAllowStay); turingAllowStayCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setAllowStay(turingAllowStayCheckBox.isSelected()); savePreferences(); } }); }
bb15f88b-7644-447e-a8d6-245a6ca13d02
7
@Override public void keyPressed(KeyEvent flecha){ if(flecha.getKeyCode()==39){ if(posX==670){ posX = 670; contador += 1; }else{ posX = posX + 160; contador += 1; } } else if(flecha.getKeyCode()==37){ if(posX==30){ posX = 30; contador += 1; }else{ posX = posX - 160; contador += 1; } } else if(flecha.getKeyCode()==38){ velocidad = 100; contador += 1; } else if(flecha.getKeyCode()==40){ velocidad = 60; contador += 1; algo = 1; } else if(flecha.getKeyCode()==31){ } }
089c25a5-4974-432a-9233-f28873d6a5fa
3
public void Print(boolean result, int ActiveTO, int sequence, boolean active,int TIME) { if(active) { if(result) System.out.println("Time: "+ TIME +" Attempting Bus: "+ (ActiveTO+1) +" Set -> ACTIVE Packet: "+sequence); else{ System.out.print("\nTime: "+ TIME +" Attempting Bus: "+ (ActiveTO+1) +" [Already Active]" +" Packet: "+sequence); /* for(int x=0; x<inputBuffers.length; x++) { System.out.print(" InB"+(x+1)+": "+inputBuffers[x].size()); } */ System.out.print("\n"); } } else { if(result) System.out.println("Time: "+ TIME +" Attempting Bus: "+ (ActiveTO+1) +" Set -> INACTIVE Packet: "+sequence); } }
f40c44e3-198b-4622-ac05-897e8d0789ec
3
public void saveGraph(File file) { BufferedImage image = new BufferedImage( contents.getWidth(), contents.getHeight(), BufferedImage.TYPE_INT_RGB ); Graphics2D g = image.createGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, contents.getWidth(), contents.getHeight()); Statistics.drawGraph(g, contents); g.dispose(); try { if (file != null) ImageIO.write(image, "png", file); else throw new IOException(); } catch (IOException e) { complain(e); } catch (NullPointerException e) { complain(e); } }
81e4debe-9a8f-4991-9ab5-16f3461f8664
3
public Dimension getPreferredSize(JComponent c) { String tipText = ((JToolTip) c).getTipText(); if (tipText == null) return new Dimension(0, 0); textArea = new JTextArea(tipText); rendererPane.removeAll(); rendererPane.add(textArea); textArea.setWrapStyleWord(true); int width = ((JMultiLineToolTip) c).getFixedWidth(); int columns = ((JMultiLineToolTip) c).getColumns(); if (columns > 0) { textArea.setColumns(columns); textArea.setSize(0, 0); textArea.setLineWrap(true); textArea.setSize(textArea.getPreferredSize()); } else if (width > 0) { textArea.setLineWrap(true); Dimension d = textArea.getPreferredSize(); d.width = width; d.height++; textArea.setSize(d); } else textArea.setLineWrap(false); Dimension dim = textArea.getPreferredSize(); dim.height += 1; dim.width += 1; return dim; }
9d711bcc-799a-40b9-8db2-d3f45e5b2634
8
private void send(byte[] contents) throws IOException { checkOpen(); try { byte cs = checksum(contents); /* SOP */ tx.write((byte)0x0f); tx.write((byte)0x0f); /* send bytes, escape if needed */ for (byte b : contents) { if (b == 0x0f || b == 0x05 || b == 0x04) { tx.write((byte)0x05); } tx.write(b); } /* escape the checksum if needed */ if (cs == 0x0f || cs == 0x05 || cs == 0x04) { tx.write((byte)0x05); } tx.write(cs); //checksum for contents tx.write((byte)0x04); //EOP } catch (IOException ioe) { System.out.println("Internal error during send: " + ioe.getMessage()); throw new IOException("Unable to send packet."); } }
3cd4a984-8882-408e-98e6-d067aebb8f23
7
public void select() { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { //1、加载驱动 Class.forName("com.mysql.jdbc.Driver"); String url ="jdbc:mysql://localhost:3306/rock"; //2、建立连接 conn = DriverManager.getConnection(url,"root","123456"); String sql = "select * from emp2"; //3、选择处理块(预处理块) pstmt = conn.prepareStatement(sql); //4、执行 rs = pstmt.executeQuery(); //5、分析结果 while(rs.next()) { System.out.println(rs.getString(2)); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { //6、释放资源 try { if(null != rs) { rs.close(); } if(null !=pstmt) { pstmt.close(); } if(null !=conn) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
37042d58-3c01-4eda-a40b-d2315802afa1
8
public boolean attack(int destx, int desty, boolean returnfire) { //Disables the ability to attack when a unit has already moved positions. if ((x != oldx && y != oldy) && !MoveAndShoot) {return false;} units.Base target = FindTarget(destx, desty, true, false); if (target!=null) { if (inrange(target.x, target.y)) { double damage = DamageFormula(target); target.health-=damage; if (target.health<=0) { damage+=target.health; if (target.bld!=-1) { Game.builds.get(target.bld).Locked=false; } Game.units.remove(target); Game.player.get(owner).kills++; Game.player.get(target.owner).loses++; Game.pathing.LastChanged = System.currentTimeMillis(); } else if (returnfire) {target.attack(x,y,false);} //Increases commander power. Game.player.get(owner).Powerup(damage, false); Game.player.get(target.owner).Powerup(damage, true); return true; } } return false; }
a42494ac-630b-4b3b-9bf9-16e3d86efe1e
5
public BigDecimal variance_as_BigDecimal() { boolean hold = Stat.nFactorOptionS; if (nFactorReset) { if (nFactorOptionI) { Stat.nFactorOptionS = true; } else { Stat.nFactorOptionS = false; } } BigDecimal variance = BigDecimal.ZERO; switch (type) { case 1: case 12: BigDecimal[] bd = this.getArray_as_BigDecimal(); variance = Stat.variance(bd); bd = null; break; case 14: throw new IllegalArgumentException("Complex cannot be converted to BigDecimal"); default: throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!"); } Stat.nFactorOptionS = hold; return variance; }
a5787b8a-d087-445d-b0c4-f18946c73312
9
public void propagateBackNNA(Bin tst) throws IOException{ double sum = 0; int i = 0; Elem tek; if(tst==bins[0]){ constructNet(bins[1].binHead); tek = bins[1].binHead; i=1; } else { updateNet(bins[0].binHead); tek = bins[0].binHead; } //updateNet instead of updateIO in order to reset outputs, makes it slower, worse performance, bigger error for ~5-8 % sum=0; do{ sum=0; while(i<binNo-1){ while(tek!=null){ updateIO(tek); Activation(); Deltas(); Weights(); //printIO(); sum += updateError(); tek=tek.sled; } if(i+1>=binNo) break; tek=bins[++i].binHead; if(tek==tst.binHead) if(i+1>=binNo) break; else tek=bins[++i].binHead; } if(Math.abs(pom-sum)<tolerance) { //System.out.print("Best I can do to match error is "+pom+", you could try different architecture.\n"); break; } pom=sum; //System.out.print(pom+"\n"); i=0; } while (sum>error_tolerance); //VALIDATION sum=0; tek=tst.binHead; while(tek!=null){ updateIO(tek); Activation(); printO(); sum += updateError(); tek=tek.sled; } archError+=sum; }
ee9c78b1-3cab-4833-91b4-03f2be009415
7
public static String averageTimeZone(ArrayList<Kill> Kills) { String result; int[] quartile = new int[3]; int[] hours = new int[24]; int total = 0; for (Kill k : Kills) { hours[k.getKillTime().get(Calendar.HOUR_OF_DAY)]++; } int[] min = new int[] { 0, hours[0] }; for (int i = 0; i < 24; i++) { total = total + hours[i]; if (min[1] > hours[i]) { min[0] = i; min[1] = hours[i]; } } int x = 0; for (int i = min[0]; i < 24 + min[0]; i++) { x = x + hours[i % 24]; if (x < total * 1 / 4) { quartile[0] = i % 24; } else if (x < total / 2) { quartile[1] = i % 24; } else if (x < total * 3 / 4) { quartile[2] = i % 24; } } result = quartile[1] + "h +-" + (quartile[1] - quartile[0]); return result; }
a832b2ef-b9b6-410e-9a0f-899feb2fc16a
4
public BinaryNode search(int key) { BinaryNode result = null; if (left != null && key < elementNumber) { result = left.search(key); } else if (right != null && key > elementNumber) { result = right.search(key); } else { result = this; } return result; }
25141a19-8971-477a-840a-8109f6d64c0a
1
public Hunter(HuntField field) { this.alive = true; this.type = 'H'; this.hunted = 0; this.field = field; synchronized (field) { this.position = new Position(random.nextInt(field.getXLength()), random.nextInt(field.getYLength())); while (field.isOccupied(position)) { this.position = new Position(random.nextInt(field.getXLength()), random.nextInt(field.getYLength())); } field.setItem(this, position); } }
1da0be1e-5419-4f18-a1be-4a818cd1e90d
4
public boolean registryServer(String address, int id) throws RemoteException { /* Was the server registered? * If something fails it will be set to 'false' */ boolean registered = true; //New server InterfaceReplicacao newserver = null; //Looking for the new server try { newserver = (InterfaceReplicacao) Naming.lookup(String.format("rmi://%s/Replica%d", address, id)); } catch (MalformedURLException e) { registered = false; System.err.println("MalformedURLException"); e.printStackTrace(); } catch(NotBoundException e) { registered = false; System.err.println("NotBoundException"); e.printStackTrace(); } /* * Get a server to provide all objects to the new server * If there is not any server, this new server is the first */ InterfaceReplicacao nserver = null; try { //Get a server nserver = nextServer(); String server = String.format("rmi://%s/%s", nserver.getAddress(), String.format("Acesso%d", nserver.getId())); //Command the new server copy all objects from another server registered = newserver.replicaAll(objects, server); } catch (NenhumServidorDisponivelException e) { System.out.println("First server connecting..."); } //Putting the new server with all servers try { Integer sid = new Integer(id); sev.put(sid, newserver); vServers.add(sid); } //Some thing got wrong! catch(NullPointerException e) {registered = false;} System.out.println("New server connected addres: " + address + ", id: " + id); return registered; }
47eb315d-6eb2-4cd0-84e5-69414677ad24
0
public void setId(String value) { this.id = value; }
778c2d68-aca9-416f-b390-f44126cd1c30
8
public Set<Map.Entry<Short,Double>> entrySet() { return new AbstractSet<Map.Entry<Short,Double>>() { public int size() { return _map.size(); } public boolean isEmpty() { return TShortDoubleMapDecorator.this.isEmpty(); } public boolean contains( Object o ) { if (o instanceof Map.Entry) { Object k = ( ( Map.Entry ) o ).getKey(); Object v = ( ( Map.Entry ) o ).getValue(); return TShortDoubleMapDecorator.this.containsKey(k) && TShortDoubleMapDecorator.this.get(k).equals(v); } else { return false; } } public Iterator<Map.Entry<Short,Double>> iterator() { return new Iterator<Map.Entry<Short,Double>>() { private final TShortDoubleIterator it = _map.iterator(); public Map.Entry<Short,Double> next() { it.advance(); short ik = it.key(); final Short key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik ); double iv = it.value(); final Double v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv ); return new Map.Entry<Short,Double>() { private Double val = v; public boolean equals( Object o ) { return o instanceof Map.Entry && ( ( Map.Entry ) o ).getKey().equals(key) && ( ( Map.Entry ) o ).getValue().equals(val); } public Short getKey() { return key; } public Double getValue() { return val; } public int hashCode() { return key.hashCode() + val.hashCode(); } public Double setValue( Double value ) { val = value; return put( key, value ); } }; } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } public boolean add( Map.Entry<Short,Double> o ) { throw new UnsupportedOperationException(); } public boolean remove( Object o ) { boolean modified = false; if ( contains( o ) ) { //noinspection unchecked Short key = ( ( Map.Entry<Short,Double> ) o ).getKey(); _map.remove( unwrapKey( key ) ); modified = true; } return modified; } public boolean addAll( Collection<? extends Map.Entry<Short, Double>> c ) { throw new UnsupportedOperationException(); } public void clear() { TShortDoubleMapDecorator.this.clear(); } }; }
7dcb0c89-5e15-426e-8b2c-8df1c4307d5f
5
private void implyRotationFrictionToMoments() { // If there are no moments, doesn't do anything if (this.moments.isEmpty()) return; ArrayList<Point> momentstobeended = new ArrayList<Point>(); // Goes through all the moments for (Point p: this.moments.keySet()) { double f = this.moments.get(p); // If the moment has run out it is no longer recognised if (Math.abs(f) < getRotationFriction()) { momentstobeended.add(p); continue; } else if (f > 0) f -= getRotationFriction(); else f += getRotationFriction(); // Changes the moment this.moments.put(p, f); } // Removes the unnecessary moments for (int i = 0; i < momentstobeended.size(); i++) this.moments.remove(momentstobeended.get(i)); }
71facc0c-0160-4ee8-a819-04e6db834d27
7
public void renderImage(int xp, int yp, int[] imagePixels, int Width, int Height, boolean fixed) { if (fixed) { xp -= xOffset; yp -= yOffset; } for (int y = 0; y < Height; y++) { int ya = y + yp; for (int x = 0;x < Width; x++) { int xa = x + xp; if (xa < 0 || xa >= width || ya < 0 || ya >= height) continue; int col = imagePixels[x + y * Width]; pixels[xa+ya*width] = col; } } }
a8499373-d247-43dd-932a-c1198fb066da
9
public SoapRequest(Service service, Method method, Object parameters) { //Set the results node resultsNode = method.getResultsNodeName(); //Create new http request request = new javaxt.http.Request(service.getURL()); request.setHeader("Content-Type", "text/xml; charset=utf-8"); request.setHeader("Accept", "text/html, text/xml, text/plain"); //Add SoapAction to the header String action = method.getSoapAction(); if (action!=null) request.addHeader("SOAPAction", action); //Create body StringBuffer body = new StringBuffer(); body.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<soap:Envelope " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Body>"); //Add method tag body.append("<" + method.getName() + " xmlns=\"" + service.getNameSpace() + "\">"); //Insert parameters (inside the method node) if (parameters!=null){ if (method.getParameters().getArray()!=null){ if (parameters instanceof Parameters){ body.append(parameters.toString()); } if (parameters instanceof Parameter){ method.getParameters().setValue((Parameter)parameters); body.append(method.getParameters().toString()); } else if (parameters instanceof String){ body.append(parameters); //assumes parameters is a correctly formatted xml fragment } else if (parameters instanceof String[]){ String[] values = (String[]) parameters; Parameter[] params = method.getParameters().getArray(); if (params!=null){ for (int i=0; i<params.length; i++ ) { String parameterName = params[i].getName(); String parameterValue = values[i]; body.append("<" + parameterName + "><![CDATA[" + parameterValue + "]]></" + parameterName + ">"); } } } } } //Close tags body.append("</" + method.getName() + ">"); body.append("</soap:Body></soap:Envelope>"); this.body = body.toString(); }
cc886561-e299-4412-905e-804215763a03
1
public ICommand getCommand(HttpServletRequest request) { String action = request.getParameter("command"); ICommand command = commands.get(ParserType.valueOf(action.toUpperCase())); if (command == null) { command = (ICommand) new NotFoundCommand(); } return command; }
27b3c2a8-e7cb-4bff-80f1-0a8fc6fda39a
7
@Override public void publishInterruptibly(long sequence, Sequence lowerCursor) throws InterruptedException { int counter = RETRIES; while (sequence - lowerCursor.get() > pendingPublication.length()) { if (--counter == 0) { if (yieldAndCheckInterrupt()) throw new InterruptedException(); counter = RETRIES; } } pendingPublication.set((int) sequence & pendingMask, sequence); // One of other threads has published this sequence for the current thread long cursorSequence = lowerCursor.get(); if (cursorSequence >= sequence) { return; } long expectedSequence = Math.max(sequence - 1L, cursorSequence); long nextSequence = expectedSequence + 1; while (lowerCursor.compareAndSet(expectedSequence, nextSequence)) { if (Thread.interrupted()) throw new InterruptedException(); expectedSequence = nextSequence; nextSequence++; if (pendingPublication.get((int) nextSequence & pendingMask) != nextSequence) { // if exceeds the capacity of pendingPublication, exit break; } } }
f18d741e-48df-407d-81db-feaf1cceacc4
6
public int bestMeleeAtk() { if(c.playerBonus[0] > c.playerBonus[1] && c.playerBonus[0] > c.playerBonus[2]) return 0; if(c.playerBonus[1] > c.playerBonus[0] && c.playerBonus[1] > c.playerBonus[2]) return 1; return c.playerBonus[2] <= c.playerBonus[1] || c.playerBonus[2] <= c.playerBonus[0] ? 0 : 2; }
aeb91ac4-c81c-4d5b-9e7c-e2090c438d26
7
private void addHandlerEdges(final Block block, final Map catchBodies, final Map labelPos, final Subroutine sub, final Set visited) { // (pr) if (visited.contains(block)) { return; } visited.add(block); final Tree tree = block.tree(); Assert.isTrue(tree != null); final Iterator hiter = handlers.values().iterator(); // Iterate over every Handler object created for this FlowGraph while (hiter.hasNext()) { final Handler handler = (Handler) hiter.next(); boolean prot = false; // Determine whether or not the block of interest lies within // the Handler's protected region if (handler.protectedBlocks().contains(block)) { prot = true; } else { final Iterator succs = succs(block).iterator(); while (succs.hasNext()) { final Block succ = (Block) succs.next(); if (handler.protectedBlocks().contains(succ)) { prot = true; break; } } } // If the block of interest lies in a protected region, add an // edge in this CFG from the block to the Handler's "catch block" // (i.e. first block in Handler). Also examine the JumpStmt that // ends the block of interest and add the catch block to its list // of catch targets. // // Note that we do not want the init block to be protected. // This may happen if the first block in the CFG is protected. // // Next, obtain the "catch body" block (contains the real code) // of the method. If no expression tree has been constructed for // it, create a new OperandStack containing only the exception // object and build a new tree for it. // // Finally, recursively add the handler edges for the first block // of the exception handler. if (prot) { // && block != iniBlock) { final Block catchBlock = handler.catchBlock(); final JumpStmt jump = (JumpStmt) tree.lastStmt(); jump.catchTargets().add(catchBlock); addEdge(block, catchBlock); // Build the tree for the exception handler body. // We must have already added the edge from the catch block // to the catch body. final Block catchBody = (Block) catchBodies.get(catchBlock); Assert.isTrue(catchBody != null); if (catchBody.tree() == null) { final OperandStack s = new OperandStack(); s.push(new StackExpr(0, Type.THROWABLE)); buildTreeForBlock(catchBody, s, sub, labelPos, catchBodies); } // (pr) // if(!handler.catchBlock.equals(block)) { addHandlerEdges(catchBlock, catchBodies, labelPos, sub, visited); // } } } }
f12ab134-d5b5-4cfb-8227-48481c002d2e
8
@Override public ResourceTask nextTask(final int taskId) throws Exception { lock.lock(); try { while (true) { // 1. counting tasks: final Range numberRange = numberRangeIterator.next(); if (numberRange != null) { assert (sortingTasksSubmitted == 0); // compose and submit a new counting task: Range alloc = allocMemoryIterator.next(); assert (alloc != null); // NB: memory is divided by "threads" as well as entire the number range. checkAlloc(alloc.length); allocResource -= alloc.length; assert (allocResource >= 0); countingTasksSubmitted++; return new CountingTask(taskId, new Resource(alloc.length), /*digitNumber, */numberRange, radixConcurrentImpl); } // all counting tasks submitted. // wait all the counting tasks to finish completely: while (countingTasksDone < countingTasksSubmitted) { condition.await(); } assert (countingTasksDone == countingTasksSubmitted); if (!integrated) { assert (allocResource == allocatableTotalNumbersMemory); // all the memory is returned // 2. Integrate the Radix. Do not submit special task for that since this is very fast: radixConcurrentImpl.integrateAllDigits(); integrated = true; } if (startedDigit < digitNumber) { startedDigit++; final long writeProvidersBuf = ((writeBuffersRatio - 1) * allocResource)/writeBuffersRatio; radixConcurrentImpl.startDigit(digitNumber, writeProvidersBuf); allocResource -= writeProvidersBuf; // subtract the amount spent for the writing buffers // divide the remaining amount of the memory by the available threads: allocMemoryIterator = new LargeFirstDivisionResultIterator(Util.divideByApproximatelyEqualParts(allocResource, threads)); } // 3. Sorting tasks: final Range digitValueRange = digitValuesRangeIterator.next(); if (digitValueRange != null) { // compose and submit next sorting task: Range alloc = allocMemoryIterator.next(); assert (alloc != null); // memory is divided by "threads" as well as // the digit values range. checkAlloc(alloc.length); allocResource -= alloc.length; assert (allocResource >= 0); sortingTasksSubmitted++; return new SortingTask(taskId, new Resource(alloc.length), digitNumber, digitValueRange, radixConcurrentImpl); } // wait all the sorting tasks to finish: while (sortingTasksDone < sortingTasksSubmitted) { condition.await(); } assert (sortingTasksDone == sortingTasksSubmitted); // 4. finish processing of this digit: radixConcurrentImpl.finishDigit(digitNumber); allocResource += radixConcurrentImpl.getTotalWriteProvidersBuffersLength(); //radixConcurrentImpl = null; assert (allocResource == allocatableTotalNumbersMemory); // next digit: digitNumber++; if (digitNumber == RadixSort.numberOfDigits) { return null; // done, no more tasks. } nextDigit(); // next digit } } finally { lock.unlock(); } }
b1fa4f57-e342-431b-b6d2-c06964dd691a
1
public void removeOnetimeLocals() { block.removeOnetimeLocals(); if (nextByAddr != null) nextByAddr.removeOnetimeLocals(); }
94cab36b-ea0a-4a84-a5a0-20a496cf0bf8
5
public void doLexing() { LexerRule accRule = null; while (finishIndex < input.length() - 1) { while (currentState.isAnyAlive()) { ++finishIndex; LexerRule tmpRule = currentState.getAccepted(); if (tmpRule == null) { } else { accRule = tmpRule; lastIndex = finishIndex - 1; } if (finishIndex < input.length()) { currentState.pushCharToAutomatons(String.valueOf(input.charAt(finishIndex))); } else { break; } } if (accRule == null) { finishIndex = startIndex++; currentState.resetAutomatons(); } else { finishIndex = lastIndex; accRule.doActions(this); accRule = null; currentState.resetAutomatons(); } } }
25ee86d4-007e-467e-a0b4-ce90f82fb032
6
public String nextCDATA() throws JSONException { char c; int i; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); if (end()) { throw syntaxError("Unclosed CDATA"); } sb.append(c); i = sb.length() - 3; if (i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { sb.setLength(i); return sb.toString(); } } }
f475e10d-1cb1-4d98-ac17-46fc1ebfeadf
3
private static void toDescriptor(StringBuffer desc, CtClass type) { if (type.isArray()) { desc.append('['); try { toDescriptor(desc, type.getComponentType()); } catch (NotFoundException e) { desc.append('L'); String name = type.getName(); desc.append(toJvmName(name.substring(0, name.length() - 2))); desc.append(';'); } } else if (type.isPrimitive()) { CtPrimitiveType pt = (CtPrimitiveType)type; desc.append(pt.getDescriptor()); } else { // class type desc.append('L'); desc.append(type.getName().replace('.', '/')); desc.append(';'); } }
774acab1-ee79-427d-9235-cdc1749b7db5
0
@Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub }
6cc305f7-e5f6-4c43-9d64-e091fb5d7aef
1
public long set(long millis, int value) { long timeOnlyMillis = iChronology.getTimeOnlyMillis(millis); int[] ymd = iChronology.gjFromMillis(millis); // First set to start of month... millis = iChronology.millisFromGJ(ymd[0], value, 1); // ...and use dayOfMonth field to check range. int maxDay = iChronology.dayOfMonth().getMaximumValue(millis); if (ymd[2] > maxDay) { ymd[2] = maxDay; } return timeOnlyMillis + iChronology.millisFromGJ(ymd[0], value, ymd[2]); }
2fd30b44-4c25-4aa4-9b42-0e94f40086b7
3
public void findMails( ) { this.ec.clearMails(); File[] path = new File(this.path).listFiles(); for(File f : path) { if(f.isFile() && f.getName().contains(".eml")) { EMail e = new EMail(); e.setFileName(f.getName()); e.parseMail(this.path, f.getName()); e.setId(this.ec.getNewId()); this.ec.addEMail(e); } } }
d4bba0d8-5594-4371-ac8f-71de7bc1087e
4
@Override public String prefix_toString(){ int count = 0; String representation = ""; if(children.length != 0 && count/2 <= children.length){ representation += children[count].prefix_toString(); count++; } representation += root.name+ " "; if(children.length != 0 && count/2 > children.length){ representation += children[count].prefix_toString(); count++; } return representation; }
e96d7518-4168-4f24-a3a3-d02d54617c9b
9
public static void main(String[] args) { if (args.length != 2) { System.out.println("THERE WAS AN ERROR WITH THE INPUTS"); return; } String tfile = ""; // .torrent file to be loaded String sfile = ""; // name of the file to save the data to for (int i = 0; i < args.length; i++) { if (i == 0) { tfile = args[i]; } else if (i == 1) { sfile = args[i]; } } // the following is a check to make sure the command line arguments were // stored correctly System.out.println("tfile: " + tfile); System.out.println("sfile: " + sfile); File file = new File(tfile); long fsize = -1; byte[] tbytes = null; InputStream fstream; try { fstream = new FileInputStream(file); fsize = file.length(); // Initialize the byte array for the file's data tbytes = new byte[(int) fsize]; int point = 0; int done = 0; // Read from the file while (point < tbytes.length && (done = fstream.read(tbytes, point, tbytes.length - point)) >= 0) { point += done; } fstream.close(); } catch (FileNotFoundException e) { return; } catch (IOException e) { return; } // tbytes is the byte array with all metainfo try { TorrentInfo alltinfo = new TorrentInfo(tbytes); PeerHost host = new PeerHost(); Tracker tracker = new Tracker(alltinfo, host); TorrentHandler handler = new TorrentHandler(alltinfo, tracker, sfile); handler.download(); } catch (BencodingException e) { e.printStackTrace(); } }
31b9b4ed-042b-4b6c-80ca-2fdb422c304e
3
private void CreateCourse() { //these will help set and control logic for courese points = new int[4]; passedPoint = new boolean[4]; passedPointLoc = new int[4]; for (int i = 0; i < points.length; i++) { points[i] = random.nextInt(1500 + 200); passedPoint[i] = false; } for (int j = 0; j < points.length; j++) { //used to reset the x after finish line is made x += 125; //creates the four segments of th course for (int i = 0; i < points[j]; i++) { //create course object Course segment = new Course(x, y, j); //add that course to the CourseList courseList.add(segment); y -= 1; } //we need four indexes of section "finish lines" passedPointLoc[j] = courseList.size(); //this will set a end of point //first make room to set the point y -= 40; x -= 125; Course segment = new Course(x, y, 4); courseList.add(segment); //make room for the finish line y -= 40; } System.out.println(courseList.size()); //courseList.get(6).changeColor(); }
48e8f327-7175-4914-8c2a-04a4eb9161be
7
public boolean moveable(Game game, Piece piece, Square targetSquare) { Chess chess = game.getChess(); Square square = piece.getCurrent(); Piece targetPiece = chess.locatePiece(targetSquare); // if (chess.isLeapOver(piece.getCurrent(), targetSquare)) { return false; } else if (targetPiece != null && targetPiece.getColor().equals(piece.getColor())) { return false; } else if (this.kingWillBeChecked(game, piece, targetSquare)) { return false; } else { return Math.abs(targetSquare.getFile() - square.getFile()) <= 1 && Math.abs(targetSquare.getRank() - square.getRank()) <= 1 && (targetSquare.getFile() != square.getFile() || targetSquare.getRank() != square.getRank()); } }
20c7b55e-165b-43be-8af4-29ebe3b6716b
5
public void addBan(String pname) { try { String[] banList = plugin.getBans(); ArrayList<String> arraylist = new ArrayList<String>(); for (String p : banList) { if (p != pname) { arraylist.add(p); } } new File(plugin.getDataFolder() + File.separator + "bans.txt") .createNewFile(); FileWriter fstream = new FileWriter(new File(plugin.getDataFolder() + File.separator + "bans.txt")); BufferedWriter out = new BufferedWriter(fstream); for (String b : arraylist) { if (!b.equalsIgnoreCase(pname)) { out.write(b + "\n"); } } out.write(pname + "\n"); out.close(); fstream.close(); } catch (IOException ex) { plugin.logger(Level.WARNING, "Player ban did not save"); } }
f6439f43-bed1-4929-906c-5e4fc94bdc03
8
public static void main(String[] args) { if (args.length == 0) { System.err.println("Please provide a text file name"); System.exit(1); } String fileName = args[0].toString(); int count = DEFAULT_COUNT; if (args.length > 1) { try { count = Integer.parseInt(args[1]); } catch (NumberFormatException e) { System.err.println("Number of words " + args[1] + " must be an integer."); System.exit(1); } } AbstractCharReader charReader = charReaders.get(CharReaders.ASCII); if (args.length > 2) { String argument = args[2].toString().toUpperCase(); try { charReader = charReaders.get(CharReaders.valueOf(argument)); } catch(IllegalArgumentException iae) { System.err.println("CharReader " + args[2] + " is invalid."); System.exit(1); } } IWordCountingStrategy strategy = strategies.get(Strategies.TRIE); if (args.length > 3) { String argument = args[3].toString().toUpperCase(); try { strategy = strategies.get(Strategies.valueOf(argument)); } catch(IllegalArgumentException iae) { System.err.println("Strategy " + args[3] + " is invalid."); System.exit(1); } } List<String> words = new WordCounter(fileName, count, charReader,strategy) .getTopWords(); for (String word : words) { System.out.println(word); } }
a5a75e7a-16d9-440b-aa5f-eeca052846de
0
public static SharedTorrent fromFile(File source, File destDir) throws IllegalArgumentException, IOException { FileInputStream fis = new FileInputStream(source); byte[] data = new byte[(int)source.length()]; fis.read(data); fis.close(); return new SharedTorrent(data, destDir); }
8e9ef5f1-6cd9-4095-a532-249dfbb12596
2
@Override public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String [] movieInfoStrings = line.split("%%%"); assert(movieInfoStrings.length==3); int year=0; try { year= Integer.parseInt(movieInfoStrings[1]); } catch (Exception e) { System.out.println("It's not value!\n"); for(String tempString:movieInfoStrings){ System.out.println(tempString+"\n"); } System.out.println(movieInfoStrings.length); System.out.println(line); } context.write(new IntWritable(year), new Text(movieInfoStrings[2])); }
0acbdc38-f658-4896-a6d4-c5914db59ebd
9
public ConnectionThread(final int id, final Socket socket) { ID = id; try { bReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); pWriter = new PrintWriter(socket.getOutputStream(), true); } catch(Exception e) { e.printStackTrace(); } thread = new Thread() { @Override public void run() { try { IP = socket.getInetAddress() + ":" + socket.getPort() + " connected!"; System.out.println(IP); IP = socket.getInetAddress().toString(); while(!socket.isClosed()) { if(bReader.ready()) { String clientMessage = bReader.readLine(); System.out.println(clientMessage); if (clientMessage == null) { //system.out.println("null"); } else if(clientMessage.contains("/connected")) { Main.userList.add(new User(id, clientMessage.substring(11))); pWriter.println("/id " + id); Main.writeToAll("/userlist " + Main.getUserList()); } else if(clientMessage.contains("/name")) { Main.writeToAll("/console ** " + Main.getUserFromId(Integer.parseInt((clientMessage.split(" ")[1]).split("\\\\")[0])) + " CHANGED THEIR NAME TO " + Main.parseName(clientMessage) + " **"); Main.writeToAll("/update " + Main.updateUser(clientMessage)); } else if(clientMessage.contains("/file")) { Main.receiveAndBounceMessage(clientMessage, socket); } else if(clientMessage.contains("/disconnect")) { Main.writeToAll("/remove " + Main.removeUser(clientMessage)); Main.ips.remove(IP); thread.stop(); } else Main.writeToAll("/msg " + clientMessage); } } } catch (Exception e) { e.printStackTrace(); } } }; thread.start(); }
ce0d939b-a367-4e42-9752-f13222c3f7b3
3
public boolean calculate() { //nope, actually change it if (seqChange.isSnp()) setSNP(); if (seqChange.isIns()) setINS(); if (seqChange.isDel()) setDEL(); return this.transcriptChange(); }
31bf46c1-9fad-4567-8220-7d25136dff1d
8
public Frame9() { try{ Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL,USER, PASS); statement = conn.createStatement(); }catch(SQLException se){ se.printStackTrace(); }catch(Exception e){ e.printStackTrace(); } setTitle("Blok D, 1 - 33 ; 68 - 73"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 1076, 604); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); comboBox = new JComboBox(); comboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (comboBox.getSelectedItem().equals("")){ textField.setText(""); textField_1.setText(""); textField_2.setText(""); textField_3.setText(""); textField_4.setText(""); textField_5.setText(""); isSelected = false; } else{ isSelected = true; String noRumah = (String) comboBox.getSelectedItem(); rumah = new Rumah(noRumah); String sql = "SELECT * FROM `tabel_rumah` WHERE noRumah='"+rumah.getNoRumah()+"';"; try { ResultSet rs = statement.executeQuery(sql); if (!rs.isBeforeFirst()){ System.out.println("Tabel Kosong"); } while(rs.next()){ rumah.setIDRumah(rs.getInt("idRumah")); rumah.setTipe(rs.getString("tipeRumah")); rumah.setLT(rs.getInt("LT")); rumah.LTAwal = rs.getInt("LTAwal"); rumah.setLB(rs.getInt("LB")); rumah.setHargaAwal(rs.getInt("HargaAwal")); rumah.setHargaNett(rs.getInt("HargaNett")); rumah.setIsBought(rs.getBoolean("isBought")); rumah.setIsEdited(rs.getBoolean("isEdited")); rumah.setIsLocked(rs.getBoolean("isLocked")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } textField.setText(rumah.getTipe()); textField_1.setText(rumah.getNoRumah()); textField_3.setText(rumah.getStrLT()); textField_2.setText(rumah.getStrLB()); textField_4.setText(rumah.getStrHN()); textField_5.setText(rumah.getStrIsBought(rumah.getIsBought())); } } }); comboBox.setFont(new Font("Tahoma", Font.PLAIN, 12)); comboBox.setModel(new DefaultComboBoxModel(new String[] {"", "D-1", "D-2", "D-3", "D-4", "D-5", "D-6", "D-7", "D-8", "D-9", "D-10", "D-11", "D-12", "D-13", "D-14", "D-15", "D-16", "D-17", "D-18", "D-19", "D-20", "D-21", "D-22", "D-23", "D-24", "D-25", "D-26", "D-27", "D-28", "D-29", "D-30", "D-31", "D-32", "D-33", "D-68", "D-69", "D-70", "D-71", "D-72", "D-73"})); comboBox.setBounds(322, 394, 63, 20); contentPane.add(comboBox); JPanel panel = new JPanel(); panel.setLayout(null); panel.setBorder(new LineBorder(new Color(0, 0, 0))); panel.setBounds(418, 389, 179, 158); contentPane.add(panel); JLabel label = new JLabel("Kavling"); label.setBounds(10, 11, 46, 14); panel.add(label); JLabel label_1 = new JLabel("No Rumah"); label_1.setBounds(10, 33, 55, 14); panel.add(label_1); JLabel label_2 = new JLabel("LB"); label_2.setBounds(10, 80, 55, 14); panel.add(label_2); JLabel label_3 = new JLabel("LT"); label_3.setBounds(10, 58, 46, 14); panel.add(label_3); JLabel label_4 = new JLabel("Harga"); label_4.setBounds(10, 105, 55, 14); panel.add(label_4); JLabel label_5 = new JLabel("Status"); label_5.setBounds(10, 130, 55, 14); panel.add(label_5); textField = new JTextField(); textField.setText((String) null); textField.setColumns(10); textField.setBounds(71, 8, 98, 20); panel.add(textField); textField_1 = new JTextField(); textField_1.setText((String) null); textField_1.setColumns(10); textField_1.setBounds(71, 30, 98, 20); panel.add(textField_1); textField_2 = new JTextField(); textField_2.setText((String) null); textField_2.setColumns(10); textField_2.setBounds(71, 77, 98, 20); panel.add(textField_2); textField_3 = new JTextField(); textField_3.setText((String) null); textField_3.setColumns(10); textField_3.setBounds(71, 55, 98, 20); panel.add(textField_3); textField_4 = new JTextField(); textField_4.setText((String) null); textField_4.setColumns(10); textField_4.setBounds(71, 105, 98, 20); panel.add(textField_4); textField_5 = new JTextField(); textField_5.setColumns(10); textField_5.setBounds(71, 127, 98, 20); panel.add(textField_5); JLabel lblPilihanRumah = new JLabel("Pilihan Rumah :"); lblPilihanRumah.setFont(new Font("Tahoma", Font.PLAIN, 12)); lblPilihanRumah.setBounds(207, 396, 90, 14); contentPane.add(lblPilihanRumah); JButton btnNewButton = new JButton("Kembali ke Peta Awal"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { setVisible(false); PetaAwal frame = new PetaAwal(); frame.setVisible(true); } }); btnNewButton.setBounds(646, 431, 172, 30); contentPane.add(btnNewButton); JButton btnNewButton_1 = new JButton("Masuk ke Menu Rumah"); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (isSelected){ MainRumah.noRumahDariPeta = rumah.getNoRumah(); setVisible(false); MainRumah frameMain = new MainRumah(); frameMain.setVisible(true); } else if (!isSelected){ JOptionPane.showMessageDialog(null, "Rumah belum dipilih, silahkan pilih terlebih dahulu"); } } }); btnNewButton_1.setBounds(646, 390, 173, 30); contentPane.add(btnNewButton_1); JLabel lblNewLabel = new JLabel(""); lblNewLabel.setIcon(new ImageIcon(Frame9.class.getResource("/gambar/Frame 8.jpg"))); lblNewLabel.setBounds(10,33,1036, 350); contentPane.add(lblNewLabel); JLabel labelKeterangan = new JLabel("Blok D, 1 - 33 ; 68 - 73"); labelKeterangan.setHorizontalAlignment(SwingConstants.CENTER); labelKeterangan.setFont(new Font("Monospaced", Font.BOLD, 20)); labelKeterangan.setBounds(10, 0, 1036, 41); contentPane.add(labelKeterangan); }
e2d85bea-25aa-4e90-a113-c34a567a6318
0
public UnknownExcelReport1(File file) { super(file); }
ce4d04f3-557c-491f-99b8-99aed642a642
8
private void JTreeContaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JTreeContaMouseClicked DefaultMutableTreeNode node = (DefaultMutableTreeNode) JTreeConta.getLastSelectedPathComponent(); if (node == null){ return; } else{ if (this.operacion!="MODIFICAR"){ if (JTreeConta.isEnabled()){ mensajeError(" "); } Object nodeInfo = node.getUserObject(); Cuenta loadcuenta = (Cuenta) nodeInfo; this.jTextField5.setText(""+loadcuenta.getNumero_C()); this.jTextField1.setText(loadcuenta.getNombre_C()); this.jTextField2.setText(loadcuenta.getCodigo_PC()); if(loadcuenta.isImputable_C()) jRadioButton2.setSelected(true); else jRadioButton1.setSelected(true); } else{ mensajeError(" "); Object nodeInfo = node.getUserObject(); Cuenta loadcuenta = (Cuenta) nodeInfo; //VERIFICAR DE ACA SI ES IMPUTABLE O NO if (!loadcuenta.isImputable_C()){ jButton6.setEnabled(true); if (this.hayLugarEnPlan(loadcuenta.getNumero_C(),loadcuenta.getCodigo_PC())){ jTextField3.setText(this.codigoPlanDisponible(loadcuenta.getNumero_C(),loadcuenta.getCodigo_PC())); } else{ jButton6.setEnabled(false); mensajeError("La Cuenta que seleccionó ya alcanzó su limite (9 ó 99)."); } } else{ jButton6.setEnabled(false); mensajeError("Para MODIFICAR una CUENTA debe SELECCIONAR un TÍTULO"); } } } //si hace doble click es como dar de alta if((evt.getClickCount()==2)&&(JTreeConta.isEnabled())){ altaCuenta (); } }//GEN-LAST:event_JTreeContaMouseClicked
ad29b049-a4a4-4cdb-a038-dc36acc0d5cb
8
@Override public boolean addCommand(CommandBase command) { CommandDescriptor descriptor = command.getDescriptor(); if (!(descriptor instanceof Dispatchable)) { throw new IllegalArgumentException("The given command is not dispatchable"); } // Remove command from old dispatcher and set this one Dispatcher oldDispatcher = descriptor.getDispatcher(); if (oldDispatcher != null) { oldDispatcher.removeCommand(command); } ((Dispatchable)descriptor).setDispatcher(this); this.commands.put(descriptor.getName().toLowerCase(), command); if (!(command instanceof AliasCommand)) { for (AliasConfiguration alias : descriptor.getAliases()) { if (alias.getDispatcher() == null) { this.addCommand(new AliasCommand(alias, command)); } else { CommandBase aliasDispatcher = getManager().getCommand(alias.getDispatcher()); if (aliasDispatcher == null || !(aliasDispatcher instanceof Dispatcher)) { throw new IllegalArgumentException("Cannot add alias to dispatcher! Command missing or is not a dispatcher."); } ((Dispatcher)aliasDispatcher).addCommand(new AliasCommand(alias, command)); } } } if (command instanceof ContainerCommand) { ((ContainerCommand)command).registerSubCommands(); } return true; }
a66f9f24-2b0d-47ee-8b70-ae2fe6d102ee
1
public List<Double> getColumn() { if (column == null) { column = new ArrayList<Double>(); } return this.column; }
08201688-409c-4821-8d9b-524c9d321fcb
4
@Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; for (int y = 0; y < Board.getHeight(); ++y ) { for (int x = 0; x < Board.getWidth(); ++x) { g2.setColor(board.getBackgroundColor()); g2.fill(new Rectangle(GlobalPositioning.getXPixel(x), GlobalPositioning.getYPixel(y), Board.getSquareWidth(), Board.getSquareHeight())); } } paintEnemyPath(g2, board.getEnemyWaves().getEnemyPath()); Placeable obj = board.getCastle(); paintPlaceable(obj, g2); paintAllTowers(g2); paintAllActiveEnemies(g2); paintAllShoots(g2); paintInfo(g2); if (nothingIsHighlighted) return; if (higlightisObj) { fillInHighlightedObj(g2); } else { fillInHighlightedPoint(g2); } paintInfo(g2); }
70662ca4-dae5-45fe-9779-93631623d3f4
2
public List<Administrateur> ListerAdministrateurs() { try { String sql = "SELECT * FROM User WHERE role='Administrateur'"; ResultSet rs = crud.exeRead(sql); List<Administrateur> liste = new ArrayList<Administrateur>(); while (rs.next()) { Administrateur a = new Administrateur(); a.setLogin(rs.getString("login")); a.setNom(rs.getString("nom")); a.setPrenom(rs.getString("prenom")); a.setTelephone(rs.getInt("telephone")); liste.add(a); } return liste; } catch (SQLException ex) { Logger.getLogger(AdministrateurDAO.class.getName()).log(Level.SEVERE, null, ex); return null; } }
2e28b39d-1599-448d-93be-678cefaa459e
9
public VOCheckIndex checkIndex(VOBackupIndex backupIndex, final boolean checkExistsFile, final boolean checkFileCheckSum) { VOCheckIndex result = new VOCheckIndex(); if (CollectionUtils.isNotEmpty(backupIndex.getBackupFileList())) { for (VOBackupFile voBackupFile : backupIndex.getBackupFileList()) { if (!voBackupFile.isDirectory() && (voBackupFile.getSize() > 0)) { if (StringUtils.isNotBlank(voBackupFile.getFileHash())) { Path dataPath = getRepoDataPath(voBackupFile.getFileHash()); if (checkExistsFile) { if (!Files.exists(dataPath)) { result.addNonExistData(voBackupFile.getPath()); } } if (checkFileCheckSum) { if (StringUtils.isNotBlank(voBackupFile.getCheckSumBck())) { // TODO Lebeda - implement check checksum } else { result.addNonExistDataCheckSum(voBackupFile.getPath()); } } } else { result.addNonExistDataLink(voBackupFile.getPath()); } } } } return result; }
53ee6f74-8674-4ac0-82ac-b8b7afc9e6c8
0
public boolean areTherePriceForQuantity (int productPackQuantity) { return prices.containsKey(productPackQuantity); }
5baaeb75-5148-4125-a9a1-fdf10f2fe279
7
public boolean equals(Object _other) { if (_other == null) { return false; } if (_other == this) { return true; } if (!(_other instanceof UserPk)) { return false; } final UserPk _cast = (UserPk) _other; if (id != _cast.id) { return false; } if (email == null ? _cast.email != email : !email.equals( _cast.email )) { return false; } if (idNull != _cast.idNull) { return false; } return true; }
1747e6b5-3393-406b-8361-cac7c936ce55
2
private int getItemIndexByElementName(String elementName) { int result = -1; Item [] items = tree.getItems(); for(int i = 0; i < items.length; i++) { if(items[i].getText().equals(elementName)) { return i; } } return result; }
9c2f8a53-cb70-4fb0-9b42-ae81b5f6959f
0
public String getImportFileFormat() { return (String) importFormatComboBox.getSelectedItem(); }
5fadbf8d-66a8-47cb-862d-a0d54c25faaa
1
@Override public String prepareConsoleMessage(int type, String msg, Throwable throwable) { StringWriter stackTrace = new StringWriter(); if (throwable != null) { throwable.printStackTrace(new PrintWriter(stackTrace)); } return (Logger.MSG_TYPE_STRING[type] + ": " + msg + stackTrace.toString()); }
c9cc27f9-c167-40da-8881-23e30838e636
1
public static NoteEditorFrame getInstance(){ if (instance == null){ instance = new NoteEditorFrame(); } return instance; }
324b8e57-2ad3-4032-82ff-5c8c449a0b7c
9
public Project2_Move_Thompson getRandomMove(int RANDOMIZATION_ALGORITHM) { //Create a list to hold all of our pieces. java.util.ArrayList<Integer> pieces = new java.util.ArrayList<Integer>(); //Find all our pieces for(int i = 0; i < 64; i++) { if(color[i] ==DARK) { pieces.add(i); } } //Create an array for randomization. int[] A = new int[pieces.size()]; for(int i = 0; i < pieces.size(); i++) A[i] = Integer.parseInt(pieces.get(i).toString()); //Depending on what randomization algorithm was chosen, randomize our pieces. if(RANDOMIZATION_ALGORITHM == 0) Project2_RandomizerUtils_Thompson.Permute_By_Sorting(A); else Project2_RandomizerUtils_Thompson.Randomize_In_Place(A); int randomPieces = A[0]; int next = 0; /* * Some pieces are going to trapped and unable to move * To fix this, let's iterative through our random piece list until we find a free piece. * At that point, take the first avialable move since we chose a piece randomly. */ while(next < A.length) { randomPieces = A[next]; TreeSet moves = this.gen(); Iterator possibleMove = moves.iterator(); //Iterate over the available moves. while(possibleMove.hasNext()) { Project2_Move_Thompson curr = (Project2_Move_Thompson)possibleMove.next(); //Is this move for our chosen piece. if(curr.from == randomPieces) { //We need to make sure the move is legal if(this.makeMove(curr)) { //Undo the move so we can return it. this.takeBack(); try{ System.out.println("Random Move: " + curr.from + " to " + curr.to); }catch(Exception ex) { } return curr; } } } next++; } return null; }
15e2f7b5-8dc5-4ac3-bdc7-46c455c064b5
5
private synchronized void integrate() { //в этом методе движок расчитывает, как взаимодействуют объекты for (PhysicalBody physBody : physBodies.values()) { Vector3d resultForce = new Vector3d(); for (ForceField forceField : forceFields.values()) { Vector3d anotherForce = forceField.forceForPhysicalBody(physBody); //узнаем значение каждой силы, пораждаемой каждым полем if (anotherForce != null) resultForce.add(anotherForce); } physBody.getCenter().setForce(resultForce); for (Plane plane : physBody.getPlanes()) { //расчитываем световой поток через каждую плоскость double resultFlux = 0; for (Illuminant lightSource : lightSources.values()) { resultFlux += lightSource.getRadiantFlux(plane); } plane.setRadiantFlux(resultFlux); } physBody.integrate(dT); //изменить параметры тела } notifyAll(); }
a40eacfb-11be-4e6a-85c5-956db85b189a
7
public static void main(String[] args) { args = getCombinedArgs(args); String challengerBot = parseStringArgument("bot", args, "ERROR: Pass a bot with -bot, eg: -bot voidious.Dookious 1.573c"); String challengeFile = parseStringArgument("c", args, "ERROR: Pass a challenge file with -c, eg: -c challenges" + SLASH + "testbed.rrc"); int seasons = -1; try { seasons = Integer.parseInt(parseStringArgument("seasons", args, "ERROR: Pass number of seasons with -seasons, eg: -seasons 10")); } catch (NumberFormatException nfe) { // semi-expected } int threads = -1; String threadsArg = parseStringArgument("t", args); if (threadsArg != null) { try { threads = Integer.parseInt(threadsArg); } catch (NumberFormatException nfe) { // semi-expected } } boolean forceWikiOutput = parseBooleanArgument("wiki", args); boolean smartBattles = parseBooleanArgument("smart", args); if (challengerBot == null || challengeFile == null || seasons == -1) { printHelp(); return; } RoboRunner runner = new RoboRunner(challengerBot, challengeFile, seasons, threads, forceWikiOutput, smartBattles); if (runner.isMissingBots()) { System.out.println("Aborted due to missing bots."); System.out.println(); } else { runner.runBattles(); runner.shutdown(); } }
996d5487-280a-44a5-8a0c-e6114e28d875
2
public void fireModifiedStateChangedEvent(Document doc) { modifiedStateChangedEvent.setDocument(doc); for (int i = 0, limit = documentListeners.size(); i < limit; i++) { ((DocumentListener) documentListeners.get(i)).modifiedStateChanged(modifiedStateChangedEvent); } for (int i = 0, limit = outlinerDocumentListeners.size(); i < limit; i++) { ((DocumentListener) outlinerDocumentListeners.get(i)).modifiedStateChanged(modifiedStateChangedEvent); } // Cleanup modifiedStateChangedEvent.setDocument(null); }
2b36d6df-4518-49b8-8033-989704a58f85
0
private void createFht() { fht = new FastHashTable<Integer,Short>(N,M,K,W,WORD,BITS); table = new Hashtable<Integer,Short>(N); }
7396d95f-1f24-4d3d-81c3-4df4de2182a6
8
public List<Person> getFriendsList(String accessToken) throws OAuthError { String basicInfoUrl = Constants.FB_FRIENDS_LIST_URI; List<Person> personList = new ArrayList<Person>(); try { String charset = "UTF-8"; List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("access_token", accessToken)); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(basicInfoUrl + "?" + URLEncodedUtils.format(params, charset)); InputStream response = client.execute(httpGet).getEntity() .getContent(); logger.debug("bp response received: " + response); BufferedReader rd = new BufferedReader(new InputStreamReader( response)); String message = ""; String lineData; while ((lineData = rd.readLine()) != null) { message += lineData; } logger.debug("bp friends list received: " + message); if (message != null && message.contains("error")) { OAuthErrorHandler.handle(message); } else if (message != null) { personList = extractFriendsList(message); } } catch (UnsupportedEncodingException e) { logger.error("UnsupportedEncodingException received: ", e); } catch (IllegalStateException e) { logger.error("IllegalStateException received: ", e); } catch (ClientProtocolException e) { logger.error("ClientProtocolException received: ", e); } catch (IOException e) { logger.error("IOException received: ", e); } return personList; }
8186f41a-d600-4f24-bdb5-0af7c3b8875b
3
@WebMethod(operationName = "ReadUser") public ArrayList<User> ReadUser(@WebParam(name = "user_id") String user_id) { User user = new User(); ArrayList<User> users = new ArrayList<User>(); ArrayList<QueryCriteria> qc = new ArrayList<QueryCriteria>(); if(!user_id.equals("-1")){ qc.add(new QueryCriteria("user_id", user_id, Operand.EQUALS)); } ArrayList<String> fields = new ArrayList<String>(); ArrayList<QueryOrder> order = new ArrayList<QueryOrder>(); try { users = user.Read(qc, fields, order); } catch (SQLException ex) { Logger.getLogger(JAX_WS.class.getName()).log(Level.SEVERE, null, ex); } if(users.isEmpty()){ return null; } return users; }