text
stringlengths
14
410k
label
int32
0
9
public String toString(){ String res = new String(); if(msg != null) res += msg; if(codErr != null) res += !res.isEmpty() ? " - " + codErr : codErr; if(sourceException != null) res += !res.isEmpty() ? "\n" + sourceException : sourceException; return res; }
5
public ArrayList<File> indexSearch(String searchPath, String searchKey) { ArrayList<File> matches = new ArrayList<File>(); for(File searchSubject : indexFiles(searchPath)) { if(searchSubject.isDirectory()) { for(File searchSubjectSub : indexSearch(searchSubject.getAbsolutePath(), searchKey)) { matches.add(searchSubjectSub); } } else { if(searchSubject.getAbsolutePath().contains(searchKey)) { if(searchSubject.getName().charAt(0) != '.') { if(searchSubject.isDirectory()) { matches.add(searchSubject); } else if(URLConnection.guessContentTypeFromName(searchSubject.getName()) != null) { if(URLConnection.guessContentTypeFromName(searchSubject.getName()).substring(0, 5).equalsIgnoreCase("image")) { matches.add(searchSubject); } } } } } } return matches; }
8
private void playlistEditMenu() { System.out.println(" Edit Menu "); System.out.println("1. |Create a playlist |"); System.out.println("2. |Add song to a playlist |"); System.out.println("3. |Delete a playlist |"); System.out.println("4. |Delete a song from a playlist |"); System.out.println("0. |Return |"); int option; option = new Scanner(System.in).nextInt(); switch (option) { case 1: createPlaylist(); break; case 2: addSongToPlaylist(); break; case 3: deletePlaylist(); break; case 4: deleteFromPlaylist(); break; case 0: playlistMenu(); break; } }
5
public CtClass getType() throws NotFoundException { int type = etable.catchType(index); if (type == 0) return null; else { ConstPool cp = getConstPool(); String name = cp.getClassInfo(type); return thisClass.getClassPool().getCtClass(name); } }
1
public void draw(Graphics2D g, Player player) { int Px = player.getScreenXpos()/32; //get row number int Py = (player.getScreenYpos()/32); int arroundX = 16; int arroundY = 10; int someX = Px-arroundX; int someXMax = Px+arroundX; int someY = Py-arroundY; int someYMax = Py+arroundY; for(int row = someY; row < someYMax; row ++){ for(int col = someX; col < someXMax; col ++){ if(row >= 0 && row < mapYRows) ; else continue; if(col >= 0 && col < mapXRows) ; else continue; if (map[row][col] == 0) continue; final int rc = map[row][col]; final int r = rc / numTilesAcross; final int c = rc % numTilesAcross; //TODO only draw a selection of images, not the entire map g.drawImage(tiles[r][c].getImage(), (int) x + (col * tileSize), (int) y + (row * tileSize), null); } } // for (int row = rowOffset; row < (rowOffset + numRowsToDraw); row++) { // // if (row >= mapYRows) // break; // // for (int col = colOffset; col < (colOffset + numColsToDraw); col++) { // // if (col >= mapXRows) // break; // // if (map[row][col] == 0) // continue; // // final int rc = map[row][col]; // final int r = rc / numTilesAcross; // final int c = rc % numTilesAcross; // // System.out.println(r + " " + c + " " + numTilesAcross + " " + rc/numTilesAcross); // // //TODO only draw a selection of images, not the entire map // g.drawImage(tiles[r][c].getImage(), (int) x + (col * tileSize), // (int) y + (row * tileSize), null); // } // } }
7
@Override public Object promptForAnswer() { HashMap<Integer, Integer> userAnswer = new HashMap<Integer, Integer>(); for (int i=1; i<=col1Choices.size(); i++){ int choice = InputHandler.getInt("Which item in column 2 matches item "+i+" from column 1?"); userAnswer.put(i, choice); } return userAnswer; }
1
public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } }
9
public static SignalAspect fromOrdinal(int ordinal) { if (ordinal < 0 || ordinal >= VALUES.length) return SignalAspect.RED; return VALUES[ordinal]; }
2
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Player player = (Player) table.getValueAt(row, PlayersTable.PLAYER_COLUMN); NationType nationType = ((Nation) table.getValueAt(row, PlayersTable.NATION_COLUMN)).getType(); JLabel label; switch(advantages) { case FIXED: label = new JLabel(Messages.message(nationType.getNameKey())); break; case SELECTABLE: if (player == null) { return new JLabel(Messages.message(nationType.getNameKey())); } else { return new JLabel(Messages.message(player.getNationType().getNameKey())); } case NONE: default: label = new JLabel(Messages.message("model.nationType.none.name")); break; } if (player != null && player.isReady()) { label.setForeground(Color.GRAY); } else { label.setForeground(table.getForeground()); } label.setBackground(table.getBackground()); return label; }
6
public void add(UnitsValue<?> other) { mValue += mUnits.convert(other.mUnits, other.mValue); }
1
*/ public boolean processAtSampling(final String line) { if (line == null) { return false; } final Matcher matcherBegin = this.patternBegin.matcher(line); final Matcher matcherEnd = this.patternEnd.matcher(line); final Matcher matcherCritical = this.patternCritical.matcher(line); final Matcher matcherException = this.patternException.matcher(line); final Matcher matcherError = this.patternError.matcher(line); final Matcher matcherNull = this.patternError.matcher(line); if (matcherBegin.matches()) { this.termType = TermType.begin; } else if (matcherEnd.matches()) { this.termType = TermType.end; } else if (matcherCritical.matches()) { this.termType = TermType.criticalerror; } else if (matcherNull.matches()) { this.termType = TermType.nullptr; } else if (matcherException.matches()) { this.termType = TermType.exception; } else if (matcherError.matches()) { this.termType = TermType.error; } // End of the if - else // return this.processTime(line); }
7
public void randTestQual(int numTests, int lenMask, long seed) { Random rand = new Random(seed); for( int t = 0; t < numTests; t++ ) { String seq = "", qual = ""; int len = (rand.nextInt() & lenMask) + 10; // Randomly select sequence length seq = randSeq(len, rand); // Create a random sequence qual = randQual(len, rand); // Create a random quality String fullSeq = seq + "\t" + qual; if( verbose ) System.out.println("DnaAndQualitySequence test:" + t + "\tlen:" + len + "\t" + seq); DnaAndQualitySequence bseq = new DnaAndQualitySequence(seq, qual, FastqVariant.FASTQ_SANGER); if( !fullSeq.equals(bseq.toString()) ) throw new RuntimeException("Sequences do not match:\n\tOriginal:\t" + fullSeq + "\n\tDnaAndQSeq:\t" + bseq); } }
3
@Override public void setPosition( float x, float y, float z ) { super.setPosition( x, y, z ); // Make sure OpenAL information has been created if( sourcePosition == null ) resetALInformation(); else positionChanged(); // put the new position information into the buffer: sourcePosition.put( 0, x ); sourcePosition.put( 1, y ); sourcePosition.put( 2, z ); // make sure we are assigned to a channel: if( channel != null && channel.attachedSource == this && channelOpenAL != null && channelOpenAL.ALSource != null ) { // move the source: AL10.alSource( channelOpenAL.ALSource.get( 0 ), AL10.AL_POSITION, sourcePosition ); checkALError(); } }
5
public void remove(T data) throws Exception { Node<T> currNode; Node<T> prevNode; if (head == null) { throw new ListEmptyException(); } else { // find the node with the data in it // adjust the links so the Node is removed from the chain of Nodes currNode = head; prevNode = head; while (currNode != null) { if (currNode.getData().compareTo(data) == 0) { // found the data we are looking for if (currNode == head) { // reset head and you're done! head = head.getNext(); return; } else { prevNode.setNext(currNode.getNext()); return; } } else { // didn't find it yet, continue on to next node prevNode = currNode; currNode = currNode.getNext(); } } // exhausted list, didn't find a match throw new NotFoundException(); } }
4
public void Init(ContentManager manager) { initBlocks(manager.getBlockManager()); initPackets(manager.getPacketManager()); }
0
public void actionPerformed(ActionEvent event) { frame.close(); }
0
private final void remove(int[] cursorArray) { if (cursorArray[1] < cursorArray[2]) { if (this.head > this.tail) { copy(); } final int length = length(); System.arraycopy(this.content[this.cIdx], this.head, this.content[this.cIdxNext], StringBuilder.PATTERN_SIZE, cursorArray[1]); System.arraycopy(this.content[this.cIdx], this.head + cursorArray[2], this.content[this.cIdxNext], StringBuilder.PATTERN_SIZE + cursorArray[1], length - cursorArray[2]); switchBuffer(); this.head = StringBuilder.PATTERN_SIZE; this.tail = (StringBuilder.PATTERN_SIZE + length) - (cursorArray[2] - cursorArray[1]); cursorArray[0] = cursorArray[2] = cursorArray[1]; return; } final int cursor = cursorArray[0]; if ((this.head == this.tail) || (cursor < 0)) { cursorArray[0] = 0; return; } if (cursor == 0) { removeFirst(); } else if (cursor == (length() - 1)) { removeLast(); } else { final int length = length(); if (this.head > this.tail) { copy(); } if (this.content[this.cIdxNext].length < this.content[this.cIdx].length) { this.content[this.cIdxNext] = new char[this.content[this.cIdx].length]; } System.arraycopy(this.content[this.cIdx], this.head, this.content[this.cIdxNext], StringBuilder.PATTERN_SIZE, cursor); System.arraycopy(this.content[this.cIdx], this.head + cursor + 1, this.content[this.cIdxNext], StringBuilder.PATTERN_SIZE + cursor, length - cursor - 1); switchBuffer(); this.tail = (StringBuilder.PATTERN_SIZE + length) - 1; this.head = StringBuilder.PATTERN_SIZE; } }
8
@EventHandler public void PlayerBlindness(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getPlayerConfig().getDouble("Player.Blindness.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if ( plugin.getPlayerConfig().getBoolean("Player.Blindness.Enabled", true) && damager instanceof Player && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, plugin.getPlayerConfig().getInt("Player.Blindness.Time"), plugin.getPlayerConfig().getInt("Player.Blindness.Power"))); } }
6
public boolean checkRow(int row) { int i = 0, j = 0, count = 0; for(i = 1; i < 10; i++) { count = 0; for(j = 0; j < 9; j++) { if(i == Integer.parseInt(entries[row][j].getText()) ) { count++; } if( count >= 2) { System.out.println("checkRow() returned false at i: " + row + " j: "+j + " with " + entries[row][j].getText()); return false; } } } return true; }
4
@Override public String getVersion() { return("*"); }
0
private synchronized void dequeue(PacketScheduler sched) { Packet np = sched.deque(); // process ping() packet if (np instanceof InfoPacket) { ((InfoPacket) np).addExitTime( GridSim.clock() ); } if (super.reportWriter_ != null) { super.write("dequeuing, " + np); } // must distinguish between normal and junk packet int tag = GridSimTags.PKT_FORWARD; if (np.getTag() == GridSimTags.JUNK_PKT) { tag = GridSimTags.JUNK_PKT; } // sends the packet via the link String linkName = getLinkName( np.getDestID() ); super.sim_schedule(GridSim.getEntityId(linkName), GridSimTags.SCHEDULE_NOW, tag, np); //System.out.println(super.get_name() + ".deque() time now " + GridSim.clock()); // process the next packet in the scheduler if ( !sched.isEmpty() ) { double nextTime = (np.getSize() * NetIO.BITS) / sched.getBaudRate(); sendInternalEvent(nextTime, sched); } }
4
protected void touchedBy(Entity entity) { if (entity instanceof Player && pushTime == 0) { pushDir = ((Player) entity).dir; pushTime = 10; } }
2
public String readPidFromFile(String targetDirectory) throws IOException { // PID to return String pid = ""; // Buffered Reader BufferedReader br = null; File pidFile = new File(targetDirectory + PID_FILE_NAME); if (pidFile.exists()) { try { // Setup buffered reader br = new BufferedReader(new FileReader(pidFile)); // Read first line String firstLine = br.readLine(); if (!StringUtils.isEmpty(firstLine)) { pid = firstLine.trim(); } } catch (IOException e) { this.getLogger().error("error reading pid from file", e); } finally { try { if (br != null) br.close(); } catch (IOException ex) { this.getLogger().error("error reading pid from file", ex); } } } return pid; }
5
private static void Optimize(DiffData data) { int startPos, endPos; startPos = 0; while (startPos < data.Length) { while ((startPos < data.Length) && (data.modified[startPos] == false)) startPos++; endPos = startPos; while ((endPos < data.Length) && (data.modified[endPos] == true)) endPos++; if ((endPos < data.Length) && (data.data[startPos] == data.data[endPos])) { data.modified[startPos] = false; data.modified[endPos] = true; } else { startPos = endPos; } // if } // while } // Optimize
7
public void generateUpdatedEntries() { _modifiedEntries.clear(); HashSet<String> newEntries = new HashSet<String>(); for (int i = 0; i < 5; i++) { OrderEntry orderEntry = null; int action = _random.nextInt(100); if (_orderEntries.size() == 0 || action >= _deleteFactor + _updateFactor) { // Action Add if (_orderEntries.size() >= _maxEntries) { continue; } orderEntry = getNewOrder(); _orderEntries.add(orderEntry); } else if (action < _deleteFactor) { // Action Delete int index = _random.nextInt(_orderEntries.size()); orderEntry = (OrderEntry)_orderEntries.get(index); if (newEntries.contains(orderEntry.makerId)) { continue; } orderEntry.action = OMMMapEntry.Action.DELETE; _orderEntries.remove(orderEntry); } else { // Action Update int index = _random.nextInt(_orderEntries.size()); OrderEntry updateEntry = (OrderEntry)_orderEntries.get(index); if (newEntries.contains(updateEntry.makerId)) { continue; } updateOrder(updateEntry); orderEntry = (OrderEntry)updateEntry.clone(); orderEntry.action = OMMMapEntry.Action.UPDATE; } newEntries.add(orderEntry.makerId); _modifiedEntries.add(orderEntry); } }
7
protected void updatePeProvisioning() { //Log.printLine("dans updatePeProvisioning"); getPeMap().clear(); for (Pe pe : getPeList()) { pe.getPeProvisioner().deallocateMipsForAllVms(); } Iterator<Pe> peIterator = getPeList().iterator(); Pe pe = peIterator.next(); PeProvisioner peProvisioner = pe.getPeProvisioner(); double availableMips = peProvisioner.getAvailableMips(); //Log.printLine("availableMips = " + availableMips); for (Map.Entry<String, List<Double>> entry : getMipsMap().entrySet()) { String vmUid = entry.getKey(); getPeMap().put(vmUid, new LinkedList<Pe>()); for (double mips : entry.getValue()) { // Log.printLine("mips : " + mips + " // available mips : " + availableMips); while (mips >= 0.1) { if (availableMips >= mips) { peProvisioner.allocateMipsForVm(vmUid, mips); getPeMap().get(vmUid).add(pe); availableMips -= mips; break; } else { peProvisioner.allocateMipsForVm(vmUid, availableMips); getPeMap().get(vmUid).add(pe); mips -= availableMips; if (mips <= 0.1) { break; } if (!peIterator.hasNext()) { Log.printLine("There is no enough MIPS (" + mips + ") to accommodate VM " + vmUid); // System.exit(0); } pe = peIterator.next(); peProvisioner = pe.getPeProvisioner(); availableMips = peProvisioner.getAvailableMips(); } } } } }
7
public static String checkLevels(double level) { String message = ""; if (level < 0.0) { message = " below acceptable range."; } if (level > 1.0) { message = " above acceptable range."; } return message; }
2
public static void main(String[] args) { try { FitnessCalc1 FitnessFunc; String testfile = "C:\\Users\\Vincent\\Documents\\GitHub\\Exercises\\testFiles\\A"; /*Initialisation*/ FitnessFunc = new DCS(); Algorithm.setMaximization(true); Algorithm.setSolution(0); Individual.setChromSize(26); int generationCounter = 0; DateFormat dateFormat = new SimpleDateFormat("_dd_MM_hh_mm"); Date date = new Date(); filename = "DCS_Results"+dateFormat.format(date)+".txt"; filename2 = "resultToPrint"+dateFormat.format(date)+".txt"; PrintWriter writer = new PrintWriter(filename, "UTF-8"); PrintWriter writer2 = new PrintWriter(filename2, "UTF-8"); PrintStream out = new PrintStream(new FileOutputStream(filename)); PrintStream out2 = new PrintStream(new FileOutputStream(filename2)); /*Fetching values into an individual*/ RealLabelledData testingData = RealLabelledDataFactory.dataFromTextFile(testfile, -1, null); int[] indexes = {4,5}; RealLabelledData testingDataLabels = RealLabelledDataFactory.selectLabels(testingData, indexes); ObservationReal[] patients = testingDataLabels.getArrayList().toArray(new ObservationReal[0]); /*Putting my patient values into my original model ones*/ Population myPop = new Population(patients.length); for(int j=0; j<patients.length; j++) { for (int i = 0; i < patients[j].getAttributeSize(); i++) { myPop.getIndividual(j).setValues(patients[j].getAttribute(i), i); } } /*Beginning the Genetic Algorithm*/ System.out.println("Generation Number, Best Fitness, Average Fitness, Deviance"); out.println("#DCS calculation"); out.println("#Chromosome size : " + myPop.getIndividual(0).getChromSize()); out.println("#Population size : " + patients.length); out.println("#Crossover rate : " + Algorithm.getUniformRate() + " , Mutation rate : " + Algorithm.getMutationRate() + " , Tournament size : " + Algorithm.getTournamentSize()); out.println("Generation.Number, Best.Fitness, Average.Fitness, Fitness.Deviance"); out2.println("Projection, Label"); while (generationCounter != 100) { /*Projecting*/ LinProj P1 = new LinProj(26); for (int i = 0; i < myPop.getIndividual(1).getChromSize(); i++) { P1.w[i] = myPop.getIndividual(1).getValues(i); } int[] labeldata = new int[patients.length]; double[] projdata = new double[patients.length]; for(int i = 0; i<patients.length; i++){ projdata[i] = P1.project(patients[i].getAttributeValues()); labeldata[i] = patients[i].getLabel(); out2.println(projdata[i] +" "+ labeldata[i]); } /*Evaluating and Evolving*/ generationCounter++; System.out.println(generationCounter + " , " + myPop.getFittest(FitnessFunc, projdata, labeldata).getFitness(FitnessFunc, projdata, labeldata) + " , " + myPop.getAvgFitness(FitnessFunc, projdata, labeldata) + " , " + myPop.getDeviance(FitnessFunc, projdata, labeldata)); myPop = Algorithm.evolvePopulation(myPop, FitnessFunc, projdata, labeldata); out.println(generationCounter + " " + myPop.getFittest(FitnessFunc, projdata, labeldata).getFitness(FitnessFunc, projdata, labeldata) + " " + myPop.getAvgFitness(FitnessFunc, projdata, labeldata) + " " + myPop.getDeviance(FitnessFunc, projdata, labeldata)); } System.out.println("Finished in " + generationCounter + " generations !"); out.close(); out2.close(); writer.close(); writer2.close(); /*CSV Generation into a file*/ CSVGen.CSVGenerator.main(null); File file = new File(filename); /*Simple text file deletion*/ if(file.delete()){ System.out.println(file.getName() + " is deleted!"); }else{ System.out.println("Delete operation is failed."); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch(Exception e){ e.printStackTrace(); } }
9
public OrgaEinheit getOrgaEinheitvonBezeichnung(String bezeichnung){ OrgaEinheit rueckgabe = null; try { ResultSet resultSet = db.executeQueryStatement("SELECT * FROM OrgaEinheiten WHERE OrgaEinheitBez = '" + bezeichnung + "'"); if(resultSet.next()) rueckgabe = new OrgaEinheit(resultSet, db, this); resultSet.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return rueckgabe; }
2
void fill( Point a, Point b, Point c, Point a0, Point b0, Point c0 ) { int x0 = (int)Math.floor( Util.minX(a, b, c) ), x1 = (int)Math.ceil( Util.maxX(a, b, c) ); int y0 = (int)Math.floor( Util.minY(a, b, c) ), y1 = (int)Math.ceil( Util.maxY(a, b, c) ); x0 = Math.max(x0, 0); x1 = Math.min(x1, width - 1 ); y0 = Math.max(y0, 0); y1 = Math.min(y1, height - 1 ); for ( int i = x0; i <= x1; ++i ) { for ( int j = y0; j <= y1; ++j ) { double []t = Point.TriangleContainsPoint(a, b, c, new Point(i, j) ); if ( t[1] >= 0 && t[2] >= 0 ) { double srcX = (a0.x * t[0] + b0.x * t[1] + c0.x * t[2]) / (t[0] + t[1] + t[2]); double srcY = (a0.y * t[0] + b0.y * t[1] + c0.y * t[2]) / (t[0] + t[1] + t[2]); if ( 0 <= srcX && srcX <= width - 1) { if ( 0 <= srcY && srcY <= height - 1 ) { int rgb = query(srcX, srcY); this.target.setRGB(i, j, rgb); } } } } } }
8
protected OgexTrack toTrack( DataStructure ds, Map<BaseStructure, Object> index ) { OgexTrack result = new OgexTrack(); BaseStructure target = ds.getProperty("target"); Object resolved = index.get(target); if( resolved == null ) { // Need to figure out what it is and create it... // but not right now FIXME throw new UnsupportedOperationException("Forward track targets not yet supported."); } result.setTarget(resolved); OgexTime time = null; OgexValue value = null; for( BaseStructure child : ds ) { if( StructTypes.TIME.equals(child.getType()) ) { if( time != null ) { throw new RuntimeException("Only one Time structure is allowed in Track, from:" + ds.location()); } time = toTime((DataStructure)child); } else if( StructTypes.VALUE.equals(child.getType()) ) { if( value != null ) { throw new RuntimeException("Only one Value structure is allowed in Track, from:" + ds.location()); } value = toValue((DataStructure)child); } else { log.warn("Unhandled structure type:" + child.getType() + ", from:" + child.location()); } } if( time == null ) { throw new RuntimeException("No Time structure found in Track, from:" + ds.location()); } if( value == null ) { throw new RuntimeException("No Value structure found in Track, from:" + ds.location()); } result.setTime(time); result.setValue(value); return result; }
8
private static String xmlTrim(String text) { int start = -1, end = text.length(); while (start < text.length() && isWhitespace(text.charAt(++start))); while (end > -1 && isWhitespace(text.charAt(--end))); if (end != -1) { return text.substring(start, end + 1); } else { return ""; } }
5
public void handleInput() { if (Keys.isPressed(Keys.ESCAPE)) gsm.setPaused(true); if (player.getHealth() == 0) return; player.setUp(Keys.keyState[Keys.UP]); player.setDown(Keys.keyState[Keys.DOWN]); player.setLeft(Keys.keyState[Keys.LEFT] || Keys.keyState[Keys.A]); player.setRight(Keys.keyState[Keys.RIGHT] || Keys.keyState[Keys.D]); player.setJumping(Keys.keyState[Keys.BUTTON1]); player.setGliding(Keys.keyState[Keys.BUTTON2]); if (Keys.isPressed(Keys.BUTTON4)) player.setFiring(); if (Keys.isPressed(Keys.BUTTON3)) player.setScratching(); }
6
public ArrayList<Integer> readGold(ID tid) { ArrayList<Integer> gtags = null; BufferedReader br = null; String line; try { gtags = new ArrayList<Integer>(); br = new BufferedReader(new FileReader(gold)); while ((line = br.readLine()) != null) { gtags.add(0); for (String s : line.split(" ")) { Pattern p = Pattern.compile("(.*/)?(.*)"); Matcher m = p.matcher(s); if (m.matches()) { gtags.add(tid.getID(m.group(2))); } } } gtags.add(0); } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (br != null) { br.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } } return gtags; }
6
public boolean nodesWithSum(int sum, treeNode root) { int[] newArray = new int[this.nodeCount]; addToArray(this.root, newArray, 0); int indexClosetLarger = newArray.length; int lowIndex = 0; int matchIndex = -1; int matchCount = 0; // find the closet number larger than sum for (int i = 0; i < newArray.length; i++) { if (newArray[i] > sum) { indexClosetLarger = i; break; } } // the smallest node i==0 or the 2nd smallest node i==1 is already // bigger than sum if (indexClosetLarger <= 1) return false; // start from biggest which is still smaller than sum, find from 0 for // the match for (int j = indexClosetLarger - 1; j > 0 && lowIndex < j; j--) { matchIndex = this.binarySearch(sum - newArray[j], newArray, lowIndex, j - 1); if (matchIndex >= 0) {// find match System.out.println("One pair: (" + newArray[matchIndex] + "," + newArray[j] + ")"); matchCount++; lowIndex = matchIndex + 1; } } if (matchCount > 0) return true; return false; }
7
@Override public T build(Map<Class<?>, ClassBuilder<?>> how) { Constructor<?>[] constructors = underConstruction.getConstructors(); Constructor<?> constructorElegido = this.elegirConstructor(constructors); if(constructorElegido != null){ try { return (T)constructorElegido.newInstance(this.getObjects(params)); } catch (Exception e) { e.printStackTrace(); throw new NoPudimosCrearLaInstanciaException(e); } } return null; }
6
public void Draw(Graphics2D g2d, Point mousePosition) { //draws according to Framework canvas size //g2d.drawImage(backgroundImg, 0, 0, Framework.frameWidth, Framework.frameHeight, null); //draw moving bg??????? movingBg.Draw(g2d); // Draws the course objects for (int i = 0; i < courseList.size(); i++) { courseList.get(i).Draw(g2d); } if(playerCar.getY() < courseList.get(passedPointLoc[0]).getY()){ //drawpoint passed g2d.setColor(Color.white); g2d.drawString("Passed Point A!!!", 5, 175); passedPoint[0] = true; } if(playerCar.getY() < courseList.get(passedPointLoc[1]).getY()){ //drawpoint passed g2d.setColor(Color.white); g2d.drawString("Passed Point B!!!", 5, 200); passedPoint[1] = true; } if(playerCar.getY() < courseList.get(passedPointLoc[2]).getY()){ //drawpoint passed g2d.setColor(Color.white); g2d.drawString("Passed Point C!!!", 5, 225); passedPoint[2] = true; } //draw the cars playerCar.Draw(g2d); enemyCar.Draw(g2d); }
4
public static Cons translateLoomPartitions(Stella_Object partitions, boolean exhaustiveP, Symbol parentconcept) { { Cons axioms = Stella.NIL; Cons partitionList = Stella.NIL; if (!Stella_Object.consP(partitions)) { partitions = Cons.consList(Cons.cons(partitions, Stella.NIL)); } if (Stella_Object.consP(((Cons)(partitions)).value)) { partitionList = ((Cons)(partitions)); } else { { Stella_Object clause = null; Cons iter000 = ((Cons)(partitions)); for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { clause = iter000.value; partitionList = Cons.cons(Cons.consList(Cons.cons(clause, Stella.NIL)), partitionList); } } } { Cons clause = null; Cons iter001 = partitionList; for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) { clause = ((Cons)(iter001.value)); { Stella_Object name = clause.value; Cons concepts = ((Cons)(clause.rest.value)); Cons localaxioms = Stella.NIL; localaxioms = Cons.cons(Cons.list$(Cons.cons(edu.isi.powerloom.pl_kernel_kb.loom_api.LoomApi.SYM_PL_KERNEL_KB_MUTUALLY_DISJOINT_COLLECTION, Cons.cons(name, Cons.cons(Stella.NIL, Stella.NIL)))), localaxioms); if (concepts != null) { localaxioms = Cons.cons(Cons.list$(Cons.cons(Logic.SYM_STELLA_e, Cons.cons(name, Cons.cons(Cons.cons(Cons.cons(Logic.SYM_PL_KERNEL_KB_SETOF, concepts.concatenate(Stella.NIL, Stella.NIL)), Stella.NIL), Stella.NIL)))), localaxioms); } if (exhaustiveP) { localaxioms = Cons.cons(Cons.list$(Cons.cons(edu.isi.powerloom.pl_kernel_kb.loom_api.LoomApi.SYM_PL_KERNEL_KB_COVERING, Cons.cons(name, Cons.cons(Cons.cons(parentconcept, Stella.NIL), Stella.NIL)))), localaxioms); } axioms = Cons.cons(Logic.conjoinSentences(localaxioms.reverse()), axioms); } } } return (axioms); } }
6
@EventHandler public void WitherInvisibility(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getZombieConfig().getDouble("Wither.Invisibility.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (damager instanceof WitherSkull) { WitherSkull a = (WitherSkull) event.getDamager(); LivingEntity shooter = a.getShooter(); if (plugin.getWitherConfig().getBoolean("Wither.Invisibility.Enabled", true) && shooter instanceof Wither && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, plugin.getWitherConfig().getInt("Wither.Invisibility.Time"), plugin.getWitherConfig().getInt("Wither.Invisibility.Power"))); } } }
7
private void makeRGBTexture(GL2 gl, BufferedImage img, int target) { /* Setup a BufferedImage suitable for OpenGL */ WritableRaster raster = Raster.createInterleavedRaster (DataBuffer.TYPE_BYTE, img.getWidth(), img.getHeight(), 4, null); ComponentColorModel colorModel = new ComponentColorModel (ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] {8,8,8,8}, true, false, ComponentColorModel.TRANSLUCENT, DataBuffer.TYPE_BYTE); BufferedImage bufImg = new BufferedImage (colorModel, raster, false, null); /* Setup a Graphic2D context that will flip the image vertically along the way */ Graphics2D g = bufImg.createGraphics(); AffineTransform gt = new AffineTransform(); gt.translate (0, img.getHeight()); gt.scale (1, -1d); g.transform (gt); g.drawImage (img, null, null ); /* Fetch the raw data out of the image and destroy the graphics context */ byte[] imgRGBA = ((DataBufferByte)raster.getDataBuffer()).getData(); g.dispose(); /* Convert the raw data to a buffer for glTexImage2D */ ByteBuffer dest = ByteBuffer.allocateDirect(imgRGBA.length); dest.order(ByteOrder.nativeOrder()); dest.put(imgRGBA, 0, imgRGBA.length); // Rewind the buffer so we can read it starting and beginning dest.rewind(); gl.glTexImage2D(target, 0, GL2.GL_RGBA, img.getWidth(), img.getHeight(), 0, GL2.GL_RGBA, GL2.GL_UNSIGNED_BYTE, dest); if(gl.glIsTexture(glTexture) == false){ System.err.println("FAILED TO GENERATE TEXTURE"); if(isPowerOfTwo(img.getWidth()) == false || isPowerOfTwo(img.getHeight()) == false){ System.err.println("Texture width or height is not power of two"); System.err.println("Texture width: " + img.getWidth()); System.err.println("Texture height: " + img.getHeight()); return; } System.err.println("Unknown reason texture did not generate"); } }
3
private synchronized void processInputs() { int code; try { // Careful: the read*() methods are blocking! code = hmi.dataIn.readInt(); Command command = Command.values()[code]; if (command == Command.IN_SET_MODE) { int imode = hmi.dataIn.readInt(); hmi.mode = Mode.values()[imode]; } else if (command == Command.IN_SELECTED_PARKING_SLOT) { hmi.selectedParkingSlot = hmi.dataIn.readInt(); } } catch (IOException e) { System.out.println("Read exception "+e); } }
3
@Override public void storeComment(Comment comment) { ResultSet rs = null; int ID = comment.getID(); if (ID > 0) { // update editComment(comment); } else { // insert try { // this.iComment = connection.prepareStatement("INSERT INTO comment (author, text, date, adminID, postID), VALUES (?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); // assumiamo che se un commento è postato da un Admin, Comment.author corrisponderà a Admin.Username this.iComment.setString(1, comment.getAuthor()); this.iComment.setString(2, comment.getText()); this.iComment.setDate(3, new java.sql.Date(System.currentTimeMillis() / 1000L)); this.iComment.setInt(5, comment.getPost().getID()); if (comment.isPostedByAdmin()) { this.iComment.setInt(4, comment.getAdmin().getID()); } else { this.iComment.setNull(4, java.sql.Types.INTEGER); } // abbiamo finito di compilare la query if (this.iComment.executeUpdate() == 1) { rs = this.iComment.getGeneratedKeys(); if (rs.next()) { ID = rs.getInt(1); } } if (ID > 0) { comment.copyFrom(getComment(ID)); // aggiorno il post } comment.setDirty(false); // dico che è pulito } catch (SQLException ex) { Logger.getLogger(SitoDataLayerMysqlImpl.class.getName()).log(Level.SEVERE, null, ex); } finally { if (rs != null) { try { rs.close(); } catch (SQLException ex) { Logger.getLogger(SitoDataLayerMysqlImpl.class.getName()).log(Level.SEVERE, null, ex); } } } } }
8
private Comparator<? super TSource> createComparatorChain() { final List<Comparator<TSource>> comparators = new LinkedList<Comparator<TSource>>(); SortableList<TSource> s = this; do { comparators.add(0, s.comparator); } while ((s = s.parent) != null); return new Comparator<TSource>() { @Override public int compare(TSource t1, TSource t2) { int compareResult = 0, i = 0; Comparator<TSource> comparator = null; do { comparator = comparators.get(i++); compareResult = comparator.compare(t1, t2); } while (compareResult == 0 && CommonUtils.isLegalIndex(comparators, i)); return compareResult; } }; }
4
private MouseMotionListener mouseMotionListener(){ return new MouseMotionAdapter() { @Override public void mouseDragged( MouseEvent e ) { if( !moving ){ if( mousePressedPoint != null ){ initMove( mousePressedPoint.x, mousePressedPoint.y ); } } if( moving ){ for( MoveableCapability item : items ){ item.moveTo( e.getX(), e.getY() ); } } } }; }
4
@Override public void restoreCurrentToDefault() { copyHashMap(def,cur); }
0
public String expression(String expression){ this.expression = expression; return this.expression; }
0
@Override protected void setup(Context context) { this.conf = context.getConfiguration(); // get cube identifier from hadoop conf try { initCubeIdentifierFromHadoopConf(); } catch (CubeIdentifierNotSetException e) { e.printStackTrace(); // TODO exit is not a good way System.exit(-1); } // get dimensionLengths from hadoop conf try { initDimensionLengthsFromHadoopConf(); } catch (DimensionLengthsNotSetException e) { e.printStackTrace(); // TODO exit is not a good way System.exit(-1); } // get newDimensionLengths from hadoop conf try { initNewDimensionLengthsFromHadoopConf(); } catch (DimensionLengthsNotSetException e) { e.printStackTrace(); // TODO exit is not a good way System.exit(-1); } // get schema from hadoop conf try { initSchemaFromConf(); } catch (InvalidObjectStringException e) { e.printStackTrace(); // TODO exit is not a good way System.exit(-1); } catch (SchemaNotSetException e) { e.printStackTrace(); // TODO exit is not a good way System.exit(-1); } // get newSchema from hadoop conf try { initNewSchemaFromConf(); } catch (InvalidObjectStringException e) { e.printStackTrace(); // TODO exit is not a good way System.exit(-1); } catch (NewSchemaNotSetException e) { e.printStackTrace(); // TODO exit is not a good way System.exit(-1); } }
7
public boolean isVertexInArea(Point p1, Point p2) { double[] posX = { p1.getX(), p2.getX() }; double[] posY = { p1.getY(), p2.getY() }; if (posX[0] > posX[1]) { swapCoords(posX); } if (posY[0] > posY[1]) { swapCoords(posY); } if (getCenterX() >= posX[0] && getCenterX() <= posX[1] && getCenterY() >= posY[0] && getCenterY() <= posY[1]) { return true; } return false; }
6
@Override public void finishOutline () {}
0
public PlantManager(World world, Object3D ground, float range) { plants=new Plant[MAX_PLANTS]; positions=new SimpleVector[MAX_PLANTS]; for (int i=0; i<MAX_PLANTS; i++) { Plant plant=new Plant(); plants[i]=plant; boolean ok=false; do { float xpos=(float)(Math.random()-0.5d)*range*2f; float zpos=(float)(Math.random()-0.5d)*range*2f; plant.setTranslationMatrix(new Matrix()); plant.translate(xpos, 0, zpos); ok=plant.place(ground); } while (!ok); plant.addToWorld(world); plant.addCollisionListener(LISTENER); } for (int i=0; i<MAX_PLANTS; i++) { positions[i]=plants[i].getTransformedCenter(); /** * The positions won't change anymore, so we can do this: */ plants[i].enableLazyTransformations(); } }
3
public void kick(String message, Object... args) { if (left) return; PacketKick kick = new PacketKick(this); kick.message = message; kick.args = args; if(properties.containsKey("translation")) { Translation t = (Translation)properties.get("translation"); System.out.println(t.translate("client.kicked", socket.getInetAddress().getCanonicalHostName(), t.translate(message, args))); } try { kick.send(); } catch (IOException e) { } try { socket.close(); } catch (IOException e) { } left = true; }
4
@Override public void parse(CommandInvocation invocation, List<ParsedParameter> params, List<Parameter> suggestions) { String token = invocation.currentToken(); for (String name : getNames()) { if (name.equalsIgnoreCase(token)) { invocation.consume(1); // TODO perhaps remember parsed name break; } } if (invocation.isConsumed() && suggestions != null) { return; } super.parse(invocation, params, suggestions); }
4
@Override protected String makeString(String t, boolean structured) { String n = ""; //new line String tt = ""; //tabulators //create new stuff, if structured if(structured){ n = "\n"; tt = t+"\t"; } //temp storage StringBuilder arrsb = new StringBuilder(); //trick to have commas just where they're needed char c = '['; for(JsonElement element : value){ arrsb.append(c+n+tt); arrsb.append( (element==null) ? ("null") : (element.makeString(tt, structured)) ); c = ','; } return arrsb.append(n+t+"]").toString(); }
3
@Override public void run() { while (true) { Point p; try { p = toLoad.take(); }catch (InterruptedException e) { e.printStackTrace(); continue; } try { Main.getLoadedWorld().addChunk(load(p)); }catch (NullPointerException e) { try { Thread.sleep(10); } catch (InterruptedException e1) { e1.printStackTrace(); } Main.getLoadedWorld().addChunk(load(p)); } } }
4
public static void print(Object s) { System.out.print(s); }
0
@Override public String process(String content) throws ProcessorException { // TODO Auto-generated method stub pipeline = new SimpleAuthenticationPipeline(); context = new AuthenticateContext(); pipeline.setBasic(new LoginEntryValve()); pipeline.addValve(new FlushValve()); pipeline.addValve(new EncodeValve()); pipeline.addValve(new GetTokenValve()); pipeline.addValve(new AuthenticateValve()); pipeline.addValve(new ValidationValve()); pipeline.addValve(new DecoderValve()); // pipeline.addValve(new EncodeValve()); pipeline.setContext(context); try { pipeline.invoke(context.getRequest(), context.getResponse(), null); } catch (ValveException e) { e.printStackTrace(); User user = context.getRequest().getCurrentUser(); String response = ""; if (user == null || user.getUserName() == null) { response = ExceptionWrapper.toJSON(503, "Internal Error"); } else { response = ExceptionWrapper.toJSON(user, e.getCode(), e.getMessage()); } return response; } return context.getResponse().getResponse(); }
3
public void bind() { SocketAddress address; if (ip.isEmpty()) { address = new InetSocketAddress(this.port); } else { address = new InetSocketAddress(this.ip, this.port); } ChannelFuture future = this.bootstrap.bind(address); Channel channel = future.awaitUninterruptibly().channel(); if (!channel.isActive()) { throw new RuntimeException("**** FAILED TO BIND TO PORT! Perhaps a server is already running on that port?"); } LOGGER.info("Ready to accept connections on " + address); }
2
@SuppressWarnings("deprecation") public void stop(){ downloadThread.stop(); }
0
public void addVertex(UndirectedNode vertex) { if (!this.vertices.contains(vertex)) { this.vertices.add(vertex); } }
1
public void writeWsFrameLength(byte type, int length) throws IOException { writeRawByte(type); // Encode length. int b1 = length >>> 28 & 0x7F; int b2 = length >>> 14 & 0x7F; int b3 = length >>> 7 & 0x7F; int b4 = length & 0x7F; if (b1 == 0) { if (b2 == 0) { if (b3 == 0) { writeRawByte(b4); } else { writeRawByte(b3 | 0x80); writeRawByte(b4); } } else { writeRawByte(b2 | 0x80); writeRawByte(b3 | 0x80); writeRawByte(b4); } } else { writeRawByte(b1 | 0x80); writeRawByte(b2 | 0x80); writeRawByte(b3 | 0x80); writeRawByte(b4); } }
3
@Override public String execute(SessionRequestContent request) throws ServletLogicException { String page = ConfigurationManager.getProperty("path.page.countries"); String prevPage = (String) request.getSessionAttribute(JSP_PAGE); resaveParamsShowCountry(request); formCountryList(request); showSelectedCountry(request); if (page == null ? prevPage != null : !page.equals(prevPage)) { request.setSessionAttribute(JSP_PAGE, page); cleanSessionShowCountry(request); } return page; }
2
@Override public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_UP: System.out.println("Stop JUMP"); break; case KeyEvent.VK_DOWN: currentSprite = anim.getImage(); robot.setDucking(false); break; case KeyEvent.VK_LEFT: robot.setMovingLeft(false); robot.stop(); break; case KeyEvent.VK_RIGHT: robot.setMovingRight(false); robot.stop(); break; case KeyEvent.VK_CONTROL: robot.setReadyToFire(true); break; } }
5
public int getSize() { return type == Type.LONG_TYPE || type == Type.DOUBLE_TYPE ? 2 : 1; }
2
public WorldInfo loadWorldInfo() { File var1 = new File(this.saveDirectory, "level.dat"); NBTTagCompound var2; NBTTagCompound var3; if(var1.exists()) { try { var2 = CompressedStreamTools.loadGzippedCompoundFromOutputStream(new FileInputStream(var1)); var3 = var2.getCompoundTag("Data"); return new WorldInfo(var3); } catch (Exception var5) { var5.printStackTrace(); } } var1 = new File(this.saveDirectory, "level.dat_old"); if(var1.exists()) { try { var2 = CompressedStreamTools.loadGzippedCompoundFromOutputStream(new FileInputStream(var1)); var3 = var2.getCompoundTag("Data"); return new WorldInfo(var3); } catch (Exception var4) { var4.printStackTrace(); } } return null; }
4
public Player play() throws GameEndedUnexpectedlyException { Player turn = null; WinResult gameState = WinResult.None; //The game loop. Halts when the game has ended while(gameState == WinResult.None) { //Determine whose turn it is if (turn == player1) { turn = player2; } else { turn = player1; } //Ask player for the next move, and update the board //If an invalid move is sent, ask for another move from the player. int moveTries = 0; Piece newestPiece = null; while(moveTries<10 && newestPiece == null) { Move nextMove = turn.getMove(this.board); newestPiece = rules.parseMove(nextMove, board); if (newestPiece == null) { moveTries++; } setChanged(); notifyObservers(newestPiece); } //If after 10 tries, the player has not provided a legal move, stop the game. //This will make the game throw a gameEndedUnexpectedlyException. if (moveTries >= 10) { break; } //Check whether the game has ended gameState = rules.checkWin(board); } switch (gameState) { case Won: return turn; case Tie: return null; default: //Exited the game loop, but no one has won and there is no tie. throw new GameEndedUnexpectedlyException(); } }
8
public static void main(String[] args) throws IOException { for (int i = 2; i < 1000000; i++) if (!primos[i]) for (int j = i + i; j < 1000000; j += i) primos[j] = true; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while(true){ int n = Integer.parseInt(in.readLine().trim()); if(n==0)break; for(int i = 2; i < n; i++) if(!primos[i]&&!primos[n-i]){ System.out.println(n + " = " + i + " + " + (n-i)); break; } } }
8
@Override public boolean grown() { final FarmingDefinition definition = definition(); if (definition.containsAction("Empty") || definition.containsAction("Take-tomato")) { return true; } final int bits = bits(); return bits == NORMAL_STAGE[2] || bits == SUPER_STAGE[2] || bits == TOMATO_STAGE[2]; }
4
public cancelService(int route) { database.openBusDatabase(); Calendar cal = Calendar.getInstance(); route_id = route; timing_point += cal.get(Calendar.HOUR_OF_DAY) * 60; timing_point += cal.get(Calendar.MINUTE); startDate = (Calendar)cal.clone(); if(startDate.get(Calendar.DAY_OF_WEEK) > 1 && startDate.get(Calendar.DAY_OF_WEEK) < 7) day_of_week = 0; else if(startDate.get(Calendar.DAY_OF_WEEK) == 7) day_of_week = 1; else day_of_week = 2; }
3
public void mouseWheelMoved(MouseWheelEvent e) { MapView mapView = (MapView) e.getSource(); ControllerAdapter mController = (ControllerAdapter) mapView.getModel() .getModeController(); if (mController.isBlocked()) { return; // block the scroll during edit (PN) } Set registeredMouseWheelEventHandler = mController .getRegisteredMouseWheelEventHandler(); for (Iterator i = registeredMouseWheelEventHandler.iterator(); i .hasNext(); ) { MouseWheelEventHandler handler = (MouseWheelEventHandler) i.next(); boolean result = handler.handleMouseWheelEvent(e); if (result) { // event was consumed: return; } } if ((e.getModifiers() & ZOOM_MASK) != 0) { // fc, 18.11.2003: when control pressed, then the zoom is changed. float newZoomFactor = 1f + Math.abs((float) e.getWheelRotation()) / 10f; if (e.getWheelRotation() < 0) newZoomFactor = 1 / newZoomFactor; final float oldZoom = ((MapView) e.getComponent()).getZoom(); float newZoom = oldZoom / newZoomFactor; // round the value due to possible rounding problems. newZoom = (float) Math.rint(newZoom * 1000f) / 1000f; newZoom = Math.max(1f / 32f, newZoom); newZoom = Math.min(32f, newZoom); if (newZoom != oldZoom) { mController.getController().setZoom(newZoom); } // end zoomchange } else if ((e.getModifiers() & HORIZONTAL_SCROLL_MASK) != 0) { ((MapView) e.getComponent()).scrollBy( SCROLL_SKIPS * e.getWheelRotation(), 0); } else { ((MapView) e.getComponent()).scrollBy(0, SCROLL_SKIPS * e.getWheelRotation()); } }
7
private static boolean checkElementDiscovered(String element) { for (int x = 0; x <= elementsDiscovered.length -1; x++) { //goes through the elementsDiscovered int elementInt = elementNumber(element); //and checks if the int of the element passed if (elementInt == elementsDiscovered[x]){ //through matches any int in the elementsDiscovered return true; } } return false; }
2
@Test public void test_solvable_matrix_size_3_solve() throws ImpossibleSolutionException,UnsquaredMatrixException, ElementOutOfRangeException{ int height=3; int width=3; float[][] matrix; float[] resultVector; float[][] knownMatrix = new float[height][width]; float[] knownResults = new float[height]; knownMatrix[0][0] = -.2f; knownMatrix[0][1] = .6f; knownMatrix[0][2] = -.2f; knownMatrix[1][0] = .6f; knownMatrix[1][1] = .2f; knownMatrix[1][2] = -.4f; knownMatrix[2][0] = 0f; knownMatrix[2][1] = -1f; knownMatrix[2][2] = 1f; knownResults[0] = .6f; knownResults[1] = 1.2f; knownResults[2] = -2.0f; try{ test_matrix = new LinearEquationSystem(height,width); }catch(UnsquaredMatrixException e){ throw e; } try{ test_matrix.setValueAt(0,0, 1.0f); test_matrix.setValueAt(0,1, 2.0f); test_matrix.setValueAt(0,2, 1.0f); test_matrix.setValueAt(0,3, 1.0f); test_matrix.setValueAt(1,0, 3.0f); test_matrix.setValueAt(1,1, 1.0f); test_matrix.setValueAt(1,2, 1.0f); test_matrix.setValueAt(1,3, 1.0f); test_matrix.setValueAt(2,0, 3.0f); test_matrix.setValueAt(2,1, 1.0f); test_matrix.setValueAt(2,2, 2.0f); test_matrix.setValueAt(2,3, -1.0f); }catch(ElementOutOfRangeException e){ throw e; } try{ resultVector = test_matrix.solve(); }catch(ImpossibleSolutionException e){ throw e; } matrix = test_matrix.returnMatrix(); Assert.assertArrayEquals(knownResults,resultVector,.001f); Assert.assertArrayEquals(knownMatrix[0],matrix[0],.001f); Assert.assertArrayEquals(knownMatrix[1],matrix[1],.001f); Assert.assertArrayEquals(knownMatrix[2],matrix[2],.001f); }
3
public String getLyricsSnippet(String artistName,String songName){ if (artistName.equals(null) || artistName.equals("") || songName.equals(null) || songName.equals("")) return null; String url = buildUrl(artistName,songName); try { Document document = reader.read(url); // XMLUtil.writeToFile(document, artistName + " - " + songName + ".xml"); Element root = document.getRootElement(); //LyricsResult element String pageId = root.element("page_id").getText(); if(pageId.equals("")){ //there is NOT lyrics page System.out.println("No lyrics page."); return null; } else return root.element("lyrics").getText(); } catch (Exception e) { return null; //e.printStackTrace(); } }
6
public GedcomObjectFactory findFactoryForTag(String tag) { if (tag.equalsIgnoreCase("DATE")) return dateFactory; else if (tag.equalsIgnoreCase("PLAC")) return placeFactory; else return null; }
2
@EventHandler public void onPlayerDeathEvent(PlayerDeathEvent event) { Player player = (Player) event.getEntity(); if (!player.hasPermission("trophyheads.drop")) { return; } if (randomGenerator.nextInt(100) >= DROP_CHANCES.get(EntityType.PLAYER.toString())) { return; } boolean dropOkay = false; DamageCause dc; if (player.getLastDamageCause() != null) { dc = player.getLastDamageCause().getCause(); logDebug("DamageCause: " + dc.toString()); } else { logDebug("DamageCause: NULL"); return; } if (DEATH_TYPES.contains(dc.toString())) { dropOkay = true; } if (DEATH_TYPES.contains("ALL")) { dropOkay = true; } if (player.getKiller() instanceof Player) { logDebug("Player " + player.getName() + " killed by another player. Checking if PVP is valid death type."); if (DEATH_TYPES.contains("PVP")) { dropOkay = isValidItem(EntityType.PLAYER, player.getKiller().getItemInHand().getType()); logDebug("PVP is a valid death type. Killer's item in hand is valid? " + dropOkay); } else { logDebug("PVP is not a valid death type."); } } if (dropOkay) { logDebug("Match: true"); Location loc = player.getLocation().clone(); World world = loc.getWorld(); String pName = player.getName(); ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3); ItemMeta itemMeta = item.getItemMeta(); ArrayList<String> itemDesc = new ArrayList<>(); itemMeta.setDisplayName("Head of " + pName); itemDesc.add(event.getDeathMessage()); itemMeta.setLore(itemDesc); if (playerSkin) { ((SkullMeta) itemMeta).setOwner(pName); } item.setItemMeta(itemMeta); world.dropItemNaturally(loc, item); } else { logDebug("Match: false"); } }
9
protected void decodeAttribute(mxCodec dec, Node attr, Object obj) { String name = attr.getNodeName(); if (!name.equalsIgnoreCase("as") && !name.equalsIgnoreCase("id")) { Object value = attr.getNodeValue(); String fieldname = getFieldName(name); if (isReference(obj, fieldname, value, false)) { Object tmp = dec.getObject(String.valueOf(value)); if (tmp == null) { System.err.println("mxObjectCodec.decode: No object for " + getName() + "." + fieldname + "=" + value); return; // exit } value = tmp; } if (!isExcluded(obj, fieldname, value, false)) { setFieldValue(obj, fieldname, value); } } }
5
public void dequeueSound( String filename ) { if( !toStream ) { errorMessage( "Method 'dequeueSound' may only be used for " + "streaming and MIDI sources." ); return; } if( filename == null || filename.equals( "" ) ) { errorMessage( "Filename not specified in method 'dequeueSound'" ); return; } synchronized( soundSequenceLock ) { if( soundSequenceQueue != null ) { ListIterator<FilenameURL> i = soundSequenceQueue.listIterator(); while( i.hasNext() ) { if( i.next().getFilename().equals( filename ) ) { i.remove(); break; } } } } }
6
private void closeDB(){ try { if(rs!=null){ rs.close(); } if(ps!=null){ ps.close(); } if(conn!=null){ conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
4
private static ResCache makeglobal() { ResCache ret; if ((ret = JnlpCache.create()) != null) return (ret); if ((ret = FileCache.foruser()) != null) return (ret); return (null); }
2
public static void loadAllAchievements() { String statement = new String("SELECT * FROM " + DBTable + " WHERE type = ?"); PreparedStatement stmt; try { stmt = DBConnection.con.prepareStatement(statement); stmt.setInt(1, HIGHSCORE_TYPE); ResultSet rs = stmt.executeQuery(); while (rs.next()) { HighScoreAchievement achievement = new HighScoreAchievement(rs.getInt("aid"), rs.getString("name"), rs.getString("url"), rs.getString("description"), rs.getInt("threshold")); allAchievements.add(achievement); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } }
2
public ArrayList<Fish> reproduceWithFish(Fish f) { Random generator = new Random(); ArrayList<Fish> babies = new ArrayList<Fish>(); double num = generator.nextDouble(); if (num <= .01) { int num1 = generator.nextInt(2); for (int x = 0; x <= num1; x++) { babies.add(new Shark(this.x, this.y, this.bounds)); } } return babies; }
2
@Test public void testGetSquareContent() { board.removeAllPawns(); Pawn pawn1 = new Pawn('a', 2, 2, board); board.addPawn(pawn1); if (board.getSquareContent(2, 2) != null) { assertEquals('a', board.getSquareContent(2, 2).getLetter()); } else { fail(); } }
1
public void input() { System.out.println("Available choices are score, flag, reveal, board, save, help, and exit"); String inputString = input.next().trim().toLowerCase(); if (inputString.equals("score")) { score(); } else if (inputString.equals("flag")) { System.out.println("Where to flag?\nplease input as 'x,y'"); accessCell(1); score(); } else if (inputString.equals("reveal")) { System.out.println("Where to reveal?\nplease input as 'x,y'"); accessCell(0); score(); } else if (inputString.equals("board")) { System.out.println(boardView.boardToString()); } else if (inputString.equals("save")) { menuModel.getBoardModel().saveBoard(); System.out.println("game saved"); } else if (inputString.equals("help")) { System.out.println("score: Shows the current score and flags"); System.out.println("flag: Flags a cell on the board"); System.out.println("reveal: Reveals a cell on the baord"); System.out.println("save: Saves the game"); System.out.println("exit: Exits back to the main menu"); } else if (inputString.equals("exit")) { drawMainMenu(); return; } else { System.out.println("Sorry, I didn't recognise that command"); } input(); }
7
private static int findMatch(String s, String p) { if (s == null || p == null) return -1; int m = s.length(); int n = p.length(); if (m < n) return -1; for (int i = 0; i <= (m - n); i++) { // (M - N) steps int j = 0; while(j < n && s.charAt(i + j) == p.charAt(j)) { // at most N steps j++; } if (j == n) return i; } return -1; }
7
public BounceFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); setTitle("Bounce"); comp = new BallComponent(); add(comp, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(); addButton(buttonPanel, "Start", new ActionListener() { public void actionPerformed(ActionEvent event) { addBall(); } }); addButton(buttonPanel, "Close", new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); add(buttonPanel, BorderLayout.SOUTH); }
0
public static String getBaseURI(NodeInfo node) { String xmlBase = node.getAttributeValue(StandardNames.XML_BASE); if (xmlBase != null) { URI baseURI; try { baseURI = new URI(xmlBase); if (!baseURI.isAbsolute()) { NodeInfo parent = node.getParent(); if (parent == null) { // We have a parentless element with a relative xml:base attribute. // See for example test XQTS fn-base-uri-10 and base-uri-27 URI base = new URI(node.getSystemId()); URI resolved = (xmlBase.length()==0 ? base : base.resolve(baseURI)); return resolved.toString(); } String startSystemId = node.getSystemId(); String parentSystemId = parent.getSystemId(); URI base = new URI(startSystemId.equals(parentSystemId) ? parent.getBaseURI() : startSystemId); baseURI = (xmlBase.length()==0 ? base : base.resolve(baseURI)); } } catch (URISyntaxException e) { // xml:base is an invalid URI. Just return it as is: the operation that needs the base URI // will probably fail as a result. \ return xmlBase; } return baseURI.toString(); } String startSystemId = node.getSystemId(); NodeInfo parent = node.getParent(); if (parent == null) { return startSystemId; } String parentSystemId = parent.getSystemId(); if (startSystemId.equals(parentSystemId)) { return parent.getBaseURI(); } else { return startSystemId; } }
9
public void display(){ int index = 0; while(index<SIZE) { if (elements[index] != null) { LinkedNode node = (LinkedNode) elements[index]; node.display(); } index++; } }
2
@Test public void testPingSocket() { LOGGER.log(Level.INFO, "----- STARTING TEST testPingSocket -----"); String client_hash = ""; String client_hash2 = ""; server1.setUseDisconnectedSockets(true); Server server3 = null; try { server3 = new Server(game, port, false); } catch (IOException | ServerSocketCloseException | TimeoutException e) { exception = true; } try { server1.startThread(); } catch (IOException | ServerSocketCloseException | FeatureNotUsedException e) { exception = true; } waitListenThreadStart(server1); try { client_hash = server2.addSocket("127.0.0.1"); } catch (IOException | TimeoutException e) { exception = true; } waitSocketThreadAddNotEmpty(server2); waitSocketThreadState(server2, client_hash, SocketThread.CONFIRMED); try { client_hash2 = server3.addSocket("127.0.0.1"); } catch (IOException | TimeoutException e) { exception = true; } waitSocketThreadAddNotEmpty(server3); waitSocketThreadState(server3, client_hash2, SocketThread.CONFIRMED); boolean loop = true; Timing new_timer = new Timing(); while (loop) { if (server1.getSocketList().size() == 2 || new_timer.getTime() > timeout) { loop = false; } } try { server1.pingSockets(); } catch (IOException e) { exception = true; } time.waitTime(wait); boolean not_disconnected = server1.getDisconnectedSockets().isEmpty(); Assert.assertTrue(not_disconnected, "Could not ping sockets"); try { server3.close(); } catch (IOException | ServerSocketCloseException | TimeoutException e) { exception = true; } waitServerState(server3, Server.CLOSED); Assert.assertFalse(exception, "Exception found"); LOGGER.log(Level.INFO, "----- TEST testPingSocket COMPLETED -----"); }
9
public String toString() { return "STATE: " + myState.toString() + " COLOR: " + myColor; }
0
public void DBDeleteAreaAndRooms(Area A) { if(A==null) return; if(!A.isSavable()) return; if(Log.debugChannelOn()&&(CMSecurity.isDebugging(CMSecurity.DbgFlag.CMAREA)||CMSecurity.isDebugging(CMSecurity.DbgFlag.DBROOMS))) Log.debugOut("RoomLoader","Destroying area "+A.name()); A.setAreaState(Area.State.STOPPED); final List<String> statements = new Vector<String>(4 + A.numberOfProperIDedRooms()); statements.addAll(getAreaDeleteStrings(A.Name())); statements.add("DELETE FROM CMROOM WHERE CMAREA='"+A.Name()+"'"); for(Enumeration<String> ids=A.getProperRoomnumbers().getRoomIDs();ids.hasMoreElements();) statements.addAll(getRoomDeleteStrings(ids.nextElement())); statements.add("DELETE FROM CMROOM WHERE CMAREA='"+A.Name()+"'"); final String[] statementsBlock = statements.toArray(new String[statements.size()]); statements.clear(); for(int i=0;i<3;i++) { // not even mysql delete everything as commanded. DB.update(statementsBlock); try { Thread.sleep(A.numberOfProperIDedRooms()); } catch(Exception e) { } } }
8
void drawEllipse(int color, int sz, int xc, int yc, int a, int b) { /* e(x,y) = b^2*x^2 + a^2*y^2 - a^2*b^2 */ int x = 0, y = b; long a2 = (long)a*a; long b2 = (long)b*b; long crit1 = -(a2/4 + a%2 + b2); long crit2 = -(b2/4 + b%2 + a2); long crit3 = -(b2/4 + b%2); long t = -a2*y; /* e(x+1/2,y-1/2) - (a^2+b^2)/4 */ long dxt = 2*b2*x; long dyt = -2*a2*y; long d2xt = 2*b2; long d2yt = 2*a2; while (y>=0 && x<=a) { paintPixelAreaXY(color, sz, xc+x, yc+y); if (x!=0 || y!=0) paintPixelAreaXY(color, sz, xc-x, yc-y); if (x!=0 && y!=0) { paintPixelAreaXY(color, sz, xc+x, yc-y); paintPixelAreaXY(color, sz, xc-x, yc+y); } if (t + b2*x <= crit1 || /* e(x+1,y-1/2) <= 0 */ t + a2*y <= crit3) { /* e(x+1/2,y) <= 0 */ x++; dxt += d2xt; t += dxt; } else if (t - a2*y > crit2) { /* e(x+1/2,y-1) > 0 */ y--; dyt += d2yt; t += dyt; } else { x++; dxt += d2xt; t += dxt; y--; dyt += d2yt; t += dyt; } } }
9
public boolean EliminarTrata(Trata p){ if (p!=null) { cx.Eliminar(p); return true; }else { return false; } }
1
@Override public String newProgrammesThisWeek() throws WhatsNewServiceException { List<BroadCastProgramme> programmeList = iProgrammesThisWeekService.programmesThisWeek(); List<Programme> newProgrammes = new ArrayList<Programme>(); if (programmeList != null) { for (BroadCastProgramme broadCastProgramme : programmeList) { // only add Programmes which are new(i.e no firstBroadcastDateTime) if (broadCastProgramme.getFirstBroadCaseDateTime() == null) { newProgrammes.add(broadCastProgramme.getProgramme()); } } } try { return JSONUtils.toJSON(newProgrammes); } catch (JSONParsingException e) { throw new WhatsNewServiceException("Exception parsing JSON", e); } }
4
public void checkType(Symtab st) { exp1.setScope(scope); exp1.checkType(st); exp2.setScope(scope); exp2.checkType(st); exp1Type = exp1.getType(st); exp2Type = exp2.getType(st); if (!exp1Type.equals("int") && !exp1Type.equals("decimal") && !exp1Type.equals("String") && !exp1Type.equals("message")) Main.error("type error in plus expression (" + exp1.getValue() + ")"); if (!exp2Type.equals("int") && !exp2Type.equals("decimal") && !exp2Type.equals("String") && !exp2Type.equals("message")) Main.error("type error in plus expression (" + exp2.getValue() + ")"); }
8
public ArrayList<String> getDimensionsFromPoints(ArrayList<ClusterPoint> p) { ArrayList<String> pointDimensionValues = new ArrayList<String>(); for(int i = 0; i < p.size(); i++) { for(int j = 0; j < dimensionCount; j++) { try { pointDimensionValues.add(Double.toString(p.get(i).getValueAtDimension(j))); } catch (Exception e) { pointDimensionValues.add("0.0"); } } } return pointDimensionValues; }
3
public void cullConnections() throws SQLException { int availableCount = 0; for (IMySQLConnection conn : conns) { if(conn.isAvailable()) { ++availableCount; } } double check = ((double)availableCount) / ((double)conns.size()); if((conns.size() > 10) && (availableCount > 5) && (check > 0.3)) { int cullCount = availableCount / 2; while(cullCount > 0) { for (IMySQLConnection conn : conns) { if(conn.isAvailable()) { conn.clean(); conn.close(); conns.remove(conn); break; } } --cullCount; } } }
8
private void createDropWidget(Composite parent) { parent.setLayout(new FormLayout()); Combo combo = new Combo(parent, SWT.READ_ONLY); combo.setItems(new String[] {"Toggle Button", "Radio Button", "Checkbox", "Canvas", "Label", "List", "Table", "Tree", "Text", "StyledText", "Combo"}); combo.select(LABEL); dropControlType = combo.getSelectionIndex(); dropControl = createWidget(dropControlType, parent, "Drop Target"); combo.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { Object data = dropControl.getLayoutData(); Composite parent = dropControl.getParent(); dropControl.dispose(); Combo c = (Combo)e.widget; dropControlType = c.getSelectionIndex(); dropControl = createWidget(dropControlType, parent, "Drop Target"); dropControl.setLayoutData(data); if (dropEnabled) createDropTarget(); parent.layout(); } }); Button b = new Button(parent, SWT.CHECK); b.setText("DropTarget"); b.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { Button b = (Button)e.widget; dropEnabled = b.getSelection(); if (dropEnabled) { createDropTarget(); } else { if (dropTarget != null){ dropTarget.dispose(); } dropTarget = null; } } }); // initialize state b.setSelection(true); dropEnabled = true; FormData data = new FormData(); data.top = new FormAttachment(0, 10); data.bottom = new FormAttachment(combo, -10); data.left = new FormAttachment(0, 10); data.right = new FormAttachment(100, -10); dropControl.setLayoutData(data); data = new FormData(); data.bottom = new FormAttachment(100, -10); data.left = new FormAttachment(0, 10); combo.setLayoutData(data); data = new FormData(); data.bottom = new FormAttachment(100, -10); data.left = new FormAttachment(combo, 10); b.setLayoutData(data); }
3
public SampleBuilder<P> blanks2blanks(Map<BlankBuilder<?>, BlankBuilder<?>> blanks2blanks) { verifyMutable(); if (this.blanks2blanks == null) { this.blanks2blanks = new HashMap<BlankBuilder<?>, BlankBuilder<?>>(); } if (blanks2blanks != null) { for (Map.Entry<BlankBuilder<?>, BlankBuilder<?>> e : blanks2blanks.entrySet()) { CollectionUtils.putItem(this.blanks2blanks, e.getKey(), e.getValue()); } } return this; }
9
private boolean jj_3_52() { if (jj_3R_70()) return true; return false; }
1
@Transient public List<LabelValue> getRoleList() { List<LabelValue> userRoles = new ArrayList<LabelValue>(); if (this.roles != null) { for (Role role : roles) { // convert the user's roles to LabelValue Objects userRoles.add(new LabelValue(role.getName(), role.getName())); } } return userRoles; }
2
public static double LinkedListFromArrayBench(int number) { LinkedListFromArray ll = new LinkedListFromArray(); long addLastTime = System.currentTimeMillis(); for (int i = 0; i < number; i++) { ll.addLast("" + Math.random()); } addLastTime = System.currentTimeMillis() - addLastTime; ll = new LinkedListFromArray(); long addFirstTime = System.currentTimeMillis(); for (int i = 0; i < number; i++) { ll.addFirst("" + Math.random()); } addFirstTime = System.currentTimeMillis() - addFirstTime; ll = new LinkedListFromArray(); long insertTime = System.currentTimeMillis(); for (int i = 0; i < number; i++) { ll.insertAt(ll.getSize() / 2, "" + Math.random()); } insertTime = System.currentTimeMillis() - insertTime; long removeTime = System.currentTimeMillis(); for (int i = 0; i < number; i++) { ll.removeAt(ll.getSize() / 2); } removeTime = System.currentTimeMillis() - removeTime; System.out.println("LLFA: " + LLBenchInfoString(addLastTime, addFirstTime, insertTime, removeTime)); return addLastTime + addFirstTime + insertTime + removeTime; }
4