text
stringlengths
14
410k
label
int32
0
9
@Override public boolean check() { // use super.check() to check the executor, then to check the distributor. if ( super.check() ) { try { this.distributor = Class.forName(this.dis); } catch (ClassNotFoundException e) { System.out.println("InnerNode " + this.name + " : " + " Distributor " + this.dis + " cannot be found."); return false; } try { this.disMethod = this.distributor.getMethod("distribute", String.class); } catch (SecurityException e) { System.out.println("InnerNode " + this.name + " : " + " Distributor " + this.dis + "'s ditribute method cannot be reached due to security problems."); return false; } catch (NoSuchMethodException e) { System.out.println("InnerNode " + this.name + " : " + " Distributor " + this.dis + "'s ditribute method cannot be found."); return false; } if ( checkNext() ) { return true; } else { return false; } } return false; }
5
public static void main(String[] args) throws IOException, ClassNotFoundException { FileOutputStream fos = new FileOutputStream("/tmp/fooobject.data"); ObjectOutputStream os = new ObjectOutputStream(fos); FooObject foo = new FooObject("foo1", 10, 12, new FooObject("test", 1, 2, null)); os.writeObject(foo); os.close(); ObjectInputStream is = new ObjectInputStream(new FileInputStream("/tmp/fooobject.data")); FooObject read = (FooObject) is.readObject(); System.out.println(read.getName()); System.out.println(read.getFriend().getName()); is.close(); }
0
public static void editRate(Rate r){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ conn.setAutoCommit(false); PreparedStatement stmnt = conn.prepareStatement("UPDATE Rates set description = ?, rate = ? WHERE rate_id = ?"); stmnt.setString(1, r.getDescription()); stmnt.setFloat(2, r.getRate()); stmnt.setInt(3, r.getRateId()); stmnt.execute(); conn.commit(); conn.setAutoCommit(true); } catch(SQLException e){ System.out.println("update fail!! - " + e); } }
4
private static void testCpus(int cpuCount, char[] ram) { DCPU[] cpus = new DCPU[cpuCount]; for (int i = 0; i < cpuCount; i++) { cpus[i] = new DCPU(); for (int j = 0; j < 65536; j++) { cpus[i].ram[j] = ram[j]; } } long ops = 0L; int hz = khz * 1000; int cyclesPerFrame = hz / 60; long nsPerFrame = 16666666L; long nextTime = System.nanoTime(); double tick = 0; double total = 0; long startTime = System.currentTimeMillis(); while (!stop) { long a = System.nanoTime(); while (System.nanoTime() < nextTime) { try { Thread.sleep(1L); } catch (InterruptedException e) { e.printStackTrace(); } } long b = System.nanoTime(); for (int j = 0; j < cpuCount; j++) { while (cpus[j].cycles < cyclesPerFrame) { cpus[j].tick(); } cpus[j].tickHardware(); cpus[j].cycles -= cyclesPerFrame; } long c = System.nanoTime(); ops += cyclesPerFrame; nextTime += nsPerFrame; tick += (c - b) / 1000000000.0; total += (c - a) / 1000000000.0; } long passedTime = System.currentTimeMillis() - startTime; System.out.println(cpuCount + " DCPU at " + ops / passedTime + " khz, " + tick * 100.0 / total + "% cpu use"); }
7
public static void splitPivotLast(int low, int high) { int i = low; for (int j = low; j < high; j++) { countLast++; if (result[j] < result[high]) { exchange(j, i); i++; } } exchange(high, i); if (low < i - 1) splitPivotLast(low, i - 1); if (i + 1 < high) splitPivotLast(i + 1, high); }
4
public void checkConsistent() { super.checkConsistent(); if (subBlocks[0].jump != null || subBlocks[0] instanceof SequentialBlock || jump != null) throw new jode.AssertError("Inconsistency"); }
3
public void setRecursiveNotDirty() { super.setRecursiveNotDirty(); this.isTargetHrefDirty = false; if(this.create!=null && this.create.isDirty()) { this.create.setRecursiveNotDirty(); } if(this.delete!=null && this.delete.isDirty()) { this.delete.setRecursiveNotDirty(); } for (Iterator iter = this.change.iterator(); iter.hasNext();) { Change cur = (Change)iter.next(); cur.setRecursiveNotDirty(); } if(this.replace!=null && this.replace.isDirty()) { this.replace.setRecursiveNotDirty(); } }
7
@Override public boolean equals(Object o) { if (o == null) { return false; } if (!(o instanceof Vector3)) { return false; } Vector3 other = (Vector3)o; return (this.x == other.x && this.y == other.y && this.z == other.z); }
4
@Override public void run() { FileProxy proxy = AppWindow.findFileProxy(mFile); if (proxy != null) { PrintCommand.print(proxy.getPrintProxy()); } else if (System.currentTimeMillis() - mStart < TimeUnit.MILLISECONDS.convert(2, TimeUnit.MINUTES)) { EventQueue.invokeLater(this); } }
2
private Response requestHelper(String requestUrl, String requestBody) { Response response = backdoorRequest(requestUrl); if(response != null && response.getValue() != null) { try { response.value = JsonParser.parse((String)response.getValue()); return response; } catch(JsonParseException e) { e.printStackTrace(); response.value = null; response.code = -1; return null; } } //Check if it's in the cache if(cacheEnabled) { response = cache.get(requestUrl); //Ignore if not in cache or too old if(response != null && System.currentTimeMillis()-response.getTimeReceived() < CACHE_AGE_LIMIT) return response; } //Otherwise send the request response = sendLimitedRequest(requestUrl, requestBody); if(response.getValue() != null) { //Parse the request try { response.value = JsonParser.parse((String)response.getValue()); cache.add(requestUrl, response); } catch(JsonParseException e) { //This shouldn't happen if we assume they're always sending correctly-formatted JSON e.printStackTrace(); response.value = null; response.code = -1; } } return response; }
8
@Override public String toString(){ return "\nRECARGO "+super.toString(); }
0
public List<VariableAppearance> getAppearances(ParsingContext context) { List<VariableAppearance> result = new ArrayList<VariableAppearance>(); for (PatternGroupStructure pattern : patterns) { Matcher matcher = pattern.getPattern().matcher(context.getContent()); while (matcher.find()) { String variableName = matcher.group(pattern.getNameGroup()); String appearancePattern = matcher.group(pattern.getAppearanceGroup()); result.add(new VariableAppearance(appearancePattern, variableName, globalContext, context, "")); if (twoScansAnalyzer && !detectedVariableNames.contains(variableName)) { detectedVariableNames.add(variableName); } } } return result; }
4
public void thaw() { Configuration[] configs = configurations.getSelected(); if (configs.length == 0) { JOptionPane.showMessageDialog(configurations, NO_CONFIGURATION_ERROR, NO_CONFIGURATION_ERROR_TITLE, JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < configs.length; i++) { configurations.setNormal(configs[i]); } configurations.deselectAll(); configurations.repaint(); }
2
public void drawTile(int xi,int yi,int tileid) { if (background == null) return; // determine position within bg int x = el.moduloFloor(xi+1,el.viewnrtilesx+3) * el.scaledtilex; int y = el.moduloFloor(yi+1,el.viewnrtilesy+3) * el.scaledtiley; // draw if (bgg==null) bgg = background.getGraphics(); Integer tileid_obj = new Integer(tileid); JREImage img = (JREImage)el.getTileImage(tileid_obj); // define background behind tile in case the tile is null or // transparent. if (img==null||el.images_transp.containsKey(tileid_obj)) { // important EngineLogic.BGImage bg_image = (EngineLogic.BGImage)el.bg_images.get(0); if (bg_image==null) { setColor(bgg,el.bg_color); bgg.fillRect(x,y,el.scaledtilex,el.scaledtiley); } else { int xtile = el.moduloFloor(xi,bg_image.tiles.x); int ytile = el.moduloFloor(yi,bg_image.tiles.y); bgg.drawImage(((JREImage)el.getImage(bg_image.imgname)).img, x, y, x+el.scaledtilex, y+el.scaledtiley, xtile*el.scaledtilex, ytile*el.scaledtiley, (xtile+1)*el.scaledtilex, (ytile+1)*el.scaledtiley, (Color)el.bg_color.impl, null); } } if (img!=null) bgg.drawImage(img.img,x,y,this); //System.out.println("Drawn tile"+tileid); }
6
private boolean sudoku(char[][] board, int pos) { int n = board.length; if(pos == n*n) return true; int x = pos/n; int y = pos%n; if(board[x][y] == '.'){ for(char c= '1'; c <= '9'; c++){ board[x][y] = c; if(isValidSudoku(board,x,y) && sudoku(board,pos+1)) return true; board[x][y] ='.'; } return false; }else{ return sudoku(board, pos+1); } }
5
short[] findY2(short t1Index, short t2Index, short t3Index, short t4Index){ short stopBefore = mod(t1Index - 1); short pathT4Index = path[t4Index]; short start = mod(t3Index + 2); int numLoops = Math.min(mod(stopBefore - start), LIMIT); if(numLoops == 0){ return null; } short t5Index = mod(start + random.nextInt(numLoops)); for(int i = 0; i < numLoops; i++){ // visualizer.highlightLoose(5, path[y2.fromIndex], path[y2.toIndex]); // visualizer.sleep(); y2Dist = dist(pathT4Index,path[t5Index]); if(simAnneal(x1Dist + x2Dist, y1Dist + y2Dist)){ short[] newPath = findX3Y3(t1Index, t2Index, t3Index, t4Index, t5Index); // visualizer.dehighlight(2); // visualizer.dehighlight(6); // visualizer.sleep(); if(newPath != null){ // visualizer.setPath(newPath); return newPath; //Next step success } } t5Index = mod(t5Index + 1); if(t5Index == stopBefore){ t5Index = start; } } return null; //This step failed }
5
@Override public void startSetup(Attributes atts) { super.startSetup(atts); addActionListener(this); }
0
public static void zmq_ctx_set (Ctx ctx_, int option_, int optval_) { if (ctx_ == null || !ctx_.check_tag ()) { throw new IllegalStateException(); } ctx_.set (option_, optval_); }
2
private void initier_table() { Vector<String> contraintes = new Vector(); for(int i=1;i<fields.size();i++) contraintes.add(fields.get(i).getText().replaceAll(" ", "")); jPanel2.removeAll(); tables = new Vector(); btn_tables = new Vector(); if(min_radio.isSelected()) { Simplexe.setZType("min"); Simplexe.setZTypeCourant("min"); } else { Simplexe.setZType("max"); Simplexe.setZTypeCourant("max"); } data = Simplexe.initialiser(fields.get(0).getText().replaceAll(" ", ""),contraintes); iteration=0; tcon.gridx=0; tcon.gridy=0; int count=0; for(int i=1;i<data.firstElement().size()-1;i++) { if(!data.firstElement().get(i).matches("^e[0-9]{0,}") && !data.firstElement().get(i).matches("^a[0-9]{0,}")) count++; } System.out.println("Nombre de variables : "+count); if(count==2) { init_contraintes.clear(); valeurs.clear(); jButton3.setVisible(true); Vector<Double> tmp; for(int i=1;i<fields.size();i++) init_contraintes.add(fields.get(i).getText().replaceAll(" ", "")); for(int i=1;i<data.size()-1;i++) { tmp = new Vector(); for(int j=1;j<count+1;j++) { System.out.print(data.get(i).get(j)+" "); tmp.add(Double.parseDouble(data.get(i).get(j))); } tmp.add(Double.parseDouble(data.get(i).lastElement())); valeurs.add(tmp); System.out.println(data.get(i).lastElement()); } } else jButton3.setVisible(false); jButton4.setVisible(true); this.bland=false; valeursZ.clear(); }
9
public StochasticKMeansPredictor(List<Instance> instances) { num_clusters = 3; if (CommandLineUtilities.hasArg("num_clusters")) { num_clusters = CommandLineUtilities.getOptionValueAsInt("num_clusters"); } // init clusters for (int i = 0 ; i < num_clusters ; i++) { clusters.add(new Cluster(instances.get(i).getFeatureVector())); } clustering_training_iterations = 10; if (CommandLineUtilities.hasArg("clustering_training_iterations")) { clustering_training_iterations = CommandLineUtilities.getOptionValueAsInt("clustering_training_iterations"); } }
3
public boolean isSelectedNumberCandidate(int x, int y) { return game[y][x] == 0 && isPossibleX(game, y, selectedNumber) && isPossibleY(game, x, selectedNumber) && isPossibleBlock(game, x, y, selectedNumber); }
3
@Override public void actionPerformed(GuiButton button) { if(button.id == 0) { GameStatistics.lives--; MapGenerator gen = new MapGeneratorSimple(); Remote2D.guiList.pop(); Remote2D.guiList.push(new GuiLoadMap(gen, 40, 40, 1337)); } else if(button.id == 1) { while(!(Remote2D.guiList.peek() instanceof GuiMainMenu)) Remote2D.guiList.pop(); } }
3
public String readDword(Key key, String valueName) throws RegistryErrorException { if(key == null) throw new NullPointerException("Registry key cannot be null"); if(valueName == null) throw new NullPointerException("Valuename cannot be null, because the default value is always a STRING! If you want to read a String use readValue"); String ret = extractAnyValue(key.getPath(), valueName); //if it is not null and it starts with hex: it is hopefully a binary entry if(ret != null && ret.startsWith(DWORD_KEY)) { return ret.substring(6); } return null; }
4
public double distanceFromLine(double testAngle) { if (leftDist <= 0 && rightDist <= 0) return 0; double x1 = leftDist * Math.cos(leftAngle); double y1 = leftDist * Math.sin(leftAngle); double x2 = rightDist * Math.cos(rightAngle); double y2 = rightDist * Math.sin(rightAngle); //Method uses a formula for drawing a straight line in polar coordinates. if (Math.abs(x2 - x1) > Math.abs(y2 - y1)) { double coeff = (y2-y1)/(x2-x1); return (y1 - x1*coeff)/(Math.sin(testAngle) - coeff * Math.cos(testAngle)); } //Other formula is used in case coefficent's denominator is close to zero. double coeff = (x2-x1)/(y2-y1); return (x1 - y1*coeff)/(Math.cos(testAngle) - coeff * Math.sin(testAngle)); }
3
Client() throws IOException { String s; System.out.println(getCurrentTime() + "::" +"Starting Client .."); clientSocket = new Socket("localhost", 38000); serverIn=new DataInputStream(clientSocket.getInputStream()); serverOut=new DataOutputStream(clientSocket.getOutputStream()); /*--------Reading file from The location specified--------*/ File file = new File("C:/Users/Devi/Documents/scu/COEN233/project/Project/Demo/March9/AmbikaPreethi/src/ClientServer/test.txt"); /*---- Creating an input stream to get data from file--------*/ DataInputStream bin = null; try { FileInputStream fin = new FileInputStream(file); bin = new DataInputStream(fin); /*---- An input stream to receive Patient Data from server----*/ BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); /*-----An output stream to send out the text file to server------*/ DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream()); /*---------read file using BufferedInputStream------*/ while( bin.available() > 0 ){ @SuppressWarnings("deprecation") String toserver = bin.readLine(); System.out.println(toserver); /*------- Send it out to the Server--------*/ serverOut.writeUTF(toserver + '\n'); } /*--- Reading data sent by server And displaying the output--------*/ String PatientInfo = serverIn.readUTF(); String UpdatedPatientInfo[] = PatientInfo.split(" "); String PatientId = UpdatedPatientInfo[1]; String PatientFirstName = UpdatedPatientInfo[3]; String PatientLastName = UpdatedPatientInfo[5]; String PatientAge = UpdatedPatientInfo[7]; System.out.println(Client.getCurrentTime() + "::" +"Patient ID: " +PatientId); System.out.println("Pateint First Name: "+PatientFirstName); System.out.println("Patient Last Name "+PatientLastName); System.out.println("Patient Age: "+PatientAge); } catch(FileNotFoundException e) { System.out.println("File not found" + e); } catch(IOException ioe) { System.out.println("Exception while reading the file " + ioe); } }
3
private void bubbleUp(int pos) { int last = heap[pos]; Integer parentPos = parent(pos); if(parentPos != null) { if(heap[parentPos] < last) { swap(pos, parentPos); bubbleUp(parentPos); } } }
2
public void zetJokerIn(Timer timer) throws LogicException { int jokers = getMaxJokers(timer); if (jokers <= 0) throw new LogicException("Jokers zijn op!"); jokersGebruikt++; timer.addJoker(); }
1
private void stepEntities(Graphics2D graphics) { Iterator<Entity> it = entities.iterator(); while (it.hasNext()) { Entity entity = it.next(); if (paused || quitRequested) { entity.draw(graphics); continue; } entity.step(); if (entity.isDead()) { if (entity instanceof PlayerShip) killPlayer((PlayerShip) entity); else if (entity instanceof EnemyShip) killEnemy((EnemyShip) entity); else if (entity instanceof Bullet) killBullet((Bullet) entity); else if (entity instanceof Pickup) { waitForPickup = false; upgrade = ((Pickup) entity).getUpgrade(); } it.remove(); } else entity.draw(graphics); } }
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Effect other = (Effect) obj; if (Float.floatToIntBits(effectDuration) != Float .floatToIntBits(other.effectDuration)) return false; if (expired != other.expired) return false; if (type != other.type) return false; return true; }
6
public Items getNext() { return next; }
0
Node<Move, GS> selectChild() { if (unexpanded() || terminated()) { // Leaf node or node of a terminated state, nothing to select. return null; } if (gameState.currentPlayer() == GameState.PLAYER_CHANCE_NODE) { assert chanceNodeChildren != null; return chanceNodeChildren.get(); } else { if (visitCount == 0) { return randomElement(children); } double maxScore = -Double.MAX_VALUE; Node<Move, GS> selected = null; ArrayList<Node<Move, GS>> unvisitedChildren = new ArrayList<>(); for (Node<Move, GS> child : children) { if (child.visitCount() == 0) { unvisitedChildren.add(child); continue; } if (unvisitedChildren.isEmpty()) { double uctScore = child.sumScores() / child.visitCount() + UCT_Coef * Math.sqrt(Math.log(visitCount) / child.visitCount()); if (uctScore > maxScore) { maxScore = uctScore; selected = child; } } } return unvisitedChildren.isEmpty() ? selected : randomElement(unvisitedChildren); } }
9
private void fillLevel() { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { walkways[i][j] = false; } } }
2
@Test public void TestSort() { MyList<Integer> list = new MyList<Integer>(); list.add(5); list.add(3); list.add(8); list.add(13); list.add(8); list.mergeSort(); Boolean res = (list.get(1) == 3 && list.get(2) == 5 && list.get(3) == 8 && list.get(4) == 8 && list.get(5) == 13); assertEquals(Boolean.TRUE, res); }
4
public void modeAuto(Loan loan) { if (user.isAllowedToBorrow(loan, this.getStockController())) { if (CalendarController.checkCalendars(loan.getStart(), loan.getEnd())) { if (this.getStockController().isAvailable(loan) && CalendarController.differenceDate(loan.getStart(), loan.getEnd()) < this.getStockController() .numberOfDayMaterialCanBeLoaned(loan)) { System.out .println("Your loan has been automatically validated."); this.getStockController().getStock().getLoans().add(loan); System.out.println("Loan added : "); System.out.println(loan.toString()); } else { System.out .println("Your loan is not valid. You claim to much equipment."); int quantity = this.getStockController() .numberOfMaterialAvailable(loan); System.out.print("You could have claimed " + quantity + loan.getName() + "."); int period = this.getStockController() .numberOfDayMaterialCanBeLoaned(loan); System.out.println("For a period of " + period + " days"); GregorianCalendar start = this.getStockController() .dayWhenMaterialIsAvailable(loan); if (start != null) { System.out.println("Or wait until " + CalendarController.calendarToString(start)); GregorianCalendar end = this.getStockController() .dayWhenMaterialIsNotAvailable(loan); System.out.print(" to " + CalendarController.calendarToString(end)); } } } else { System.out.println("Wrong parameters : \tCalendars."); } } else { System.out.println("You are not allowed to make this loan."); } }
5
private static Outline createTestPanel(boolean wrapped) { Outline outline = new Outline(); OutlineModel model = outline.getModel(); outline.setDynamicRowHeight(wrapped); Column column = new Column(0, "Testy Goop", new TextCell(SwingConstants.LEFT, wrapped)); //$NON-NLS-1$ model.addColumn(column); for (int i = 2; i < 10; i++) { column = new Column(i - 1, Integer.toString(i), new TextCell(SwingConstants.RIGHT)); model.addColumn(column); } int rowCount = 0; for (int i = 0; i < 10000; i++) { rowCount += buildRows(model); } System.out.println("Added " + Numbers.format(rowCount) + " nodes"); //$NON-NLS-1$ //$NON-NLS-2$ outline.sizeColumnsToFit(); outline.setSize(outline.getPreferredSize()); return outline; }
2
public RangeType(ReferenceType bottomType, ReferenceType topType) { super(TC_RANGE); if (bottomType == tNull) throw new alterrs.jode.AssertError("bottom is NULL"); this.bottomType = bottomType; this.topType = topType; }
1
public int maximumGap_bucket(int[] num) { if (num.length < 2) return 0; int max = findMinMax(num, 1); int min = findMinMax(num, -1); int buckets = num.length - 1; double step = (max - min + 0.0) / buckets; // bucketize Map<Integer, List<Integer>> bucketMinMax = bucketize(num, min, step); int lastMax = bucketMinMax.get(0).size() > 1 ? bucketMinMax.get(0).get(1) : bucketMinMax.get(0).get(0); int maxGap = lastMax - min; for (int i = 1; i < buckets; i++) { List<Integer> list = bucketMinMax.get(i); if (list != null && list.size() > 0) { maxGap = Math.max(maxGap, list.get(0) - lastMax); lastMax = list.size() > 1 ? list.get(1) : list.get(0); } } return maxGap; }
6
public Insanity[] check(CacheEntry... cacheEntries) { if (null == cacheEntries || 0 == cacheEntries.length) return new Insanity[0]; if (null != ramCalc) { for (int i = 0; i < cacheEntries.length; i++) { cacheEntries[i].estimateSize(ramCalc); } } // the indirect mapping lets MapOfSet dedup identical valIds for us // // maps the (valId) identityhashCode of cache values to // sets of CacheEntry instances final MapOfSets<Integer, CacheEntry> valIdToItems = new MapOfSets<Integer, CacheEntry>(new HashMap<Integer, Set<CacheEntry>>(17)); // maps ReaderField keys to Sets of ValueIds final MapOfSets<ReaderField, Integer> readerFieldToValIds = new MapOfSets<ReaderField, Integer>(new HashMap<ReaderField, Set<Integer>>(17)); // // any keys that we know result in more then one valId final Set<ReaderField> valMismatchKeys = new HashSet<ReaderField>(); // iterate over all the cacheEntries to get the mappings we'll need for (int i = 0; i < cacheEntries.length; i++) { final CacheEntry item = cacheEntries[i]; final Object val = item.getValue(); if (val instanceof FieldCache.CreationPlaceholder) continue; final ReaderField rf = new ReaderField(item.getReaderKey(), item.getFieldName()); final Integer valId = Integer.valueOf(System.identityHashCode(val)); // indirect mapping, so the MapOfSet will dedup identical valIds for us valIdToItems.put(valId, item); if (1 < readerFieldToValIds.put(rf, valId)) { valMismatchKeys.add(rf); } } final List<Insanity> insanity = new ArrayList<Insanity>(valMismatchKeys.size() * 3); insanity.addAll(checkValueMismatch(valIdToItems, readerFieldToValIds, valMismatchKeys)); insanity.addAll(checkSubreaders(valIdToItems, readerFieldToValIds)); return insanity.toArray(new Insanity[insanity.size()]); }
7
public final static String date(long millis) { long secs = millis / 1000; long mins = secs / 60; long hours = mins / 60; long days = hours / 24; final long years = days / 365; long year = 1970 + years; days -= getDays(year); if (days < 0) { if (isLeap(--year)) { days += 366; } else { days += 365; } } int month = 0; if (days > Time.daysOfMonth[month]) { days -= Time.daysOfMonth[month++]; final int daysFeb; if (isLeap(year)) { daysFeb = Time.daysOfMonth[month] + 1; } else { daysFeb = Time.daysOfMonth[month]; } if (days > daysFeb) { days -= daysFeb; month++; while (days > Time.daysOfMonth[month]) { days -= Time.daysOfMonth[month++]; } } } final String timeString = String.format("%02d:%02d:%02d", ++hours % 24, ++mins % 60, ++secs % 60) + " " + ++days + " " + ++month + " " + year; // System.out.println("calculated: " + timeString + " (" // + getMonthName(String.valueOf(month)) + ")"); return timeString; }
6
@Override public void destroy() { synchronized (this) { doDestroy(); } }
0
public void paivita(Object uusi, int rivi, int sarake) { Henkilo henkilo = henkilot.get(rivi); if (sarake == 0) henkilo.setId(((Integer) uusi).intValue()); else if (sarake == 1) henkilo.setEtunimi((String) uusi); else if (sarake == 2) henkilo.setSukunimi((String) uusi); else if (sarake == 3) henkilo.setSyntymavuosi(((Integer) uusi).intValue()); else if (sarake == 4) henkilo.setMaa((String) uusi); else if (sarake == 5) henkilo.setRooli((String) uusi); henkilot.remove(rivi); henkilot.add(rivi, henkilo); tallenna(); }
6
public Column getColumnWithID(int id) { int count = getColumnCount(); for (int i = 0; i < count; i++) { Column column = getColumnAtIndex(i); if (column.getID() == id) { return column; } } return null; }
2
private String findChromosomeName( BPTreeNode thisNode, int chromID){ String chromKey = null; // mark unfound condition as an empty string // search down the tree recursively starting with the root node if(thisNode.isLeaf()) { int nLeaves = thisNode.getItemCount(); for(int index = 0; index < nLeaves; ++index){ BPTreeLeafNodeItem leaf = (BPTreeLeafNodeItem)thisNode.getItem(index); if(leaf.getChromID() == chromID){ // mChromosome key match chromKey = leaf.getChromKey(); break; } // else check next leaf } } else { // check all child nodes int nNodes = thisNode.getItemCount(); for(int index = 0; index < nNodes; ++index){ BPTreeChildNodeItem childItem = (BPTreeChildNodeItem)thisNode.getItem(index); BPTreeNode childNode = childItem.getChildNode(); // check if key is in the node range int lowestID = childNode.getLowestChromID(); int highestID = childNode.getHighestChromID(); // test chromosome ID against node ID range if(chromID >= lowestID && chromID <= highestID) { // keep going until leaf items are checked chromKey = findChromosomeName(childNode, chromID); // check for chromosome ID match if(chromKey != null) break; } } } return chromKey; }
7
private void mergePhrasemes(List<Homonym> result, List<List<Phraseme>> phrasemes) { for (Homonym homonym : result) { //System.out.println(homonym.getOrig()); for (List<Phraseme> phs: phrasemes) { if (phs != null) { if (homonym.getOrig().equals(phs.get(0).getOrig())) { //1st contains the homonym itself for (int i = 1; i<phs.size(); i++) { Phraseme ph = phs.get(i); ph.setType(VariantHelper.getPhrasemeType(ph.getOrig())); ph.setOrig(StringHelper.removeExpr(ph.getOrig())); //remove expr. semi-/fix. from orig if (ph.getOrig().matches("^[IV]+[a-j]{1}\\s.*$")) { //is expression String mloc = ph.getOrig().substring(0, ph.getOrig().indexOf(" ")).trim(); //System.out.println("XXX mergePhrasemes for: " + homonym.getOrig() + " with: " + ph.getOrig() + " at loc: " + mloc); if (getWTIndex(mloc) < homonym.getWords().size() && getMnngIndex(mloc) < homonym.getWords().get(getWTIndex(mloc)).getMeanings().size()) { ph.setOrig(StringUtils.removeStart(ph.getOrig(), mloc).trim()); homonym.getWords().get(getWTIndex(mloc)).getMeanings().get(getMnngIndex(mloc)).addExpression(ph); } } else { homonym.addIdiom(ph); } } } } } } }
8
@Basic @Column(name = "POP_TERMINAL") public String getPopTerminal() { return popTerminal; }
0
public static void listarVenta(HashMap<Integer, Ventas> tablaVentas) { int codigoCliente; int codigoMusica; int codigoVenta; if (tablaVentas.isEmpty()) // No hay ventas en el sistema { System.out.println("No hay ventas en el registro."); } else { Set<Entry<Integer,Ventas>> s = tablaVentas.entrySet(); Iterator<Entry<Integer, Ventas>> it=s.iterator(); Entry<Integer, Ventas> m = null; while (it.hasNext()) // Recorremos las ventas almacenadas { m =it.next(); codigoCliente=(int)m.getValue().codCliente; codigoMusica=(int)m.getValue().codMusica; codigoVenta=(int)m.getValue().codVenta; System.out.println("Codigo de cliente: "+codigoCliente+" Codigo de disco: "+codigoMusica+" Codigo de venta: "+codigoVenta); } } }
2
public List<T> find(T start, T goal, StopDemander stop) { Node<T> startNode = new Node<T>(start, null); if (start.equals(goal)) { return startNode.getPathElements(); } List<Node<T>> queue = new LinkedList<Node<T>>(); Set<T> visited = new HashSet<T>(); queue.add(startNode); visited.add(start); while (!queue.isEmpty()) { Node<T> node = queue.remove(queue.size() - 1); List<T> successors = ProductionUtil.getSuccessors( node.getElement(), productions); for (T successor : successors) { if (!visited.contains(successor)) { Node<T> subNode = new Node(successor, node); if (successor.equals(goal)) { // The goal is found return subNode.getPathElements(); } queue.add(subNode); visited.add(successor); } } } // Not found return null; }
5
public boolean equals(Object object) { Pair pair = (Pair) object; return from.equals(pair.from) && to.equals(pair.to); }
1
public static String toProperCase(String s) { if (s.isEmpty()) return ""; String[] unimportant = new String[] { "a", "an", "and", "but", "is", "are", "for", "nor", "of", "or", "so", "the", "to", "yet" }; String[] split = s.split("\\s+"); String result = ""; for (int i = 0; i < split.length; i++) { String word = split[i]; boolean capitalize = true; for (String str : unimportant) { if (str.equalsIgnoreCase(word)) { if (i > 0 && i < split.length - 1) { //middle unimportant word capitalize = false; break; } } } if (capitalize) result += capitalize(word) + " "; else result += word.toLowerCase() + " "; } return result.trim(); }
7
@Override public void paintComponent(final Graphics g) { // Check if we have a running game super.paintComponent(g); g.setColor(this.getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); if (this.model != null) { // Draw all tiles by going over them x-wise and y-wise. for (int i = 0; i < this.modelSize.width; i++) { for (int j = 0; j < this.modelSize.height; j++) { GameTile tile = this.model.getGameboardState(i, j); tile.draw(g, i * this.tileSize.width, j * this.tileSize.height, this.tileSize); } } } else { g.setFont(new Font("Sans", Font.BOLD, 24)); g.setColor(Color.BLACK); final char[] message = "No model chosen.".toCharArray(); g.drawChars(message, 0, message.length, 50, 50); } }
3
private void initTools() { JToolBar toolBar = new JToolBar(); toolBar.setFloatable(false); toolBar.setPreferredSize(new Dimension(30, 28)); toolBar.add(new JLabel("Mode ")); final JComboBox<EditorMode> modeBox = new JComboBox<EditorMode>(); modeBox.addItem(EditorMode.GUI); modeBox.addItem(EditorMode.NODE); toolBar.add(modeBox); toolBar.addSeparator(); final JToggleButton debugButton = new JToggleButton( IconsLibrary.getIcon(IconsLibrary.RunDebug, 22)); debugButton.setToolTipText("Debug"); final JToggleButton runButton = new JToggleButton(IconsLibrary.getIcon( IconsLibrary.Run, 22)); runButton.setToolTipText("Run"); runButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { editor_.setMode((editor_.getMode() == EditorMode.RUN ? (EditorMode) modeBox .getSelectedItem() : EditorMode.RUN)); rightPanel_.setVisible(editor_.getMode() == EditorMode.RUN ? false : true); modeBox.setEnabled(editor_.getMode() != EditorMode.RUN); debugButton.setEnabled(modeBox.isEnabled()); if (modeBox.isEnabled()) { runButton.setIcon(IconsLibrary .getIcon(IconsLibrary.Run, 22)); } else { runButton.setIcon(IconsLibrary.getIcon(IconsLibrary.Stop, 22)); } revalidate(); } }); toolBar.add(runButton); toolBar.add(debugButton); toolBar.addSeparator(new Dimension(30, 10)); JButton saveButton = new JButton(IconsLibrary.getIcon( IconsLibrary.FileSave, 22)); saveButton.setToolTipText("Save"); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Create a file chooser final JFileChooser fc = new JFileChooser(); // In response to a button click: int returnVal = fc.showSaveDialog(MainPanel.this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { File f = fc.getSelectedFile(); Document doc = XMLBuilder.makeDoc(); doc.appendChild(editor_.getXML(doc)); XMLBuilder.saveDoc(doc, f); } catch (Exception e) { JOptionPane.showMessageDialog(MainPanel.this, e.getMessage()); e.printStackTrace(); } } } }); toolBar.add(saveButton); JButton openButton = new JButton(IconsLibrary.getIcon( IconsLibrary.FileOpen, 22)); openButton.setToolTipText("Open"); openButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Create a file chooser final JFileChooser fc = new JFileChooser(); // In response to a button click: int returnVal = fc.showOpenDialog(MainPanel.this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { File f = fc.getSelectedFile(); Document doc = XMLBuilder.loadDoc(f); editor_.loadXML(doc.getDocumentElement()); } catch (Exception e) { JOptionPane.showMessageDialog(MainPanel.this, e.getMessage()); e.printStackTrace(); } } } }); toolBar.add(openButton); debugButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { editor_.setMode((editor_.getMode() == EditorMode.DEBUG ? (EditorMode) modeBox .getSelectedItem() : EditorMode.DEBUG)); modeBox.setEnabled(editor_.getMode() != EditorMode.DEBUG); runButton.setEnabled(modeBox.isEnabled()); revalidate(); if (modeBox.isEnabled()) { debugButton.setIcon(IconsLibrary.getIcon( IconsLibrary.RunDebug, 22)); } else { debugButton.setIcon(IconsLibrary.getIcon(IconsLibrary.Stop, 22)); } } }); modeBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { editor_.setMode((EditorMode) modeBox.getSelectedItem()); } }); this.add(toolBar, BorderLayout.NORTH); rightPanel_ = new RightPanel(); rightPanel_.setSize(new Dimension(300, 100)); rightPanel_.setPreferredSize(new Dimension(300, 100)); this.add(rightPanel_, BorderLayout.LINE_END); }
9
public static void addToTable(Item item,int quantity) throws NullPointerException { if (item.getQuantity() >= quantity) { total = (getTotal() + item.getPrice() * quantity); item.changeQuantity(-quantity); modifyItem(item); int datalength = (tableData == null ? 0 : tableData.length); Object[][] temp = new Object[datalength + 1][5]; if (tableData != null) for (int i = 0; i < datalength; i++) for (int j = 0; j < 5; j++) temp[i][j] = tableData[i][j]; temp[datalength][0] = item.getId(); temp[datalength][1] = item.getName(); temp[datalength][2] = quantity; temp[datalength][3] = item.getPrice(); temp[datalength][4] = item.getDescription(); tableData = temp; } }
5
private static void secondStrategy() { Semaphore MReading = new Semaphore(1); Semaphore MWriting = new Semaphore(1); Semaphore MPrio = new Semaphore(1); int counter = 0; Random r = new Random(); while(true) { if(r.nextDouble() > 0.5) new Lecteur(MReading,MWriting, counter).run(); else new Redacteur2(MWriting,MPrio).run(); } }
2
private Iterable<Position<T>> positions() throws InvalidPositionException, BoundaryViolationException, EmptyTreeException { ArrayList<Position<T>> ps = new ArrayList<Position<T>>(); if (size != 0) { preOrderPositions(root(), ps); // inOrderPositions(root(), ps); // postOrderPositions(root(), ps); } return ps; }
1
public synchronized void samplesUpload(List<JSONObject> samples, String callBackUrl) { try { JSONObject data = new JSONObject(); data.put(Constants.SAMPLES, new JSONArray(samples)); getJson(Methods.POST, callBackUrl, data); } catch (JSONException e) { BmLog.error("Failed to upload samples: " + e.getMessage()); } }
1
public void removeEdge(Collection<Edge> e_list){ NodeFunction f;// = e.getSource(); NodeVariable x;// = e.getDest(); FunctionEvaluator fe;// = f.getFunction(); HashMap<NodeFunction, LinkedList<NodeVariable>> f_xs = new HashMap<NodeFunction, LinkedList<NodeVariable>>(); HashMap<NodeVariable, LinkedList<NodeFunction>> x_fs = new HashMap<NodeVariable, LinkedList<NodeFunction>>(); for (Edge e:e_list){ f = e.getSource(); x = e.getDest(); // add f -> x1,x2,..,xn // of variables to be removed from f if (!f_xs.containsKey(f)){ f_xs.put(f, new LinkedList<NodeVariable>()); } f_xs.get(f).add(x); // add x -> f1,f2,..fn // of functions to be removed from x if (!x_fs.containsKey(x)){ x_fs.put(x, new LinkedList<NodeFunction>()); } x_fs.get(x).add(f); // remove e from this factorgraph edges set this.edges.remove(e); } // step 1&2 // minimize function on remaining args // remove NodeVariable from function // TODO: change with entryset for (NodeFunction key_f : f_xs.keySet()){ key_f.removeNeighbours( f_xs.get(key_f) ); } // step 3 // remove NodeFunction from variable for (NodeVariable key_x : x_fs.keySet()){ key_x.removeNeighbours( x_fs.get(key_x) ); } }
5
public void notifySpritePaletteChanged() { if (paletteRegion != null) { paletteRegion.resetPalette(); } for (int i = 0; i < patternTableRegions.length; i++) { if (patternTableRegions[i] != null) { patternTableRegions[i].updatePatternTable(); } } for (int i = 0; i < nameTableRegions.length; i++) { if (nameTableRegions[i] != null) { nameTableRegions[i].updateNameTableTiles(true); } } if (editorRegion != null) { editorRegion.repaint(); } if (animationGrid != null) { animationGrid.updateAnimationView(); } }
7
public static int loadShaderPair(String vertexShaderLocation, String fragmentShaderLocation) { int shaderProgram = glCreateProgram(); int vertexShader = glCreateShader(GL_VERTEX_SHADER); int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); StringBuilder vertexShaderSource = new StringBuilder(); StringBuilder fragmentShaderSource = new StringBuilder(); try { InputStream is = ShaderLoader.class.getClassLoader().getResourceAsStream(vertexShaderLocation); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while ((line = reader.readLine()) != null) { vertexShaderSource.append(line).append('\n'); } reader.close(); } catch (IOException e) { System.err.println("Vertex shader wasn't loaded properly."); Display.destroy(); System.exit(1); } try { InputStream is = ShaderLoader.class.getClassLoader().getResourceAsStream(fragmentShaderLocation); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while ((line = reader.readLine()) != null) { fragmentShaderSource.append(line).append('\n'); } reader.close(); } catch (IOException e) { System.err.println("Fragment shader wasn't loaded properly."); Display.destroy(); System.exit(1); } glShaderSource(vertexShader, vertexShaderSource); glCompileShader(vertexShader); if (glGetShaderi(vertexShader, GL_COMPILE_STATUS) == GL_FALSE) { System.err .println("Vertex shader wasn't able to be compiled correctly. Error log:"); System.err.println(glGetShaderInfoLog(vertexShader, 1024)); } glShaderSource(fragmentShader, fragmentShaderSource); glCompileShader(fragmentShader); if (glGetShaderi(fragmentShader, GL_COMPILE_STATUS) == GL_FALSE) { System.err .println("Fragment shader wasn't able to be compiled correctly. Error log:"); System.err.println(glGetShaderInfoLog(fragmentShader, 1024)); } glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glValidateProgram(shaderProgram); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); return shaderProgram; }
6
public static void main(String[] args) throws Throwable{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int caso = 1; for(String line; (line = in.readLine())!=null; caso++){ StringTokenizer st = new StringTokenizer(line); N = Integer.parseInt(st.nextToken()); X = Integer.parseInt(st.nextToken()); sb.append("Selection #").append(caso).append("\n"); deck = new int[20]; for (int i = 0; i < 20; i++) deck[i]=Integer.parseInt(st.nextToken()); List<Integer> people = new ArrayList<Integer>(); for (int i = 1; i <= N; i++) { people.add( i ); } int indexDeck = 0; while( people.size() > X && indexDeck < deck.length ){ System.out.println(people.size() + " " + deck[indexDeck]); for (int i = 0, j = 0; i < people.size() && people.size() > X; j++) { i+=deck[indexDeck]; if( i-j < people.size() ) people.remove(i-j); System.out.println(people + " "); } indexDeck++; } } System.out.print(new String(sb.substring(0,sb.length()-1))); }
8
public CtrlComptesRendus getCtrlCR() { return ctrlCR; }
0
@SuppressWarnings("unchecked") private void mondayCheckActionPerformed(java.awt.event.ActionEvent evt) { if(this.dayChecks[1].isSelected()) { this.numSelected++; if(this.firstSelection) { stretch(); } this.models[1] = new DefaultListModel<Object>(); this.mondayJobList.setModel(this.models[1]); this.mondayScrollPane.setViewportView(this.mondayJobList); this.mondayJobName.setColumns(20); this.mondayLabel.setText("Job Name:"); this.mondayAddJob.setText("Add Job"); this.mondayAddJob.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { if(!Config.this.mondayJobName.getText().isEmpty()) { Config.this.models[1].addElement(Config.this.mondayJobName.getText()); Config.this.mondayJobList.setModel(Config.this.models[1]); Config.this.mondayJobName.setText(""); } } }); this.mondayDeleteJob.setText("Delete Job"); this.mondayDeleteJob.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { while(!Config.this.mondayJobList.isSelectionEmpty()) { int n = Config.this.mondayJobList.getSelectedIndex(); Config.this.models[1].remove(n); } } }); javax.swing.GroupLayout mondayTabLayout = new javax.swing.GroupLayout(this.mondayTab); this.mondayTab.setLayout(mondayTabLayout); mondayTabLayout.setHorizontalGroup( mondayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mondayTabLayout.createSequentialGroup() .addContainerGap() .addComponent(this.mondayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(mondayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mondayTabLayout.createSequentialGroup() .addComponent(this.mondayLabel) .addGroup(mondayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mondayTabLayout.createSequentialGroup() .addGap(14, 14, 14) .addComponent(this.mondayAddJob)) .addGroup(mondayTabLayout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(this.mondayJobName, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(this.mondayDeleteJob)) .addContainerGap(431, Short.MAX_VALUE)) ); mondayTabLayout.setVerticalGroup( mondayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mondayTabLayout.createSequentialGroup() .addContainerGap() .addGroup(mondayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(mondayTabLayout.createSequentialGroup() .addGroup(mondayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(this.mondayJobName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(this.mondayLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(this.mondayAddJob) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(this.mondayDeleteJob)) .addComponent(this.mondayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(25, Short.MAX_VALUE)) ); this.dayTabs.addTab("Monday", this.mondayTab); } else { this.numSelected--; stretch(); this.dayTabs.remove(this.mondayTab); } }
4
public static PrototypeManager getManager() { if (pm == null) { pm = new PrototypeManager(); } return pm; }
1
public Method findMethod(String prefix, String methodName, Class<?> ... paramType) { if(methodName == null || methodName.isEmpty()) return null; methodName = createMethodName(prefix, methodName); try { return getInspectedClass().getDeclaredMethod(methodName, paramType); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } return null; }
5
public ChestKitsConfiguration(Configuration config, Logger log) { kits = new HashMap<String, ChestKitsKit>(); List<String> listOfKits = config.getStringList("kits"); if (listOfKits != null) { for (String kitName : listOfKits) { log.info("Loading kit " + kitName); List<?> items = config.getList("kititems." + kitName); if (items == null) { log.severe("Kit " + kitName + " has no items defined! Skipping..."); continue; } List<ItemStack> itemStacks = new LinkedList<ItemStack>(); for (Object o : items) { if (o instanceof ItemStack) { itemStacks.add((ItemStack)o); } else { log.severe("Invalid object found in configuration for kit " + kitName + ": " + o); } } long cooldown = config.getLong("kitcooldown." + kitName, 0L); ChestKitsKit kit = new ChestKitsKit(kitName, itemStacks); kit.setCooldown(cooldown); addKit(kitName, kit); } } log.info("Successfully loaded " + kits.size() + " kits."); }
6
public Operation sendUnconnectedOperation(final Operation operation) throws ConnectionException, TimeoutException { try { if (OperationType.isADisconnectedOperation(operation.getOperationType())) { createSocket(); MessageUtils.sendOperation(sock, operation); int retry = 0; Operation response; sock.setSoTimeout(30000); do { response = MessageUtils.getOperation(sock); if (response.getOperationType().equals(operation.getOperationType())) { return response; } retry ++; LOG.warn("Received " + response.getOperationType().toString() + " instead of " + operation.getOperationType() + "! Retrying to get the operation." ); } while (!response.getOperationType().equals(operation.getOperationType()) || retry <= 10); } } catch (SocketTimeoutException s) { LOG.error("Server didn't answer in time..."); throw new TimeoutException(s.getMessage()); } catch (IOException e) { LOG.error("Operation " + operation.getOperationType().toString() + " has failed!"); throw new ConnectionException(e.getMessage()); } finally { //remove timeout option try { if (sock != null && !sock.isClosed()) { sock.setSoTimeout(0); } } catch (SocketException e) {} } return null; }
9
public static Map<String, String> simpleCommandLineParser(String[] args) { Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i <= args.length; i++) { String key = (i > 0 ? args[i-1] : null); String value = (i < args.length ? args[i] : null); if (key == null || key.startsWith("-")) { if (value != null && value.startsWith("-")) value = null; if (key != null || value != null) map.put(key, value); } } return map; }
9
private void RemoveArestas() { LinkedList<Aresta> arestasPesoMinimo = new LinkedList<Aresta>(); ArrayList<Aresta> arestasAGM = (ArrayList<Aresta>) grafoDePalavrasAGM.Arestas(); Aresta[] arestasGrafoAGM = new Aresta[arestasAGM.size()]; for (int i = 0; i < arestasGrafoAGM.length; i++) arestasGrafoAGM[i] = arestasAGM.get(i); // Ordena Arestas QuickSortArestas.Ordena(arestasGrafoAGM); System.out.println("[" + sdf.format(calendario.getTime()) + "] " + "Ordenando Arestas (Quick Sort) . . .\n\n"); for (int i = 0; i < arestasGrafoAGM.length; i++) System.out.println(arestasGrafoAGM[i]); // Obtém k Arestas de peso mínimo da AGM for (int i = 0; i < numeroDeClusters - 1; i++) arestasPesoMinimo.add(arestasGrafoAGM[i]); System.out.println("\n\n[" + sdf.format(calendario.getTime()) + "] " + "Removendo Arestas de Peso Mínimo"); do { Aresta arestaMinima = arestasPesoMinimo.removeFirst(); // Remove Arestas for (int u = 0; u < grafoDePalavrasAGM.getNumeroDeVertices(); u++) { for (Aresta aresta : grafoDePalavrasAGM.Adjacencias(u)) { if (arestaMinima.getU() == aresta.getU() && arestaMinima.getV() == aresta.getV() && arestaMinima.getPeso() == aresta.getPeso()) { grafoDePalavrasAGM.RemoveAresta(aresta); } } // Fim de foreach } // Fim de for int u = 0 } while (arestasPesoMinimo.size() > 0); } // Fim do método RemoveAresta
9
@Override public void addWord(String word) { if (Math.random() <= Math.pow(2., -h)) { MyString str = new MyString(word); Integer i = sample.get(str); if (i == null) sample.put(str, 1); else sample.put(str, 1 + i.intValue()); sumK++; } if(sumK == Math.pow(2., b)){ h++; RandomDataGenerator rand = new RandomDataGenerator(); Iterator<MyString> it = sample.keySet().iterator(); while(it.hasNext()){ MyString s = it.next(); int ks = sample.get(s); sumK -= ks; int k = rand.nextBinomial(ks, 0.5); if(k != 0){ sample.put(s, k); sumK += k; } else it.remove(); } } }
5
@org.junit.Test public void multipleDragons() { Logic game1 = new Logic(10, 1, 1); char[][] maze=game1.getMaze(); int count=0; for(int i=0; i<10; i++) { for(int j=0; j<10; j++) { if(maze[i][j]=='D') count++; } } assertSame(count, 1); Logic game2 = new Logic(40, 2, 1); maze=game2.getMaze(); count=0; for(int i=0; i<40; i++) { for(int j=0; j<40; j++) { if(maze[i][j]=='D') count++; } } assertSame(count, 2); Logic game3 = new Logic(40, 3, 1); maze=game3.getMaze(); count=0; for(int i=0; i<40; i++) { for(int j=0; j<40; j++) { if(maze[i][j]=='D') count++; } } assertSame(count, 3); }
9
public Gap insertGapAt(int pos, int length, boolean exclusive) throws BadBytecode { /** * cursorPos indicates the next bytecode whichever exclusive is * true or false. */ Gap gap = new Gap(); if (length <= 0) { gap.position = pos; gap.length = 0; return gap; } byte[] c; int length2; if (bytecode.length + length > Short.MAX_VALUE) { // currentPos might change after calling insertGapCore0w(). c = insertGapCore0w(bytecode, pos, length, exclusive, get().getExceptionTable(), codeAttr, gap); pos = gap.position; length2 = length; // == gap.length } else { int cur = currentPos; c = insertGapCore0(bytecode, pos, length, exclusive, get().getExceptionTable(), codeAttr); // insertGapCore0() never changes pos. length2 = c.length - bytecode.length; gap.position = pos; gap.length = length2; if (cur >= pos) currentPos = cur + length2; if (mark > pos || (mark == pos && exclusive)) mark += length2; } codeAttr.setCode(c); bytecode = c; endPos = getCodeLength(); updateCursors(pos, length2); return gap; }
6
@Override public void tableChanged(TableModelEvent arg0) { if(ignoreNext) { ignoreNext = false; return; } //System.out.println(""+arg0.getColumn()+" "+arg0.getFirstRow()+" "+arg0.getLastRow()+" "+arg0.getType()); int col = arg0.getColumn(); int row = arg0.getFirstRow(); int regvalue = 0; try { Object val = table.getValueAt(row, col); if(val instanceof Integer) { regvalue = (Integer)val; } else { regvalue = Integer.parseInt((String)val); } } catch (NumberFormatException e) { this.ignoreNext(); if(col == 0) { table.setValueAt("V" + (row*2), row, col); return; } if(col == 2) { table.setValueAt("V" + (row*2 + 1), row, col); return; } table.setValueAt("", row, col); return; } int regNumber = 0; if(col == 1) regNumber = row*2; if(col == 3) regNumber = row*2 + 1; cpu.setRegister(regNumber, regvalue); }
7
public static void onIntentFinished(Activity sourceActivity, int requestCode, int resultCode, Intent data, String devPayload) { InAppPurchaseExtension.logToAS("Intent finished"); sourceActivity.finish(); sourceActivity = null; if(requestCode == BUY_REQUEST_CODE) { if(resultCode == Activity.RESULT_CANCELED) { InAppPurchaseExtension.logToAS("Purchase has been cancelled!"); context.dispatchStatusEventAsync(InAppPurchaseMessages.PURCHASE_CANCELED, ""); } else { int responseCode = data.getIntExtra("RESPONSE_CODE", 0); String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA"); String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE"); if(responseCode == BILLING_RESPONSE_RESULT_OK) { JSONObject item = null; Boolean hasSimilarPayload = false; try { item = new JSONObject(purchaseData); hasSimilarPayload = devPayload.equals(item.getString("developerPayload")); } catch(Exception e) {context.dispatchStatusEventAsync(InAppPurchaseMessages.PURCHASE_FAILURE, "Error while converting the bought product data to JSONObject!"); return;} if(!hasSimilarPayload) { onPurchaseVerificationFailed(item, context.getActivity().getPackageName()); return; } JSONObject jsonObject = new JSONObject(); try{ jsonObject.put("productId", item.getString("productId")); jsonObject.put("transactionTimestamp", item.getInt("purchaseTime")); jsonObject.put("developerPayload", item.get("developerPayload")); jsonObject.put("purchaseToken", item.get("purchaseToken")); jsonObject.put("orderId", item.get("orderId")); jsonObject.put("signature", dataSignature); jsonObject.put("playStoreResponse", purchaseData); } catch(Exception e) {context.dispatchStatusEventAsync(InAppPurchaseMessages.PURCHASE_FAILURE, "Error while creating the returned JSONObject!"); return;} InAppPurchaseExtension.logToAS("The product has been successfully bought! returning it with the event ..."); context.dispatchStatusEventAsync(InAppPurchaseMessages.PURCHASE_SUCCESS, jsonObject.toString()); } else if(responseCode == BILLING_RESPONSE_RESULT_USER_CANCELED) { InAppPurchaseExtension.logToAS("Purchase has been cancelled!"); context.dispatchStatusEventAsync(InAppPurchaseMessages.PURCHASE_CANCELED, ""); } else { InAppPurchaseExtension.logToAS("The purchase failed! " + ERRORS_MESSAGES.get(responseCode)); context.dispatchStatusEventAsync(InAppPurchaseMessages.PURCHASE_FAILURE, ERRORS_MESSAGES.get(responseCode)); } } } }
7
public void put_branch(String roll, BasicDBObject document, DB_Init db_table, ArrayList<String> branchArray, ArrayList<String> rollStartArray, ArrayList<String> rollEndArray) { String first_char = roll.substring(0, 1); System.out.println("Outside branch insertion module "); for (int i = 0; i < branchArray.size(); ++i) { String startRoll = rollStartArray.get(i); String endRoll = rollEndArray.get(i); System.out.println("startROll : " + startRoll + " endROll : " + endRoll + "first_char : " + first_char + " Roll: " + roll); System.out.println(document); if (first_char.equals(startRoll.substring(0, 1))) { String temp_roll, temp_startRoll, temp_endRoll; temp_startRoll = startRoll.substring(1); temp_endRoll = endRoll.substring(1); temp_roll = roll.substring(1); long start = Integer.parseInt(temp_startRoll), end = Integer .parseInt(temp_endRoll), current_roll = Integer .parseInt(temp_roll); if (current_roll >= start && current_roll <= end) { if (document.containsField("Branch") == true) { System.out.println("START OF DOC" + document); String id = document.get("_id").toString(); BasicDBObject doc2 = new BasicDBObject(); doc2.put("Branch", branchArray.get(i)); db_table.original_table.update(new BasicDBObject("_id", id), doc2); } document.put("Branch", branchArray.get(i)); System.out.println("Inside branch insertion module " + branchArray.get(i)); } } } }
5
public synchronized void waitForNextDealConfirmation() { dealLatch = new CountDownLatch(1); KeyEventDispatcher dispatcher = new KeyEventDispatcher() { // Anonymous class invoked from EDT public boolean dispatchKeyEvent(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) dealLatch.countDown(); return false; } }; KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher); try { dealLatch.await(); // current thread waits here until countDown() is called } catch (InterruptedException ignored) { } KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(dispatcher); }
2
public String getLyrics(String artistName, String songName) throws UnexpectedDataException { String lyrics = ""; // TODO: Sanitize string try { URI xmlURI = new URI("http", "lyrics.wikia.com", "/api.php", "artist="+ artistName +"&song="+ songName +"&fmt=xml", null); InputStream xmlStream = this.getInputStream(xmlURI.toURL().toString()); String fullLyricsURL = this.getLyricURLFromXML(xmlStream); lyrics = this.getLyricsFromURL(fullLyricsURL); } catch (URISyntaxException e) { throw new UnexpectedDataException(); } catch (MalformedURLException e) { throw new UnexpectedDataException(); } return lyrics; }
2
public void setPort(int port) { clientPort = port; }
0
public static boolean deleteFolderContents(File folder) { File[] files = folder.listFiles(); for (File file : files) { if (file.isFile()) { if (!file.delete()) { return false; } } else { if (!deleteFolder(file)) { return false; } } } return true; }
4
public boolean equals(Object that) { if (!(that instanceof MockMessage)) return false; String thatMessage = ((MockMessage) that).getMessage(); if (this.message == null) return thatMessage == null; return (this.message == thatMessage) || this.message.equals(thatMessage); }
3
private boolean dadosValidos() { return !StringHelper.estaNulaOuVazia(txtCnpj.getText()) && !StringHelper.estaNulaOuVazia(txtEndereco.getText()) && !StringHelper.estaNulaOuVazia(txtNomeresponsavel.getText()) && !StringHelper.estaNulaOuVazia(txtRazaosocial.getText()) && !StringHelper.estaNulaOuVazia(txtTelefone.getText()); }
4
public Node getFirstNodeAtPosition(int x, int y) { Enumeration<Node> nodeEnumer = Runtime.nodes.getSortedNodeEnumeration(false); while(nodeEnumer.hasMoreElements()){ Node node = nodeEnumer.nextElement(); if(node.isInside(x, y, pt)) { return node; } } return null; }
2
public TrackedPeer(Torrent torrent, String ip, int port, ByteBuffer peerId) { super(ip, port, peerId); this.torrent = torrent; // Instanciated peers start in the UNKNOWN state. this.state = PeerState.UNKNOWN; this.lastAnnounce = null; }
0
boolean printHeaders(File targ, PrintStream ps) throws IOException { boolean ret = false; int rCode = 0; if (!targ.exists() || targ.getName().indexOf("..")>0) { rCode = HTTP_NOT_FOUND; ps.print("HTTP/1.0 " + HTTP_NOT_FOUND + " Not Found"); ps.write(EOL); ret = false; } else { rCode = HTTP_OK; ps.print("HTTP/1.0 " + HTTP_OK+" OK"); ps.write(EOL); ret = true; } WebServer.log("From " +s.getInetAddress().getHostAddress()+": GET " + targ.getAbsolutePath()+"-->"+rCode); ps.print("Server: simpleness"); ps.write(EOL); ps.print("Date: " + (new Date())); ps.write(EOL); if (ret) { if (!targ.isDirectory()) { ps.print("Content-length: " + targ.length()); ps.write(EOL); ps.print("Last Modified: " + new Date(targ.lastModified())); ps.write(EOL); String name = targ.getName(); int ind = name.lastIndexOf('.'); String ct = null; if (ind > 0) { ct = (String) map.get(name.substring(ind)); } if (ct == null) { ct = "unknown/unknown"; } ps.print("Content-type: " + ct); ps.write(EOL); } else { ps.print("Content-type: text/html"); ps.write(EOL); } if(targ.getName().equals("FileWriter.html") && WebServer.id.equals("null")) { WebServer.id = Double.toString(Math.random()); ps.print("Set-Cookie: zehut="+WebServer.id); ps.write(EOL); } } return ret; }
8
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ args1 = args; try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); }
6
public void startGUI() { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { getMf().setVisible(true); } }); }
6
public void checkCherries(ArrayList<EntityCherry> ch){ for(int i = 0; i < ch.size(); i++){ EntityCherry c = ch.get(i); if(sliding){ if( c.getx() > x && c.getx() < x + (cwidth / 2) && c.gety() > y - height / 2 && c.gety() < y + height / 2 ){ c.hit(1); } } if(intersects(c)){ hit(); } } }
7
public void run() { String csvFile = "USData.csv"; BufferedReader br = null; String line = ""; String cvsSplitBy = ","; int count = 0; try { br = new BufferedReader(new FileReader(csvFile)); //reads file line by line while ((line = br.readLine()) != null) { // use comma as separator // edge[i] = each comma seperated token String[] edge = line.split(cvsSplitBy); count++; //System.out.println("u: " + edge[0] // + " v: " + edge[1] + " weight: " + edge[2]); Edge n = new Edge(edge[0], edge[1], Integer.parseInt(edge[2]) ); SexyCities.addEdge(n); } } catch (FileNotFoundException e) { //incase file is not found } catch (IOException e) { } finally { if (br != null) { // close the bufferreader when file is done try { br.close(); } catch (IOException e) { } } } //message that lets the user know the file has been completely read System.out.printf("Done - Processed %d lines - %d cities",count, SexyCities.chrisCounter); }
5
public List<String> calculateMotifEnumeration() { List<String> kMers; List<String> resultList = new ArrayList<String>(); kMers = getAllKMers(); for (String s : kMers) { List<String> mismatchList = createMismatches(s); for (String string : mismatchList) { List<String> allMismatches = createMismatches(string); for (String mismatch : allMismatches) { if (appearsInAllStrings(mismatch) && !existsInList(resultList, mismatch)) { resultList.add(mismatch); } } } } return resultList; }
5
private ArrayList<Integer> straightLinePostProcessing(ArrayList<Integer> corners, double[] distApart) { ArrayList<Integer> filteredCorners = new ArrayList<Integer>(corners); boolean allLines = false; while (!allLines) { allLines = true; for (int i = 1; i < filteredCorners.size(); i++) { int c1 = filteredCorners.get(i - 1); int c2 = filteredCorners.get(i); if (!isLine(c1, c2, LINE_THRESHOLD)) { int newCorner = minDistBetweenIndices(distApart, c1, c2); filteredCorners.add(i, newCorner); allLines = false; } } } for (int i = 1; i < filteredCorners.size() - 1; i++) { int c1 = filteredCorners.get(i - 1); int c2 = filteredCorners.get(i); int c3 = filteredCorners.get(i + 1); if (isLine(c1, c3, LINE_THRESHOLD)) { filteredCorners.remove(i); i--; } } try { if (distance(pts.get(0), pts.get(filteredCorners.get(1))) < 15.0) { filteredCorners.remove(1); } if (distance(pts.get(pts.size() - 1), pts.get(filteredCorners.get(filteredCorners.size() - 2))) < 15.0) { filteredCorners.remove(filteredCorners.size() - 2); } } catch (Exception ex) { } return filteredCorners; }
8
public boolean setValue(String key, String value) { for(int i = 0; i < MAX_PROPS; i++) { if(keys_[i].equals(UNDEFINED)) { keys_[i] = key; values_[i] = value; return true; } } return false; }
2
private boolean jj_3_31() { if (jj_3R_48()) return true; return false; }
1
public static List<Pregunta> buscaTemaGlobal(int numPreguntas) { /* * Habría que hacer una consulta aleatoria que sólo devuelva n líneas */ List<Pregunta> c = null; if (openConexion() != null) { try { String qry = "SELECT * FROM preguntas"; PreparedStatement stmn = cnx.prepareStatement(qry); ResultSet rs = stmn.executeQuery(); c = new ArrayList<Pregunta>(); while (rs.next()) { Pregunta aux = recuperaPregunta(rs); c.add(aux); } rs.close(); stmn.close(); closeConexion(); } catch (Exception ex) { Logger.getLogger(PreguntaDAO.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } } //Tenemos en c todas las preguntas del tema "tema" java.util.Date date = new java.util.Date(); Collections.shuffle(c, new Random(date.getTime())); if (c == null || c.size() < numPreguntas) { return c; } else { return c.subList(0, numPreguntas); } }
5
private void kingLeftPossibleMove(Piece piece, Position position) { int x1 = position.getPositionX(); int y1 = position.getPositionY(); if((x1 >= 1 && y1 >= 0) && (x1 < maxWidth && y1 < maxHeight)) { if(board.getChessBoardSquare(x1-1, y1).getPiece().getPieceType() != board.getBlankPiece().getPieceType()) { if(board.getChessBoardSquare(x1-1, y1).getPiece().getPieceColor() != piece.getPieceColor()) { // System.out.print(" " + coordinateToPosition(x1-1, y1)+"*"); Position newMove = new Position(x1-1, y1); piece.setPossibleMoves(newMove); } } else { // System.out.print(" " + coordinateToPosition(x1-1, y1)); Position newMove = new Position(x1-1, y1); piece.setPossibleMoves(newMove); } } }
6
public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
7
@Override public String call() throws Exception { StringBuffer sb = new StringBuffer(); for (int i = 0; i < 10; i++) { sb.append(para); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } return sb.toString(); }
2
protected void handleCommand(Player sender, String[] names) { Zone zone = executor.plugin.getSelectedZone(sender); if (zone == null) { sender.sendMessage("[InvisibleWalls] Please select an zone first. (Use: /iw select <zoneId>)"); return; } StringBuilder str = new StringBuilder(); for (String s : names) { if (!s.startsWith("g:")) { if (zone.addPlayer(s)) str.append(s).append(','); } else { if (zone.addGroup(s.substring(2))) str.append(s).append(','); } } if (str.length() > 0) str.setLength(str.length()-1); executor.plugin.save(); sender.sendMessage("[InvisibleWalls] Added: " + str.toString()); }
6
@Override public int compareTo(VectorTimeStamp ts) { boolean beforeFlag = false; boolean afterFlag = false; // For vector time stamp, we need to compare corresponding value one by one for(Entry<String, AtomicInteger> e : localTS.entrySet()) { int local = e.getValue().get(); int remote = ts.getTimeStamp().get(e.getKey()).get(); if(local < remote) { beforeFlag = true; } else if(local > remote){ afterFlag = true; } } if(beforeFlag == true && afterFlag == false) { return -1; } else if(beforeFlag == false && afterFlag == true) { return 1; } else { return 0; } }
7
private synchronized void receiveAd(Sim_event ev) { if (super.reportWriter_ != null) { super.write("receive router ad from, " + GridSim.getEntityName(ev.get_src()) ); } // what to do when an ad is received FloodAdPack ad = (FloodAdPack)ev.get_data(); // prevent count-to-infinity if (ad.getHopCount() > Router.MAX_HOP_COUNT) { return; } String sender = ad.getSender(); Iterator it = ad.getHosts().iterator(); while ( it.hasNext() ) { String host = (String) it.next(); if ( host.equals(super.get_name()) ) { continue; } if (hostTable.containsValue(host)) { // direct connection continue; } if (forwardTable.containsKey(host)) { Object[] data = (Object[])forwardTable.get(host); int hop = ((Integer)data[1]).intValue(); if ((hop) > ad.getHopCount()) { Object[] toPut = { sender, new Integer(ad.getHopCount()) }; forwardTable.put(host, toPut); } } else { Object[] toPut = { sender, new Integer(ad.getHopCount()) }; forwardTable.put(host, toPut); } } forwardAd(ad); }
7
public List<Object> getContent() { if (content == null) { content = new ArrayList<Object>(); } return this.content; }
1
private boolean conditionL0(String value, int index) { if (index == value.length() - 3 && contains(value, index - 1, 4, "ILLO", "ILLA", "ALLE")) { return true; } else if ((contains(value, index - 1, 2, "AS", "OS") || contains(value, value.length() - 1, 1, "A", "O")) && contains(value, index - 1, 4, "ALLE")) { return true; } else { return false; } }
5
public void undo() { if (prevSpeed == CeilingFan.HIGH) { ceilingFan.high(); } if (prevSpeed == CeilingFan.MEDIUM) { ceilingFan.medium(); } if (prevSpeed == CeilingFan.LOW) { ceilingFan.low(); } if (prevSpeed == CeilingFan.OFF) { ceilingFan.off(); } }
4