text
stringlengths
14
410k
label
int32
0
9
public void loadCharacters(Element docEle){ NodeList charactersList = docEle.getElementsByTagName("Characters"); Node charactersNode = charactersList.item(0); Element characterElement = (Element)charactersNode; String charactersPath = characterElement.getAttribute("FolderPath"); String characterPrefix = characterElement.getAttribute("Prefix"); NodeList nList = charactersNode.getChildNodes(); for(int i = 0; i < nList.getLength(); i++){ Node node = nList.item(i); if(node.getNodeType() == Node.ELEMENT_NODE){ Element ele = (Element) node; String name = node.getNodeName(); String id = ele.getAttribute("ID"); String path = charactersPath+ele.getAttribute("Path"); String description = ele.getAttribute("Description"); if(!graphics.containsKey(path)) graphics.put(path, Utilities.loadImage(path)); BufferedImage image = graphics.get(path); NodeList animationsList = ele.getElementsByTagName("Animations"); node = animationsList.item(0); NodeList nAnimationList = node.getChildNodes(); List <Rect2i> animationBoxes = new ArrayList<Rect2i>(); for(int a = 0; a<nAnimationList.getLength();a++){ Node animationNode = nAnimationList.item(a); if(animationNode.getNodeType() == Node.ELEMENT_NODE){ Element animation = (Element)animationNode; animationBoxes.add(new Rect2i(Integer.parseInt(animation.getAttribute("x")),Integer.parseInt(animation.getAttribute("y")), Integer.parseInt(animation.getAttribute("w")),Integer.parseInt(animation.getAttribute("h")))); } } Rect2i[] boxes = new Rect2i[animationBoxes.size()]; for(int b = 0; b < animationBoxes.size(); b++){ boxes[b] = animationBoxes.get(b); } new Entity(characterPrefix+id, image, boxes, name, description); } } }
6
public void calcTangents() { for(int i = 0; i < indices.size(); i += 3) { int i0 = indices.get(i); int i1 = indices.get(i + 1); int i2 = indices.get(i + 2); Vector3f edge1 = positions.get(i1).sub(positions.get(i0)); Vector3f edge2 = positions.get(i2).sub(positions.get(i0)); float deltaU1 = texCoords.get(i1).getX() - texCoords.get(i0).getX(); float deltaV1 = texCoords.get(i1).getY() - texCoords.get(i0).getY(); float deltaU2 = texCoords.get(i2).getX() - texCoords.get(i0).getX(); float deltaV2 = texCoords.get(i2).getY() - texCoords.get(i0).getY(); float fDividend = (deltaU1 *deltaV2 - deltaU2 * deltaV1); float f = fDividend == 0 ? 0.1f : 1.0f/fDividend; Vector3f tangent = new Vector3f(0,0,0); tangent.setX(f * (deltaV2 * edge1.getX() - deltaV1 * edge2.getX())); tangent.setY(f * (deltaV2 * edge1.getY() - deltaV1 * edge2.getY())); tangent.setZ(f * (deltaV2 * edge1.getZ() - deltaV1 * edge2.getZ())); tangents.get(i0).set(tangents.get(i0).add(tangent)); tangents.get(i1).set(tangents.get(i1).add(tangent)); tangents.get(i2).set(tangents.get(i2).add(tangent)); } for(int i = 0; i < tangents.size(); i++) tangents.get(i).set(tangents.get(i).normalized()); }
3
public void battle(Team other) { for (int i = 0; i < Math.max(this.team.length, other.team.length); i++) { if (this.team[i] != null) { int j = (int)Math.round(((Math.random() + i - 1) * 3)); while(j < 0 || j > team.length - 1) { j = (int)Math.round(((Math.random() + i - 1) * 3)); } this.team[i].compare(other.team[j]); } } }
4
public String showBorad() //trying to make it look decent { StringBuffer s = new StringBuffer(); int j = 0; // String white = "\u25CB", black = "\u25CF", empty = "\u2212"; String white = "W", black = "B", empty = "-"; s.append("\n"); s.append(" | | | | | | | | | \n"); //i was using \r\n after each row but over HTTP in mac the \r prints as a &#13 so removed it here for(int i = -1; i < 8; i++) { if(i == -1) { s.append(" | "); } else { s.append(i+" | "); } } s.append("\n"); s.append("___|_____|_____|_____|_____|_____|_____|_____|_____|___\n"); s.append(" | | | | | | | | | \n"); for (int[] row : board) { s.append(j+" | "); for (int value : row) { if(value == B) { s.append(black+" | "); } else if (value == W) { s.append(white+" | "); } else s.append(" | "); } s.append("\n"); s.append("___|_____|_____|_____|_____|_____|_____|_____|_____|___\n"); s.append(" | | | | | | | | | \n"); j++; } return s.toString(); }
6
private void updatePalettes() { if (paletteType == PPUConstants.IMAGE_PALETTE_TYPE) { for (int i = 0; i < backgroundPalette.length; i++) { backgroundPalette[i] = (byte) EnvironmentUtilities.getIntegerEnvSetting(IMAGE_HELPER_BG_PALETTE_INDEX + i, DEFAULT_IMAGE_HELPER_BG_PALETTE); } for (int i = 0; i < spritePalette.length; i++) { if (i % 4 == 0) { spritePalette[i] = backgroundPalette[i]; } else { spritePalette[i] = (byte) EnvironmentUtilities.getIntegerEnvSetting(IMAGE_HELPER_SPR_PALETTE_INDEX + i, DEFAULT_IMAGE_HELPER_SPR_PALETTE); } } } else { // give priority to the saved sprite palette for index 0 for (int i = 0; i < spritePalette.length; i++) { spritePalette[i] = (byte) EnvironmentUtilities.getIntegerEnvSetting(IMAGE_HELPER_SPR_PALETTE_INDEX + i, DEFAULT_IMAGE_HELPER_SPR_PALETTE); } for (int i = 0; i < backgroundPalette.length; i++) { if (i % 4 == 0) { backgroundPalette[i] = spritePalette[i]; } else { backgroundPalette[i] = (byte) EnvironmentUtilities.getIntegerEnvSetting(IMAGE_HELPER_BG_PALETTE_INDEX + i, DEFAULT_IMAGE_HELPER_BG_PALETTE); } } } if (palettePanel != null) { palettePanel.setVisibleSpritePaletteSize(spritePaletteSize, false); palettePanel.setVisibleImagePaletteSize(backgroundPaletteSize, false); palettePanel.resetPalette(); resetDimensions(); } }
8
private void disassociateAC(ComponentEntry ac) { System.out.println("No KEEP_ALIVE received from "+ac.id+", assuming dead..."); this.accessControllers.remove(ac.id); AccessAssociation aa = findAssociation(ac.id); if (aa != null) { this.accessAssociations.remove(aa); if (!associateAccessPoint(aa.accessPoint)) { if (findAssociation(aa.accessPoint.id) == null) { aa.accessPoint.associated = false; System.out.println("Dissassociating "+aa.accessPoint.id); Message msg = new Message(Message.Type.DISASSOCIATE, aa.accessPoint.id, Message.MANAGER); hydnaSvc.sendMessage(Serializer.serialize(msg)); } } } }
3
public static final int task7(int nthPrime) { int prime = 2; int number = 3; while (prime < nthPrime) { number += 2; if (isPrime(number)) { prime++; } } return number; }
2
@Test public void PelaajanAlkusijaintiKunOnKerrottu() { ArrayList<String> rivit = new ArrayList(); rivit.add("P 20 20"); TasonLuonti tl = new TasonLuonti(rivit); Taso ta = tl.getTaso(); assertTrue("Pelaajan alkusijainti oli väärä" + ta.getPelaajanAlkusijainti().toString(), ta.getPelaajanAlkusijainti().getX() == 20 && ta.getPelaajanAlkusijainti().getY() == 20); }
1
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Vendor)) { return false; } Vendor other = (Vendor) object; if ((this.vendorID == null && other.vendorID != null) || (this.vendorID != null && !this.vendorID.equals(other.vendorID))) { return false; } return true; }
5
public void reorderList(ListNode head) { // deal with the trivial case when head is null if ( head == null || head.next == null ) { return; } // 1. find the first element that should moved forward ListNode p = findMover(head); Stack<ListNode> s = new Stack<>(); while ( p != null ){ s.push( p ); p = p.next; } // 2. do recursion ListNode iter = head; while ( !s.isEmpty() ) { ListNode n = s.pop(); n.next = iter.next; iter.next = n; iter = iter.next.next; } }
4
public static void main(String args[]) { /* * Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* * If Nimbus (introduced in Java SE 6) is not available, stay with the * default look and feel. For details see * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { GUI temp = new GUI(); temp.setVisible(true); } }); }
6
public ConfigurationSerializable deserialize(Map<String, Object> args) { Preconditions.checkNotNull(args, "Args must not be null"); ConfigurationSerializable result = null; Method method = null; if (result == null) { method = getMethod("deserialize", true); if (method != null) { result = deserializeViaMethod(method, args); } } if (result == null) { method = getMethod("valueOf", true); if (method != null) { result = deserializeViaMethod(method, args); } } if (result == null) { Constructor<? extends ConfigurationSerializable> constructor = getConstructor(); if (constructor != null) { result = deserializeViaCtor(constructor, args); } } return result; }
7
private boolean cmdSet(CommandSender sender, String world, String[] data, int offset, boolean oneRadius) { int radiusX, radiusZ; double x, z; try { radiusX = Integer.parseInt(data[offset]); if (oneRadius) { radiusZ = radiusX; offset -= 1; } else radiusZ = Integer.parseInt(data[offset + 1]); x = Double.parseDouble(data[offset + 2]); z = Double.parseDouble(data[offset + 3]); } catch (NumberFormatException ex) { sender.sendMessage(clrErr + "The radius value(s) must be integers and the x and z values must be numerical."); return false; } Config.setBorder(world, radiusX, radiusZ, x, z); return true; }
2
public static boolean validCod(String cod){ if(cod.length()<5 || cod.length()>20){ return false; }else{ return true; } }
2
public ArrayList<Node> calculatePath(Node p_Start, Node p_Goal) { ArrayList<Node> nodes = new ArrayList<>(); boolean done = false; Node temp = p_Goal; while(!done) { //always add the new node at the beginning of the list nodes.add(0,temp); //get the previous node from the temp. temp = temp.previous; //if the temp is equal to the start node then the path is recreated. if(temp == p_Start) done = true; } return nodes; }
2
@Override public Matrix add(Matrix matrix) throws IllegalArgumentException { int rows = this.getRowsNumber(); int cols = this.getColumnsNumber(); if (matrix.getRowsNumber() != rows || matrix.getColumnsNumber() != cols) { throw new IllegalArgumentException("Macierze o różnych rozmiarach"); } try { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { _values[i][j] += matrix.getElementAt(i+1, j+1); } } } catch (OutOfBoundsException e) { // Well, tutaj ten exception na pewno sie nie pojawi, // skoro sprawdzilem czy sa rownych rozmiarów te macierze e.printStackTrace(); } return this; }
5
public static void main(String[] args) throws Exception { DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option pathOpt = obuilder.withLongName("path").withRequired(true).withArgument( abuilder.withName("path").withMinimum(1).withMaximum(1).create()).withDescription( "The local file system path").withShortName("m").create(); Option classifyOpt = obuilder.withLongName("classify").withRequired(true).withArgument( abuilder.withName("classify").withMinimum(1).withMaximum(1).create()).withDescription( "The doc to classify").withShortName("").create(); Option encodingOpt = obuilder.withLongName("encoding").withRequired(true).withArgument( abuilder.withName("encoding").withMinimum(1).withMaximum(1).create()).withDescription( "The file encoding. Default: UTF-8").withShortName("e").create(); Option analyzerOpt = obuilder.withLongName("analyzer").withRequired(true).withArgument( abuilder.withName("analyzer").withMinimum(1).withMaximum(1).create()).withDescription( "The Analyzer to use").withShortName("a").create(); Option defaultCatOpt = obuilder.withLongName("defaultCat").withRequired(true).withArgument( abuilder.withName("defaultCat").withMinimum(1).withMaximum(1).create()).withDescription( "The default category").withShortName("d").create(); Option gramSizeOpt = obuilder.withLongName("gramSize").withRequired(true).withArgument( abuilder.withName("gramSize").withMinimum(1).withMaximum(1).create()).withDescription( "Size of the n-gram").withShortName("ng").create(); Option typeOpt = obuilder.withLongName("classifierType").withRequired(true).withArgument( abuilder.withName("classifierType").withMinimum(1).withMaximum(1).create()).withDescription( "Type of classifier").withShortName("type").create(); Option dataSourceOpt = obuilder.withLongName("dataSource").withRequired(true).withArgument( abuilder.withName("dataSource").withMinimum(1).withMaximum(1).create()).withDescription( "Location of model: hdfs").withShortName("source").create(); Group options = gbuilder.withName("Options").withOption(pathOpt).withOption(classifyOpt).withOption( encodingOpt).withOption(analyzerOpt).withOption(defaultCatOpt).withOption(gramSizeOpt).withOption( typeOpt).withOption(dataSourceOpt).create(); Parser parser = new Parser(); parser.setGroup(options); CommandLine cmdLine = parser.parse(args); int gramSize = 1; if (cmdLine.hasOption(gramSizeOpt)) { gramSize = Integer.parseInt((String) cmdLine.getValue(gramSizeOpt)); } BayesParameters params = new BayesParameters(); params.setGramSize(gramSize); String modelBasePath = (String) cmdLine.getValue(pathOpt); params.setBasePath(modelBasePath); log.info("Loading model from: {}", params.print()); Algorithm algorithm; Datastore datastore; String classifierType = (String) cmdLine.getValue(typeOpt); String dataSource = (String) cmdLine.getValue(dataSourceOpt); if ("hdfs".equals(dataSource)) { if ("bayes".equalsIgnoreCase(classifierType)) { log.info("Using Bayes Classifier"); algorithm = new BayesAlgorithm(); datastore = new InMemoryBayesDatastore(params); } else if ("cbayes".equalsIgnoreCase(classifierType)) { log.info("Using Complementary Bayes Classifier"); algorithm = new CBayesAlgorithm(); datastore = new InMemoryBayesDatastore(params); } else { throw new IllegalArgumentException("Unrecognized classifier type: " + classifierType); } } else { throw new IllegalArgumentException("Unrecognized dataSource type: " + dataSource); } ClassifierContext classifier = new ClassifierContext(algorithm, datastore); classifier.initialize(); String defaultCat = "unknown"; if (cmdLine.hasOption(defaultCatOpt)) { defaultCat = (String) cmdLine.getValue(defaultCatOpt); } File docPath = new File((String) cmdLine.getValue(classifyOpt)); String encoding = "UTF-8"; if (cmdLine.hasOption(encodingOpt)) { encoding = (String) cmdLine.getValue(encodingOpt); } Analyzer analyzer = null; if (cmdLine.hasOption(analyzerOpt)) { analyzer = ClassUtils.instantiateAs((String) cmdLine.getValue(analyzerOpt), Analyzer.class); } if (analyzer == null) { analyzer = new StandardAnalyzer(Version.LUCENE_31); } log.info("Converting input document to proper format"); String[] document = BayesFileFormatter.readerToDocument(analyzer,Files.newReader(docPath, Charset.forName(encoding))); StringBuilder line = new StringBuilder(); for (String token : document) { line.append(token).append(' '); } List<String> doc = new NGrams(line.toString(), gramSize).generateNGramsWithoutLabel(); log.info("Done converting"); log.info("Classifying document: {}", docPath); ClassifierResult category = classifier.classifyDocument(doc.toArray(new String[doc.size()]), defaultCat); log.info("Category for {} is {}", docPath, category); }
9
public GrammarTable getTable() { return table; }
0
public void updateDecorRenderList(World world) { decorationsToRender.clear(); for(Decoration decoration : world.getDecorList()) { Vector2f c = decoration.getCoords(); if((c.x >= (cLoc.x - (cameraWidth / 2) - decoration.getBB().getWidth()) || c.x <= (cLoc.x + (cameraWidth / 2) + decoration.getBB().getWidth())) || (c.y >= (cLoc.y - (cameraHeight / 2) - decoration.getBB().getHeight()) || c.y <= (cLoc.y + (cameraHeight / 2) + decoration.getBB().getHeight()))) { decorationsToRender.add(decoration); } } }
5
private static <E> void merge(E[] a, int from, int mid, int to, Comparator<? super E> comp) { int n = to - from + 1; Object[] values = new Object[n]; int fromValue = from; int middleValue = mid + 1; int index = 0; while (fromValue <= mid && middleValue <= to) { if (comp.compare(a[fromValue], a[middleValue]) < 0) { values[index] = a[fromValue]; fromValue++; } else { values[index] = a[middleValue]; middleValue++; } index++; } while (fromValue <= mid) { values[index] = a[fromValue]; fromValue++; index++; } while (middleValue <= to) { values[index] = a[middleValue]; middleValue++; index++; } for (index = 0; index < n; index++) a[from + index] = (E) values[index]; }
7
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((attributes == null) ? 0 : attributes.hashCode()); result = prime * result + (hasClosingTag ? 1231 : 1237); result = prime * result + (hasOpeningTag ? 1231 : 1237); result = prime * result + (isClosing ? 1231 : 1237); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((reporter == null) ? 0 : reporter.hashCode()); result = prime * result + (selfClosing ? 1231 : 1237); result = prime * result + ((location == null) ? 0 : location.hashCode()); return result; }
8
@Override public void mouseClick(int X, int Y) { if(this.getMouseListener() != null) { this.getMouseListener().MouseClick(this); } }
1
private void deopPlayers() { User[] users = bot.getUsers(gameChan); for (User user : users) { String nick = user.getNick(); if (user.isOp() && players2.isPlaying(nick)) { bot.sendMessage("ChanServ", "deop " + gameChan + " " + nick); } } }
3
@Override public void applyRenewPolicy(LibraryModel model, List<LibraryView> views, List<Copy> toRenew, String borrowerID) { List<Copy> reservedCopies = new LinkedList<Copy>(); List<Copy> toRemove = new LinkedList<Copy>(); for (Copy copy : toRenew) { Item item = model.findItem(copy.getRelatedItemID()); List<Reservation> sortedReservations = getReservationsOfItem(model, item.getID()); Collections.sort(sortedReservations); if (sortedReservations.size() > 0 || copy.isRecalled()) { /* * In case that there are reservations or the copy is recalled, * check... */ if (sortedReservations.size() <= countOfFreeCopiesOfItem(model, copy.getRelatedItemID())) { /* * ...if there are more free copies than reservations remove * any outstanding reservation of this borrower that is not * the first. */ for (Reservation reservation : sortedReservations) { if (reservation.getIssuerID().equals(borrowerID)) { model.removeReservation(reservation.getId()); } } copy.setRecalled(false); model.updateCopy(copy); } else { /* * ...or remove the copy from the items to issue and tell * the borrower that there are not enough copies. */ toRemove.add(copy); reservedCopies.add(copy); } } } for (Copy copy : toRemove) { toRenew.remove(copy); } if (reservedCopies.size() > 0) { viewsShowErrorMessage(views, "Issue Item", "The following items have been reserved and therefore removed from the list: " + getStringOfCopies(model, reservedCopies)); } }
8
@Override public String getUserServicePrice(String seller, String serviceName) { String priceValue = "0"; Service service = new Service(); Call call; try { call = (Call)service.createCall(); Object[] inParams = new Object[]{seller, serviceName}; call.setTargetEndpointAddress(new URL(SERVICES_URL)); call.setTargetEndpointAddress(SERVICES_URL); call.setOperationName(new QName(GET_PRICE)); call.setProperty(Call.ENCODINGSTYLE_URI_PROPERTY, ""); call.addParameter("seller", string, String.class, ParameterMode.IN); call.addParameter("serviceName", string, String.class, ParameterMode.IN); call.setReturnClass(String.class); priceValue = (String)call.invoke(inParams); } catch (ServiceException e) { System.out.println("Error calling user service price"); e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } return priceValue; }
3
@SuppressWarnings("unchecked") public synchronized static <T> int indexOf(T array[], T search) { if (array == null || array.length == 0) { return -1; } if (search == null) { for (int i = 0; i < array.length; ++i) { if (array[i] == null) { return i; } } } else { for (int i = 0; i < array.length; ++i) { if (array[i] != null && search.equals(array[i])) { return i; } } } return -1; }
8
private static void processFile(String filename, double dt) { try { System.err.println("Loading file " + filename + " ..."); JPLEphemeris ephemeris = new JPLEphemeris(filename); NeptuneBarycentricElements runner = new NeptuneBarycentricElements(ephemeris, dt); runner.run(); } catch (JPLEphemerisException jee) { jee.printStackTrace(); System.err.println("JPLEphemerisException ... " + jee); System.exit(1); } catch (IOException ioe) { ioe.printStackTrace(); System.err.println("IOException ... " + ioe); System.exit(1); } }
2
@Override public boolean importGroup27ReadingCO(JSONObject toImport, String device_serial, String product_id) throws Exception { String latitude = __jdbcProperties.getProperty("sql.latitude"); String longitude = __jdbcProperties.getProperty("sql.longitude"); String method = __jdbcProperties.getProperty("sql.method"); String deviceid = device_serial + "_co"; String current_value = (String)toImport.get("current_value"); String max_value = (String)toImport.get("max_value"); String min_value = (String)toImport.get("min_value"); int currentdata = parsevalue(current_value); int maxdata = parsevalue(max_value); int mindata = parsevalue(min_value); String datetime = (String) toImport.get("at");//2014-04-29T03:11:31.118995Z Calendar cal = DatatypeConverter.parseDateTime(datetime); Date d = cal.getTime(); String tags = null; JSONArray tagary = (JSONArray)toImport.get("tags"); for (int i = 0; i < tagary.size(); i++) { if (tags == null) tags = (String) tagary.get(i); else tags += ","+(String) tagary.get(i); } Connection c = null; PreparedStatement ps1 = null; PreparedStatement ps2 = null; boolean previousAC = true; if (toImport.isEmpty()) return false; try { c = _getConnection(); previousAC = c.getAutoCommit(); c.setAutoCommit(false); ps1 = c.prepareStatement(__jdbcProperties.getProperty("sql.importCommonReadings")); ps2 = c.prepareStatement(__jdbcProperties.getProperty("sql.importGroup27CoReadings")); ps1.setString(1, deviceid); ps1.setTimestamp(2, new java.sql.Timestamp(d.getTime()), AQMDAOFactory.AQM_CALENDAR); ps1.setDouble(3, Double.parseDouble(latitude)); ps1.setDouble(4, Double.parseDouble(longitude)); ps1.setString(5, method); ps2.setString(1, product_id); ps2.setString(2, deviceid); ps2.setTimestamp(3, new java.sql.Timestamp(d.getTime()), AQMDAOFactory.AQM_CALENDAR); ps2.setInt(4, currentdata); ps2.setInt(5, maxdata); ps2.setInt(6, mindata); ps2.setString(7, tags); ps2.setString(8, (String) ((JSONObject)toImport.get("unit")).get("label")); ps2.setString(9, (String) ((JSONObject)toImport.get("unit")).get("symbol")); System.out.println("co 1"); ps1.executeUpdate(); ps1.clearParameters(); ps2.executeUpdate(); ps2.clearParameters(); c.commit(); System.out.println("co finish"); } catch (SQLException se) { se.printStackTrace(); throw new Exception(se); } catch (Throwable t) { t.printStackTrace(); throw new Exception(t); } finally { try { if (ps1 != null) ps1.close(); if (ps2 != null) ps2.close(); if (c != null) { c.rollback(); c.setAutoCommit(previousAC); c.close(); } } catch (SQLException se2) { se2.printStackTrace(); } } return true; }
9
public static void main(String[] args) { Enumeration<CommPortIdentifier> portList; CommPortIdentifier portId; String messageString = "Hello, world!\n"; SerialPort serialPort = null; OutputStream outputStream = null; portList = getPortIdentifiers(); while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { // if (portId.getName().equals("COM1")) { if (portId.getName().equals("/dev/term/a")) { try { serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000); } catch (PortInUseException e) { } try { outputStream = serialPort.getOutputStream(); } catch (IOException e) { } try { serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) { } try { outputStream.write(messageString.getBytes()); } catch (IOException e) { } } } } }
7
private boolean validateCoordinate(int i){ if(i <= 0 || i> model.getField().size){ view.onError("Не верное значение, значение должно быть от 1 до " + model.getField().size + " попробуйте еще раз"); return false; } return true; }
2
@Override public void removeEdgesTo(N to) { if(containsNode(to)) { for(N node : nodes.keySet()) { List<Edge<N>> edgesFrom = edgesFrom(node); for(Edge<N> edge : edgesFrom) { if(edge.to.equals(to)) { nodes.get(node).remove(edge); } } } } }
4
@Test public void testTruncate() { String s = "My really long string that needs to be cut down to size."; Assert.assertEquals( "My really long string that needs to be cut down…", _helper.truncate(s, 50) ); }
0
@Override public void actionPerformed(ActionEvent e) { JButton augmenter = (JButton) e.getSource(); System.out.println("Augmenter vitesse"); new Thread(new Runnable() { public void run() { try { Main.service.augmenterVitesse(bus); } catch (IOException e) { e.printStackTrace(); } } }).start(); }
1
@Override public void run() { Thread me = Thread.currentThread(); String item = (String) (cb.getSelectedItem()); int current_index = item2index(item); while (true) { item = (String) (cb.getItemAt(current_index)); cb.setSelectedIndex(current_index); bitStream = selectSource(item); if (bitStream != null) { if (udp_port != -1) { play_udp_stream(me); } else { play_stream(me); } } else if (cb.getItemCount() == 1) { break; } if (player != me) { break; } bitStream = null; current_index++; if (current_index >= cb.getItemCount()) { current_index = 0; } if (cb.getItemCount() <= 0) { break; } } player = null; start_button.setText("start"); }
7
private void executeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_executeButtonActionPerformed String input = inputTextField.getText(); if (state == 0) { if (input.equals("open door")) { feedbackLabel.setText("You open the door."); storyLabel.setText("You enter the dining room."); state+=1; } else if (input.equals("look around")) { feedbackLabel.setText("As you look around you spot a teapot sitting atop a fireplace."); } else if (input.equals("pick up teapot")) { feedbackLabel.setText("You pick up the teapot."); inventory.add("teapot"); } } }//GEN-LAST:event_executeButtonActionPerformed
4
public void SmithWaterman() { int x,y; matrix[0][0]=0; //System.out.println(matrix.length + ":" + matrix[1].length); for(x=1;x<matrix[0].length;x++) { matrix[0][x]= Math.max(matrix[0][x-1] +effort[0], 0); } for(y=1;y<matrix.length;y++) { matrix[y][0]= Math.max(matrix[y-1][0] +effort[1], 0); } //Berechnung des inneren for(y=1;y<matrix.length;y++) { for(x=1;x<matrix[y].length;x++) { matrix[y][x]= calc(y,x); //Berechne Wert für stelle matrix[y][x]); } } }
4
public String weekTo(String field) { String newField = " TO "; if(field.length() == 3) { if(field.equals("SUN") || field.equals("MON") || field.equals("TUE") || field.equals("WED") || field.equals("THU") || field.equals("FRI") || field.equals("SAT")) { newField = newField + String.valueOf(getWeek(field)); } } else { newField = "~invalid~"; } return newField; }
8
public static int menu () { Scanner kb = new Scanner(System.in); int cho = 0; do { System.out.println ("\n\n[*] Menu:\n"); System.out.println ("1) Conta esemplari totali"); System.out.println ("2) Calcola valore totale della raccolta"); System.out.println ("3) Cerca e visualizza il tipo francobollo di maggior valore"); System.out.println ("4) Visualizza la nazione di cui si hanno piu' francobolli"); System.out.println ("5) Exit"); System.out.println ("\nChoice: "); cho = kb.nextInt(); } while (cho != 1 && cho != 2 && cho != 3 && cho != 4 && cho != 5); return cho; }
5
public JPanel addNumberButtons(JTextField DispField){ final JTextField Field = DispField; JPanel ButtonPanel = new JPanel(); ButtonPanel.setLayout(new GridLayout(4, 3)); ButtonPanel.setPreferredSize(new Dimension(500,320)); ButtonPanel.setMaximumSize(new Dimension(500,500)); JButton [] NumButtons = new JButton[10]; JButton StarButtons = new JButton("*"); StarButtons.setFont(NumButtonsFont); StarButtons.setPreferredSize(new Dimension(100,75)); StarButtons.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { if(Field.getText().length()<MaxChars) Field.setText(Field.getText()+"*"); if(!MainFrame.RedirectPanel.isVisible()) CallButton.setEnabled(true); } }); JButton latticeButtons = new JButton("#"); latticeButtons.setFont(NumButtonsFont); latticeButtons.setPreferredSize(new Dimension(100,75)); latticeButtons.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { if(Field.getText().length()<MaxChars) Field.setText(Field.getText()+"#"); if(!MainFrame.RedirectPanel.isVisible()) CallButton.setEnabled(true); } }); for (int i=0; i<10; i++){ final String name=""+i; NumButtons[i]=new JButton(""+i); NumButtons[i].setFont(NumButtonsFont); NumButtons[i].setPreferredSize(new Dimension(100,75)); NumButtons[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { if(Field.getText().length()<MaxChars) Field.setText(Field.getText()+name); if(!MainFrame.RedirectPanel.isVisible()) CallButton.setEnabled(true); } }); } for (int i=1;i<=9;i++){ ButtonPanel.add(NumButtons[i]); } ButtonPanel.add(StarButtons); ButtonPanel.add(NumButtons[0]); ButtonPanel.add(latticeButtons); return ButtonPanel; }
8
private int[] parseBookingID(String bookingID) { int[] idArray = null; try { // exit if bookingID is empty if (bookingID == null || bookingID.length() == 0) { return null; } int MAX_ATTR = 2; // 2 members: resID_reservationID String[] list = bookingID.split("_"); if (list.length != MAX_ATTR) { return null; } // [0] = resID, [1] = reservID, [2] = trans ID, [3] = this entity ID idArray = new int[MAX_ID]; idArray[0] = Integer.parseInt(list[0]); // to get resID idArray[1] = Integer.parseInt(list[1]); // to get reservationID // if the resource id doesn't exist or there are more IDs if (GridSim.isResourceExist(idArray[0]) == false) { idArray = null; } } catch (Exception e) { idArray = null; System.out.println(super.get_name() + ": Error - Invalid booking ID of " + bookingID); } return idArray; }
5
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
protected AutomatonSimulator getSimulator(Automaton automaton) { return SimulatorFactory.getSimulator(automaton); }
0
public static void main(String args[]) { /* * Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* * If Nimbus (introduced in Java SE 6) is not available, stay with the * default look and feel. For details see * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ComSupErrorBank.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ComSupErrorBank.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ComSupErrorBank.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ComSupErrorBank.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 ComSupErrorBank().setVisible(true); } }); }
6
public List<ServerFile> getServerFiles() { List<ServerFile> files = new ArrayList<>(); if(dontScan) { return files; } ServerFile sf; File[] dirfiles; getServer().log("Parsing " + getDirectory().getParent() + "/" + getDirectory().getName()); dirs: for (File directory : getFiles()) { if (!directory.isDirectory()) { continue; // only dirs. } for (String ignore : ignores) { if (directory.getName().startsWith(ignore)) { continue dirs; } } dirfiles = directory.listFiles(); if (dirfiles == null) { // System Volume Information >.> continue; } for (File sub : dirfiles) { sf = new ServerFile(); sf.setServercategory(this); sf.setServer(getServer()); sf.setName(sub.getName()); sf.setDisplayname(sub.getName()); sf.setDirectory(directory.getName()); sf.setDisplaydirectory(directory.getName()); sf.setServerpath(sub.getPath()); sf.setFlag(ServerFile.CREATED); sf.setPath(""); sf.setCreated(); // TODO: this is slow, find a better way. // sf.setType(sub.isDirectory() ? "directory" : "file"); sf.setType("unknown"); // TODO: fill these. sf.setExtension(""); files.add(sf); } } return files; }
7
public Map<String, Mass> makeMassMap(){ Map<String, Mass> massMap = new HashMap<String, Mass>(); NodeList[] massArray = {movingMasses, fixedMasses}; for (NodeList massType: massArray){ for (int i = 0; i < massType.getLength(); i++) { Node node = massType.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; String id = element.getAttribute("id"); double x = Double.parseDouble(element.getAttribute("x")); double y = Double.parseDouble(element.getAttribute("x")); double vx = getVelocity(element, "vx"); double vy = getVelocity(element, "vy"); double m; if (element.getAttribute("mass").equals("")) m = 1.0; else m = Double.parseDouble(element.getAttribute("mass")); if (element.getNodeName().equals("mass")){ Mass moveableMass = new MoveableMass(id, 1, 5, x, y, vx, vy, m, mMassColor); massMap.put(id, moveableMass); } else{ Mass fixedMass = new FixedMass(id, 0, 5, x, y, 1, fMassColor); massMap.put(id, fixedMass); } } } } return massMap; }
5
public Recipe getRecipeForPallet(Pallet pallet) { String sql = "Select quantity, rawMaterialName, recipeName "+ "from Ingredients "+ "where Ingredients.recipeName like ? "; PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); ps.setString(1, pallet.recipeName); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } Recipe rtn = null; try { ResultSet rs = ps.executeQuery(); while (rs.next()) { if (rtn == null) { rtn = new Recipe(rs.getString("recipeName"), new ArrayList<Ingredient>()); } rtn.ingredients.add(new Ingredient(rs.getInt("quantity"),new RawMaterial(rs.getString("rawMaterialName")))); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { if(ps != null) try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return rtn; }
6
public void update(long currentTime) { if (isFinished) { return; } progress = (double)(currentTime - iT)/period; if (progress >= 1) { if (loop) { start(currentTime); return; } progress = 1; isFinished = true; for (AnimationListener listener : listeners) { listener.animationFinished(this); } } updateAnimation(pace(progress, paceType)); }
4
@Before public void setUp(){ for(int i = 0; i < 20; i++){ solutions.put(i,(double) i); } classUnderTest.setSolutionFitness(solutions); }
1
private void doSave() { fileDialog = new JFileChooser(currentDirectory); File selectedFile; //Initially selected file name in the dialog. if (editFile == null) selectedFile = new File("filename.txt"); else selectedFile = new File(editFile.getName()); fileDialog.setSelectedFile(selectedFile); fileDialog.setDialogTitle("Select File to be Saved"); int option = fileDialog.showSaveDialog(this); if (option != JFileChooser.APPROVE_OPTION) return; // User canceled or clicked the dialog's close box. selectedFile = fileDialog.getSelectedFile(); if (selectedFile.exists()) { // Ask the user whether to replace the file. int response = JOptionPane.showConfirmDialog( this, "The file \"" + selectedFile.getName() + "\" already exists.\nDo you want to replace it?", "Confirm Save", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE ); if (response != JOptionPane.YES_OPTION) return; // User does not want to replace the file. } PrintWriter out; try { FileWriter stream = new FileWriter(selectedFile); out = new PrintWriter( stream ); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Sorry, but an error occurred while trying to open the file:\n" + e); return; } try { out.print(text.getText()); // Write text from the TextArea to the file. out.close(); if (out.checkError()) // (need to check for errors in PrintWriter) throw new IOException("Error check failed."); editFile = selectedFile; setTitle("TrivialEdit: " + editFile.getName()); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Sorry, but an error occurred while trying to write the text:\n" + e); } }
7
private void listenClient(String clientRequest) throws NullPointerException { String[] reqSplit = clientRequest.split("-"); if (reqSplit[0].equals("LOGOUT") && reqSplit.length == 2) { processor.getMessageQ().add(this, clientRequest); } else if (reqSplit[0].equals("LOGIN") && reqSplit.length == 3) { processor.getMessageQ().add(this, clientRequest); } else if (reqSplit[0].equals("REG") && reqSplit.length == 3) { processor.getMessageQ().add(this, clientRequest); } else { responClient("\"" + clientRequest + "\"" + " IS NOT RECOGNIZE."); } }
6
Xpp3Dom getResults() { return getInTestLinkListener().getResults(); }
0
public RoleSchool removeRole(long id){ for(int i = 0; i < roles.size(); i++){ if(roles.get(i).getId() == id){ return roles.remove(i); } } return null; }
2
public String getMiasto() { return miasto; }
0
public static void call(final String mapping, final String data) throws Exception { // delimited by a comma // text qualified by double quotes // ignore first record OrderBy orderby = null; final Parser pzparser = DefaultParserFactory.getInstance().newDelimitedParser(new File(mapping), new File(data), ',', '"', true); final DataSet ds = pzparser.parse(); // re order the data set by last name orderby = new OrderBy(); orderby.addOrderColumn(new OrderColumn("CITY", false)); orderby.addOrderColumn(new OrderColumn("LASTNAME", true)); // ds.orderRows(orderby); final String[] colNames = ds.getColumns(); while (ds.next()) { if (ds.isRecordID("header")) { System.out.println(">>>>found header"); System.out.println("COLUMN NAME: INDICATOR VALUE: " + ds.getString("RECORDINDICATOR")); System.out.println("COLUMN NAME: HEADERDATA VALUE: " + ds.getString("HEADERDATA")); System.out.println("==========================================================================="); continue; } if (ds.isRecordID("trailer")) { System.out.println(">>>>found trailer"); System.out.println("COLUMN NAME: INDICATOR VALUE: " + ds.getString("RECORDINDICATOR")); System.out.println("COLUMN NAME: TRAILERDATA VALUE: " + ds.getString("TRAILERDATA")); System.out.println("==========================================================================="); continue; } for (final String colName : colNames) { System.out.println("COLUMN NAME: " + colName + " VALUE: " + ds.getString(colName)); } System.out.println("==========================================================================="); } if (ds.getErrors() != null && !ds.getErrors().isEmpty()) { System.out.println("<<<<FOUND ERRORS IN FILE>>>>"); final Iterator pzerrors = ds.getErrors().iterator(); while (pzerrors.hasNext()) { final DataError error = (DataError) pzerrors.next(); System.out.println("Error Msg: " + error.getErrorDesc() + " line no: " + error.getLineNo()); } } }
7
public void endElement(String uri, String localName, String qName) throws SAXException { int tag = getTagIndex(qName); if (inOneBoxResult) { doOneBoxResult(tag); } else if (inOneBoxResponse) { doOneBoxResponse(tag); } else if (inResult) { doResult(tag); } else if(inNavigationResult){ doNavigationResult(tag); } else if(inNavigationResponse){ doNavigationResponse(tag); } else if (inResponse) { doResponse(tag); } else if (inSpelling) { doSpelling(tag); } else if (inSynonyms) { doSynonym(tag); } else if (inKeymatchResults) { doKeymatch(tag); } else { // in <GSP> doTopLevel(tag); } }
9
public static void main(String[] args) { // insert a bunch of strings String[] strings = { "it", "was", "the", "best", "of", "times", "it", "was", "the", "worst" }; IndexMaxPQ<String> pq = new IndexMaxPQ<String>(strings.length); for (int i = 0; i < strings.length; i++) { pq.insert(i, strings[i]); } // print each key using the iterator for (int i : pq) { StdOut.println(i + " " + strings[i]); } StdOut.println(); // increase or decrease the key for (int i = 0; i < strings.length; i++) { if (StdRandom.uniform() < 0.5) pq.increaseKey(i, strings[i] + strings[i]); else pq.decreaseKey(i, strings[i].substring(0, 1)); } // delete and print each key while (!pq.isEmpty()) { String key = pq.maxKey(); int i = pq.delMax(); StdOut.println(i + " " + key); } StdOut.println(); // reinsert the same strings for (int i = 0; i < strings.length; i++) { pq.insert(i, strings[i]); } // delete them in random order int[] perm = new int[strings.length]; for (int i = 0; i < strings.length; i++) perm[i] = i; StdRandom.shuffle(perm); for (int i = 0; i < perm.length; i++) { String key = pq.keyOf(perm[i]); pq.delete(perm[i]); StdOut.println(perm[i] + " " + key); } }
8
private int extractSlot(byte[] schedule, int slot) { // since 8 is divisible by bitsPerSlot, we know that // one slot will never span more than one byte. // relevant byte: byte b = schedule[(slot * bitsPerSlot) / 8]; int startBit = (slot * bitsPerSlot) % 8; b >>= startBit; b &= (1 << bitsPerSlot) - 1; return (int) b; }
0
@Override public void keyTyped(KeyEvent e) { if(e.getKeyChar() == this.editor.getCommandChar()) { this.view.getCommand().setVisible(true); this.view.getCommand().setText(this.editor.getCommandChar()+""); this.view.getCommand().requestFocusInWindow(); } else switch (e.getKeyChar()) { case '\u0008': case '\u007F': break; case '\n': this.editor.newLine(); break; default: this.editor.insertChar(e.getKeyChar()); } view.getDocument().setText(this.editor.print()); }
4
private Raum[][] erzeugeRaumArray(List<Raum> raumListe, List<XmlRaum> raumPositionen) { Raum[][] result = new Raum[getMaximumX(raumListe) + 1][getMaximumY(raumListe) + 1]; for(Raum raum : raumListe) { for(XmlRaum xmlraum : raumPositionen) { if(xmlraum.getID() == raum.getId()) { result[raum.getX()][raum.getY()] = raum; break; } } } return result; }
3
void run() { if (fileToProcess != null) { File resultFile = new File(fileToProcess); if (!resultFile.exists() || resultFile.isDirectory()) { LOG.error("{} is not a good result file", fileToProcess); return; } try { LoadFile loadFile = new LoadFile(resultFile); loadFile.load(); } catch (Throwable e) { LOG.error("Exception Caught", e); } } }
4
public InvertedFileIterator(int entryPar,String indexDirectory,int lexiconSizePar, InvertedFile invFile){ synchronized(this){ entry=entryPar; lexiconSize=lexiconSizePar; try{ File pl_f=new File(indexDirectory+"/invfile/pl_e"+entry+"_sorted.dat"); if(pl_f.exists()) { if(postingListFile==null){ // System.out.println("Opening posting list "+entry); postingListFile=new RandomAccessFile(pl_f,"r"); } if(postingListIndex==null){ // System.out.println("Reading index of posting list "+entry); postingListIndex=new int[lexiconSize]; //positions range from 0 up to (including) the number of reference objects //Can we do the following by using MemoryMappedBuffers rather than random access files? postingListFile.seek(0); for(int s=0;s<postingListIndex.length;s++){ byte[] position_buff=new byte[4]; postingListFile.read(position_buff); int position=it.cnr.isti.SimilaritySearch.MI_File.Conversions.byteArrayToInt(position_buff); postingListIndex[s]=position; } } // System.out.println(fromScoreParam+" "+toScoreParam+" "+fromPos+" "+toPos); // pl=invFile[entry].getChannel().map(java.nio.channels.FileChannel.MapMode.READ_ONLY,fromPos,toPos-fromPos); if(postingListMemoryMapped==null){ postingListMemoryMapped=postingListFile.getChannel().map(java.nio.channels.FileChannel.MapMode.READ_ONLY,postingListIndex[0],postingListFile.length()-postingListIndex[0]); } } else{ currentPos=fromPos=toPos=0; } }catch(Exception e){ System.err.println("Cannot open posting list"); e.printStackTrace(); } } }
6
protected synchronized void onResized(int columns, int rows) { TerminalSize newSize = new TerminalSize(columns, rows); if(lastKnownSize == null || !lastKnownSize.equals(newSize)) { lastKnownSize = newSize; for(ResizeListener resizeListener: resizeListeners) resizeListener.onResized(lastKnownSize); } }
3
@Override public void actionPerformed(ActionEvent e) { visibleScreen.getFrame().getContentPane().removeAll(); boolean playerHadABang = false; if (visibleScreen.getSetup().getRound().playerInTurnIsNextToReactToDuello()) { playerHadABang = visibleScreen.getSetup().getRound().getCheckerForPlayedCard().searchPlayerHandForCertainCard(visibleScreen.getSetup().getRound().getPlayerInTurn(), "BANG!"); if (!playerHadABang && visibleScreen.getSetup().getRound().getPlayerInTurn().getAvatar().toString().equals("Calamity Janet")) { visibleScreen.getSetup().getRound().getCheckerForPlayedCard().searchPlayerHandForCertainCard(visibleScreen.getSetup().getRound().getPlayerInTurn(), "Mancato!"); } visibleScreen.getSetup().getRound().getDiscardpile().place(visibleScreen.getSetup().getRound().getPlayerInTurn().drawSpecificHandCardWithoutGivingReplacingOne(visibleScreen.getSetup().getRound().getCheckerForPlayedCard().getIndexOfReplyCard(), visibleScreen.getSetup().getRound())); visibleScreen.getSetup().getRound().setPlayerInTurnIsNextToReactToDuello(false); } else { playerHadABang = visibleScreen.getSetup().getRound().getCheckerForPlayedCard().searchPlayerHandForCertainCard(visibleScreen.getSetup().getRound().getPlayerToFollow(), "BANG!"); if (!playerHadABang && visibleScreen.getSetup().getRound().getPlayerToFollow().getAvatar().toString().equals("Calamity Janet")) { visibleScreen.getSetup().getRound().getCheckerForPlayedCard().searchPlayerHandForCertainCard(visibleScreen.getSetup().getRound().getPlayerToFollow(), "Mancato!"); } visibleScreen.getSetup().getRound().getDiscardpile().place(visibleScreen.getSetup().getRound().getPlayerToFollow().drawSpecificHandCard(visibleScreen.getSetup().getRound().getCheckerForPlayedCard().getIndexOfReplyCard(), visibleScreen.getSetup().getRound())); visibleScreen.getSetup().getRound().setPlayerInTurnIsNextToReactToDuello(true); } visibleScreen.duelloToOtherPlayerScreen(); visibleScreen.getFrame().revalidate(); visibleScreen.getFrame().repaint(); }
5
public void ship(String dest) { Contents c = contents(); Destination d = to(dest); System.out.println(d.readLabel()); }
0
@Override public void processEntity(Entity entity) { Spatial spatial = entity.getComponent(Spatial.class); /** * If the previous spatial was null, this is the first time it's been * through this PreviousSpatialSystem. We therefore create its new * Spatial. We couldn't do this within the Spatial class because it * would cause recursion. IE, doing Spatial() { previousSpatial = new * Spatial(); } would not be a good idea! * <p> * Our second test is, if it different to before we should update it, * and change the boolean flags to let any other system that cares about * the change. Possibly the rendering system and collision detection * system etc. * <p> * Our last else is simply to say there was no change, and we reset the * flags to false. */ if (spatial.previousSpatial == null) { spatial.previousSpatial = new Spatial(spatial.x, spatial.y, spatial.width, spatial.height, spatial.getRotation()); spatial.spatialChanged = true; spatial.previousSpatialWasNull = true; } else if (!spatial.equals(spatial.previousSpatial)) { spatial.previousSpatial.x = spatial.x; spatial.previousSpatial.y = spatial.y; spatial.previousSpatial.width = spatial.width; spatial.previousSpatial.height = spatial.height; spatial.previousSpatial.setRotation(spatial.getRotation()); spatial.spatialChanged = true; spatial.previousSpatialWasNull = false; } else { spatial.spatialChanged = false; spatial.previousSpatialWasNull = false; } }
2
@Test public void testTasks() { Task heute,invalid; try { //anpassen an aktuellen tag! heute=new Task(2012, 11, 16,"heute"); } catch (InvalidTaskException ex) { fail(ex.getMessage()); } invalid=null; try { invalid=new Task(2011, 11, 16,"invalid year"); fail("Task "+invalid+" should throw an InvalidTaskException!"); } catch (InvalidTaskException ex) { System.out.println(ex.getMessage()); } assertNull("invalid should be null!",invalid); invalid=null; try { invalid=new Task(2012, 13, 16,"invalid month"); fail("Task "+invalid+" should throw an InvalidTaskException!"); } catch (InvalidTaskException ex) { System.out.println(ex.getMessage()); } assertNull("invalid should be null!",invalid); invalid=null; try { invalid=new Task(2012, 0, 16,"invalid month"); fail("Task "+invalid+" should throw an InvalidTaskException!"); } catch (InvalidTaskException ex) { System.out.println(ex.getMessage()); } assertNull("invalid should be null!",invalid); invalid=null; try { //kein Schaltjahr invalid=new Task(2013, 2, 29,"invalid day (no leapyear)"); fail("Task "+invalid+" should throw an InvalidTaskException!"); } catch (InvalidTaskException ex) { System.out.println(ex.getMessage()); } assertNull("invalid should be null!",invalid); invalid=null; try { invalid=new Task(2012, 9, 31,"invalid day (too much days in a month)"); fail("Task "+invalid+" should throw an InvalidTaskException!"); } catch (InvalidTaskException ex) { System.out.println(ex.getMessage()); } assertNull("invalid should be null!",invalid); }
6
public E succ(E e) { DoublyLinkedNode node = search(e); if (node != null) { if (node.getSucc() != null) { final E returnValue = (E) node.getSucc().getKey(); return returnValue; } } return null; }
2
public Class<?> getColumnClass(int columnIndex) { switch (columnIndex) { case COL_HASH: case COL_TITLE: case COL_LINK: case COL_SOURCE: return String.class; case COL_SEED: case COL_LEECH: return Integer.class; default: return String.class; } }
7
public static boolean isAvailable(int port){ if (port < 0) { return false; } ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.setReuseAddress(true); //ServerSocket类中,默认值为false,该方法必须在绑定端口前使用才有效 ds = new DatagramSocket(port); ss.setReuseAddress(true); return true; } catch (IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { } } } return false; }
5
private boolean checkSetting() { if (DoArea.userNameField.getText().isEmpty()) return false; if (DoArea.passWordField.getText().isEmpty()) return false; if (DoArea.keyPathField.getText().isEmpty()) return false; if (DoArea.hostNameField.getText().isEmpty()) return false; if (DoArea.portNumberField.getText().isEmpty()) return false; if (DoArea.uploadPathField.getText().isEmpty()) return false; return true; }
6
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { if(!auto) return false; final Physical target=givenTarget; if(target==null) return false; if((target instanceof Item)&&(room==null)) return false; if(target.fetchEffect("Sinking")==null) { final Sinking F=new Sinking(); F.setMiscText(this.reversed()?"REVERSED":"NORMAL"); F.invoker=null; if(target instanceof MOB) F.invoker=(MOB)target; else F.invoker=CMClass.getMOB("StdMOB"); target.addEffect(F); F.setSavable(false); F.makeLongLasting(); if(!(target instanceof MOB)) CMLib.threads().startTickDown(F,Tickable.TICKID_MOB,1); target.recoverPhyStats(); } return true; }
8
boolean setLcLpPb(int lc, int lp, int pb) { if (lc > Base.kNumLitContextBitsMax || lp > 4 || pb > Base.kNumPosStatesBitsMax) { return false; } m_LiteralDecoder.create(lp, lc); int numPosStates = 1 << pb; m_LenDecoder.create(numPosStates); m_RepLenDecoder.create(numPosStates); m_PosStateMask = numPosStates - 1; return true; }
3
private void integrityCheck() { PurchasableCircularList next = nextGroupElement; int stations = 0; int owned = 0; do { stations++; next = next.getNextGroupElement(); } while(!next.equals(this)); next = this; do { if(next.getOwner() != null && next.getOwner().equals(owner)) { owned++; } next = next.getNextGroupElement(); } while(!next.equals(this)); if(owned >= (stations * 0.75)) { stage = 3; } else if(owned >= (stations * 0.5)) { stage = 2; } else if(owned >= (stations * 0.25)) { stage = 1; } else { stage = 0; } }
7
@Override public boolean canImport(TransferSupport support) { return (support.getComponent() instanceof JList) && support.isDataFlavorSupported(RiverComponent.RIVER_COMPONENT_DATA_FLAVOR); }
1
public List<Position> getClosestCarsInt() { //Returns closest car to intersection on each road List<Position> closest = new ArrayList<Position>(); ListIterator<Road> roadItr = this.roads.listIterator(); Position carPos = null; // For if we continue cars moving while (roadItr.hasNext()) { carPos = null; boolean exit = false; Road nextRoad = roadItr.next(); ListIterator<Car> carItr = nextRoad.getCars().listIterator(); while (carItr.hasNext() && !exit) { carPos = carItr.next().getPos(); if (nextRoad.getDirection() == Road.horizontal && carPos.getX() < this.getPos().getX()) { exit = true; } else if (nextRoad.getDirection() == Road.vertical && carPos.getY() < this.getPos().getY()) { exit = true; } } if (carPos == null) { carPos = this.pos; } closest.add(carPos); } return closest; }
8
@Override public void paint(Graphics2D g2d) { super.paint(g2d); if(municion <= MUNICION_PARA_RECARGAR) g2d.drawString("Reload! ("+movimientos.getRecargar().getNombreTecla()+")", x, y+6); if(salud<=5 && vidas>0) g2d.drawString("Reviviendo en "+salud, x, y-10); g2d.setColor(Color.WHITE); g2d.drawString(nombre, x, y+15); }
3
public void deleteFile(String fileName){ // deletion flag boolean flag = true; // Create an instance of File representing the named file File file0 = new File(fileName); // Check that the file exists if(!file0.exists()){ System.err.println("Method deleteFile: no file or directory of the name " + fileName + " found"); flag = false; } // Check whether FileName is write protected if(flag && !file0.canWrite()){ System.err.println("Method deleteFile: " + fileName + " is write protected and cannot be deleted"); flag = false; } // Check, if fileName is a directory, that it is empty if(flag && file0.isDirectory()){ String[] dirFiles = file0.list(); if (dirFiles.length > 0){ System.err.println("Method deleteFile: " + fileName + " is a directory which is not empty; no action was taken"); flag = false; } } // Delete file if(flag){ flag = file0.delete(); if(!flag)System.err.println("Method deleteFile: deletion of the temporary file " + fileName + " failed"); } }
8
private void checkHit() { int mapPosX = Main.getMapPosX(); int mapPosY = Main.getMapPosY(); int epsilon = 100; // Epsilon fuer Radius um Schwerts LinkedList<Mob> Mobs = AssetCreator.getMobs(); for (int i = 0; i < Mobs.size(); i++) { Mob mob = Mobs.get(i); if(!mob.isHit() && (x+epsilon-mapPosX > mob.getPositionX()+mob.getWidth()/2 && x-epsilon-mapPosX < mob.getPositionX()+mob.getWidth()/2) && (y+epsilon-mapPosY > mob.getPositionY()+mob.getHeight()/2 && y-epsilon-mapPosY < mob.getPositionY()+mob.getHeight()/2)){ mob.setHp((int)(mob.getHp()-damage)); mob.setHit(true); if (mob.getHp() < 0) { Mobs.remove(mob); } } } }
7
public void destroy() { bgComboBox.destroy(); ActionListener[] al = okButton.getActionListeners(); if (al != null) { for (ActionListener i : al) okButton.removeActionListener(i); } al = cancelButton.getActionListeners(); if (al != null) { for (ActionListener i : al) cancelButton.removeActionListener(i); } WindowListener[] wl = getWindowListeners(); if (wl != null) { for (WindowListener i : wl) removeWindowListener(i); } getContentPane().removeAll(); try { finalize(); } catch (Throwable t) { t.printStackTrace(System.err); } dispose(); bgComboBox = null; page = null; }
7
private void initCamera() { Transform3D projectionMatrix = new Transform3D(); double nearClipping = 0.1; double farClipping = 5.0; double[] intrinsics = new double[9]; try { System.out.println(UbitrackFacade.DATAFLOW_PATH+File.separator +"CamCalib-3-3-Matrix" ); FileReader fro = new FileReader(System.getProperty("user.dir") + File.separator + "dataflow" +File.separator +"CamCalib-3-3-Matrix" ); BufferedReader bro = new BufferedReader( fro ); // declare String variable and prime the read String stringRead = bro.readLine( ); while( stringRead != null ) // end of the file { StringTokenizer st = new StringTokenizer( stringRead, " " ); st.nextToken( ); st.nextToken( ); st.nextToken( ); st.nextToken( ); st.nextToken( ); st.nextToken( ); st.nextToken( ); st.nextToken( ); for (int i = 0; i < intrinsics.length; i++) { intrinsics[i] = Double.parseDouble(st.nextToken()); } stringRead = bro.readLine( ); // read next line } bro.close( ); } catch( FileNotFoundException filenotfoundexxption ) { System.out.println( "CamCalib-3-3-Matrix, does not exist" ); } catch( IOException ioexception ) { ioexception.printStackTrace( ); } double[] projectionArray = constructProjectionMatrix(intrinsics, nearClipping, farClipping); // for (int i = 0; i < projectionArray.length; i++) { // System.out.println(i + ":" + projectionArray[i]); // } projectionMatrix.set(projectionArray); universe.getViewer().getView().setCompatibilityModeEnable(true); universe.getViewer().getView().setLeftProjection(projectionMatrix); }
4
public void splitCodeAndComment(CodeMethod cm) { List<String> src = new LinkedList<String>(); List<String> comment = new LinkedList<String>(); boolean comment_mode = false; // multi-line comment mode String comment_mark = ""; StringBuilder sb = null; for (String sen : cm.body) { if (comment_mode) { if (sen.trim().endsWith(comment_mark)) { sb.append(sen.trim().substring(0, sen.trim().length() - 3)); comment.add(sb.toString()); comment_mode = false; } else { sb.append(sen.trim()); } } else { if (sen.trim().startsWith("\"\"\"") || sen.trim().startsWith("'''")) { comment_mode = true; comment_mark = sen.trim().substring(0, 3); sb = new StringBuilder(); sb.append(sen.trim().substring(3)); } else if (sen.trim().startsWith("#")) { comment.add(sen.trim().substring(1)); } else { String[] tmp = sen.split("#"); src.add(tmp[0]); if (tmp.length > 1) { comment.add(tmp[1]); } } } } cm.body = src; cm.comment = comment; }
7
@Override public void caseAFormallist(AFormallist node) { inAFormallist(node); { List<PFormalrest> copy = new ArrayList<PFormalrest>(node.getFormalrest()); Collections.reverse(copy); for(PFormalrest e : copy) { e.apply(this); } } if(node.getIdentifier() != null) { node.getIdentifier().apply(this); } if(node.getType() != null) { node.getType().apply(this); } outAFormallist(node); }
3
private void initiateParsing() { // http://tutorials.jenkov.com/java-xml/sax.html SAXParserFactory factory = SAXParserFactory.newInstance(); File file = new File("assets/OSM_MapOfDenmark.osm"); try { InputStream openStreetMapData = new FileInputStream(file); SAXParser saxParser = factory.newSAXParser(); saxParser.parse(openStreetMapData, this); isParsed = true; //Release Memory openStreetMapData.close(); saxParser.reset(); } catch (Throwable err) { err.printStackTrace(); } isParsed = false; tempRoadTypeList.clear(); file = new File("assets/OSM_PlaceNames.osm"); try { InputStream openStreetMapData = new FileInputStream(file); SAXParser saxParser = factory.newSAXParser(); saxParser.parse(openStreetMapData, this); isParsed = true; //Release Memory openStreetMapData.close(); saxParser.reset(); } catch (Throwable err) { err.printStackTrace(); } quadTree = new QuadTree(edges, minX, minY, Math.max(maxX - minX, maxY - minY)); }
2
private void initializeJob() { if (job == null) { job = new Job("3D Molecular Simulator #" + jobIndex++) { public void run() { while (true) { super.run(); while (!isStopped()) { modelTime += getTimeStep(); advance(indexOfStep++); execute(); } synchronized (this) { try { wait(); } catch (InterruptedException e) { // e.printStackTrace(); break; } } } } public void runScript(String script) { if (script != null) runTaskScript(script); } public void notifyChange() { MolecularModel.this.notifyChange(); } }; job.setInitTaskAction(new Runnable() { public void run() { getView().getActionMap().get("properties").actionPerformed(null); } }); } if (!recorderDisabled && !job.contains(movieUpdater)) job.add(movieUpdater); if (!job.contains(paintView)) job.add(paintView); }
8
public void makeBold() { if (this.isDisposed()) { return; } isBold = true; setFont(boldFont); }
1
private int getDepth() { Stack<TreeNode<E>> nodeStack = new Stack<TreeNode<E>>(); Stack<Integer> leftStack = new Stack<Integer>(); Stack<Integer> rightStack = new Stack<Integer>(); nodeStack.push(root); leftStack.push(-1); rightStack.push(-1); while (true) { TreeNode<E> t = nodeStack.peek(); int left = leftStack.peek(); int right = rightStack.peek(); if (t == null) { nodeStack.pop(); leftStack.pop(); rightStack.pop(); int value = 0; if (nodeStack.isEmpty()) return value; else if (leftStack.peek() == -1) { leftStack.pop(); leftStack.push(value); } else { rightStack.pop(); rightStack.push(value); } } else if (left == -1) { nodeStack.push(t.left); leftStack.push(-1); rightStack.push(-1); } else if (right == -1) { nodeStack.push(t.right); leftStack.push(-1); rightStack.push(-1); } else { nodeStack.pop(); leftStack.pop(); rightStack.pop(); int value = 1 + Math.max(left, right); if (nodeStack.isEmpty()) return value; else if (leftStack.peek() == -1) { leftStack.pop(); leftStack.push(value); } else { rightStack.pop(); rightStack.push(value); } } } }
8
private void receiveRegularMessage(Message m) { if(this.children.contains(m.broadcaster())) { if (this.parent == -1) { this.returnACK(m); } else { this.rebroadcast(m); } } else if (this.parent == m.broadcaster()) { if (m.Up()) { for (Message oldM: this.sentMessageDuration.keySet()) { if (oldM.id() == m.id()) { sentMessageDuration.remove(oldM); } } } else if (this.children.contains(m.destination())){ this.rebroadcast(m); } } else if (this.id == m.destination()) { //it has reached the destination! } else { System.out.println("SOMETHING WENT TERRIBLY WRONG"); } }
8
private boolean attemptWin(Command command){ if (!command.hasNthWord(2)) { System.out.println("Go where?"); } else if (command.getNthSegment(1).equalsIgnoreCase("Sunset")){ if(bag.contains("hull") && bag.contains("mast") && bag.contains("rudder") && bag.contains("helm")){ System.out.println("Something something ken boat win"); } else { System.out.println("Oh no missing boat parts lose"); } return true; } return false; }
6
public void testConstructor_RP_RI8() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Period dur = new Period(0, 0, 0, 0, 0, 0, 0, -1); try { new Interval(dur, dt); fail(); } catch (IllegalArgumentException ex) {} }
1
public void setButtonRate(JButton button) { button.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent evt) { try { System.out.println("Rate Button for Media_Id: " + wbview.getSelectedId()); if (wbview.getSelectedRowCount() == 1) { wbview.invokeRateMediaDialog(wbview.getSelectedId()); } else { throw new Exception("multiselect"); } } catch (Exception e) { if (e.getMessage().equals("multiselect")) { wbview.showError("You have to select ONE media item!"); } else { wbview.showError("You have to select a media item!"); } } } }); }
3
public static Double complexSum ( Double value1, Double value2 ) { if ( ( value1 >= 0.0 && value2 >= 0.0 ) || ( value1 <= 0.0 && value2 <= 0.0 ) ) { return value1 + value2; } else if ( ( value1 >= 0.0 && value2 <= 0.0 ) || ( value1 <= 0.0 && value2 >= 0.0 ) ) { return value2 - value1; } return 0.0; }
8
protected boolean checkCDATA(StringBuffer buf) throws IOException { char ch = this.readChar(); if (ch != '[') { this.unreadChar(ch); this.skipSpecialTag(0); return false; } else if (! this.checkLiteral("CDATA[")) { this.skipSpecialTag(1); // one [ has already been read return false; } else { int delimiterCharsSkipped = 0; while (delimiterCharsSkipped < 3) { ch = this.readChar(); switch (ch) { case ']': if (delimiterCharsSkipped < 2) { delimiterCharsSkipped += 1; } else { buf.append(']'); buf.append(']'); delimiterCharsSkipped = 0; } break; case '>': if (delimiterCharsSkipped < 2) { for (int i = 0; i < delimiterCharsSkipped; i++) { buf.append(']'); } delimiterCharsSkipped = 0; buf.append('>'); } else { delimiterCharsSkipped = 3; } break; default: for (int i = 0; i < delimiterCharsSkipped; i += 1) { buf.append(']'); } buf.append(ch); delimiterCharsSkipped = 0; } } return true; } }
9
private void StakeholderListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_StakeholderListValueChanged // TODO add your handling code here: Stakeholder tempSH = new Stakeholder(); String tempName = (String) StakeholderList.getSelectedValue(); for (int i = 0; i < Stakeholders.size(); i++){ if (Stakeholders.get(i).getName().equals(tempName) ){ tempSH = Stakeholders.get(i); break; } } //set name SHNameTextArea.setText(tempSH.getName()); //set wants SHWantsTextArea.setText(tempSH.getWants()); //set booleans if (tempSH.getPower() == true) { SHPowerYRadioButton.setSelected(true); SHPowerNRadioButton.setSelected(false); } else { SHPowerYRadioButton.setSelected(false); SHPowerNRadioButton.setSelected(true); } if (tempSH.getLegitimacy() == true) { SHLegitimacyYRadioButton.setSelected(true); SHLegitimacyNRadioButton.setSelected(false); } else { SHLegitimacyYRadioButton.setSelected(false); SHLegitimacyNRadioButton.setSelected(true); } if (tempSH.getUrgency() == true) { SHUrgencyYRadioButton.setSelected(true); SHUrgencyNRadioButton.setSelected(false); } else { SHUrgencyYRadioButton.setSelected(false); SHUrgencyNRadioButton.setSelected(true); } if (tempSH.getCooperation() == true) { SHCooperationYRadioButton.setSelected(true); SHCooperationNRadioButton.setSelected(false); } else { SHCooperationYRadioButton.setSelected(false); SHCooperationNRadioButton.setSelected(true); } if (tempSH.getThreat() == true) { SHThreatYRadioButton.setSelected(true); SHThreatNRadioButton.setSelected(false); } else { SHThreatYRadioButton.setSelected(false); SHThreatNRadioButton.setSelected(true); } //set all areas to non-editable SHNameTextArea.setEnabled(false); SHWantsTextArea.setEnabled(false); SHPowerYRadioButton.setEnabled(false); SHPowerNRadioButton.setEnabled(false); SHLegitimacyYRadioButton.setEnabled(false); SHLegitimacyNRadioButton.setEnabled(false); SHUrgencyYRadioButton.setEnabled(false); SHUrgencyNRadioButton.setEnabled(false); SHCooperationYRadioButton.setEnabled(false); SHCooperationNRadioButton.setEnabled(false); SHThreatYRadioButton.setEnabled(false); SHThreatNRadioButton.setEnabled(false); SHSaveButton.setEnabled(false); SHEditButton.setEnabled(true); SHRemoveButton.setEnabled(true); }//GEN-LAST:event_StakeholderListValueChanged
7
public Tile(int x, int y, int t) { this.x = x; this.y = y; type = t; }
0
public void sendToNether(Player p){ if(p.hasPermission(DeityNether.OVERRIDE_PERMISSION)){ testAndPort(p, false); }else if(p.hasPermission(DeityNether.GENERAL_PERMISSION)){ if(p.getWorld() == DeityNether.server.getWorld(DeityNether.config.getNetherWorldName())){ p.sendMessage(DeityNether.lang.formatAlreadyInNether()); }else{ if(PlayerStats.hasWaited(p) || PlayerStats.hasTimeLeft(p)){ testAndPort(p, true); }else{ p.sendMessage(DeityNether.lang.formatNeedToWait(PlayerStats.getWaitHoursLeft(p), PlayerStats.getWaitMinutesLeft(p), PlayerStats.getWaitSecondsLeft(p))); } } }else{ p.sendMessage(DeityNether.lang.formatInvalidArguments()); } }
5
protected String[] parseRow( ) throws SQLException { String[] newRow = new String[ COLUMN_NAMES.length ]; String headerLine = readNextLine(); if ( headerLine == null ) { return null; } if ( !isRecordHeader( headerLine ) ) { throw new SQLException( "Badly formatted record header: " + headerLine ); } // the next line has all of the columns except for DESCRIPTION String mainline = readNextLine(); if ( mainline == null ) { return null; } int oldIdx[] = new int[ 1 ]; oldIdx[ 0 ] = 0; for ( int i = 0; i < DESCRIPTION; i++ ) { newRow[ i ] = readField( mainline, oldIdx ); } // get the number of lines in the DESCRIPTION int descriptionLineCount = 0; try { String lineCountField = newRow[ LINE_COUNT ]; if ( lineCountField != null ) { lineCountField = lineCountField.trim(); String numberString = lineCountField.substring( 0, lineCountField.indexOf( ' ' ) ); descriptionLineCount = Integer.parseInt( numberString ); } } catch ( Throwable t ) { throw wrap( "Error parsing description line count at line " + getLineNumber() + ": " + mainline, t ); } // account for extra blank line descriptionLineCount++; // the rest of the record is the DESCRIPTION StringBuffer buffer = new StringBuffer(); for ( int i = 0; i < descriptionLineCount; i++ ) { String nextLine = readNextLine(); buffer.append( nextLine ); } newRow[ DESCRIPTION ] = buffer.toString(); return newRow; }
7
public void setAuthor(String author) { this.author = author; }
0
protected static boolean isDayLightSavings(double latitude, double longitude, int date, int dstFlag) { boolean DSTBoolean = false; //user says no if(dstFlag == 1) { DSTBoolean = false; } //user says yes else if (dstFlag == 2) { DSTBoolean = true; } //user does not know else { try { //check if its summer and we're in a location that does DST (S-hemisphere not implemented yet) //Also, assuming USA DST dates for global usage if(hasDSTLocation(latitude, longitude) && isUSASummer(date)) { DSTBoolean = true; } } catch (Exception e) { System.out.println(e); } } return DSTBoolean; }
5
private String checkDetailsNode(Element element, int nodeCount, String xmlTag){ if(nodeCount == 0){ //This value is returned when detail tag is not present return ""; } String genre = ""; NodeList detailsNode = element.getElementsByTagName("detail"); for(int i = 0; i < detailsNode.getLength(); i++){ Node tempNode = detailsNode.item(i); if(tempNode.getNodeType() == Node.ELEMENT_NODE){ Element tempEl = (Element)tempNode; String str = tempEl.getElementsByTagName("name").item(0).getTextContent().toString(); if(str.equals("Genre")){ String genreValue = tempEl.getElementsByTagName("value").item(0).getTextContent().toString(); genreValue = replaceSpecialCharacters(genreValue); //This value is returned when we have the detail tag as well as sub-tags with name-value pair return genreValue; } } } //This value is returned we have a tag for detail but does not contain sub-tags showing Genre information return genre; }
4
public boolean getBoolean(String key) throws JSONException { Object object = this.get(key); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); }
6