text
stringlengths
14
410k
label
int32
0
9
private String getMatch(String s) { for (int i = 0; i < dataList.size(); i++) { String s1 = dataList.get(i).toString(); if (s1 != null) { if (!isCaseSensitive && s1.toLowerCase().startsWith(s.toLowerCase())) return s1; if (isCaseSensitive && s1.startsWith(s)) return s1; } } return null; }
6
@Override public Object getValueAt(int rowIndex, int columnIndex) { RaavareDTO raavare = raavareList.get(rowIndex); Object value = null; switch (columnIndex) { case 0: value = raavare.getRaavareId(); break; case 1: value = raavare.getVareNavn(); break; case 2: value = raavare.getLeverandoerId(); break; case 3: value = raavare.getRaavareKostPris(); break; case 4: value = raavare.getRaavareVaegt(); break; } return value; }
5
private int[] generateTestingArray() { Random r = new Random(); int arraySize = (Integer) spinnerArraySize.getValue(); int[] values = new int[arraySize]; for (int i = 0; i < values.length; i++) values[i] = r.nextInt(SAVHistoryComponent.PLAYING_CARD_AMOUNT); if (this.rdbtnSorted.isSelected()) { Arrays.sort(values); } else if (this.rdbtnReverse.isSelected()) { Arrays.sort(values); for (int i = 0; i < values.length / 2; i++) { int temp = values[i]; values[i] = values[values.length - i - 1]; values[values.length - i - 1] = temp; } } return values; }
4
@SuppressWarnings("unchecked") void readMolecularOrbitals() throws Exception { Hashtable[] mos = new Hashtable[5]; Vector[] data = new Vector[5]; int nThisLine = 0; while (readLine() != null && line.toUpperCase().indexOf("DENS") < 0) { String[] tokens = getTokens(line); int ptData = (line.charAt(5) == ' ' ? 2 : 4); if (line.indexOf(" ") == 0) { addMOData(nThisLine, data, mos); nThisLine = tokens.length; tokens = getTokens(readLine()); for (int i = 0; i < nThisLine; i++) { mos[i] = new Hashtable(); data[i] = new Vector(); mos[i].put("symmetry", tokens[i]); } tokens = getStrings(readLine().substring(21), nThisLine, 10); for (int i = 0; i < nThisLine; i++) mos[i].put("energy", new Float(tokens[i])); continue; } try { for (int i = 0; i < nThisLine; i++) data[i].add(tokens[i + ptData]); } catch (Exception e) { Logger.error("Error reading Gaussian file Molecular Orbitals at line: " + line); break; } } addMOData(nThisLine, data, mos); }
8
@Override public Consulta listByIdUpdate(int codigo) { Connection con = null; PreparedStatement pstm = null; ResultSet rs = null; Consulta c = new Consulta(); try { con = ConnectionFactory.getConnection(); pstm = con.prepareStatement(LISTBYIDUPDATE); pstm.setInt(1, codigo); rs = pstm.executeQuery(); while (rs.next()) { //codigo, data_consulta,descricao, codigo_paciente,tipo_consulta,horario c.setCodigo(rs.getInt("consulta.codigo")); c.setDataDaConsulta(rs.getDate("data_consulta")); c.setDescricao(rs.getString("descricao")); c.setTipoConsulta(rs.getString("tipo_consulta")); c.setHorario(rs.getTime("horario")); Paciente p = new Paciente(); p.setCodigo(rs.getInt("paciente.codigo")); p.setNome(rs.getString("paciente.nome")); c.setPaciente(p); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao listar(ID): " + ex.getMessage()); } finally { try { ConnectionFactory.closeConnection(con, pstm, rs); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro ao fechar a conexão" + e.getMessage()); } } return c; }
3
public void initChatGroup() { String sessionId = getSession().getId(); checkUserRegister(getRequest(), sessionId); int selfChatState = UserState.dao.getUserState(sessionId); if (selfChatState == Users.onlineWithoutChat || selfChatState == Users.offLine || selfChatState == Users.unExist) { UserState.dao.updateUserState(sessionId, Users.requestChat); String newAcceptancerId = UserState.dao.getLongWriteUser(sessionId);// 返回此用户ID if (StringKit.isBlank(newAcceptancerId)) { renderText("-1"); } else { renderText("0," + newAcceptancerId); } } else if (selfChatState == Users.onChatting || selfChatState == Users.onWritting) { String resultTypeAndId = ChatGroup.dao.getChatTypeAndId(sessionId, ChatGroup.onChatting); if (StringKit.isBlank(resultTypeAndId)) { UserState.dao.updateUserState(sessionId, Users.requestChat); renderText("-2"); } else { String[] strTempArr = resultTypeAndId.split(","); renderText("1," + strTempArr[1] + "," + UserState.dao.getUserState(strTempArr[1])); } } else if (selfChatState == Users.requestChat) { String acceptance_session_id = UserState.dao .getLongWriteUser(sessionId); if (StringKit.isBlank(acceptance_session_id)) { renderText("-1"); } else { renderText("0," + acceptance_session_id); } } }
9
@Override public boolean matches(String[] input) { for (String word: input) { if (word.equals("test")) { return true; } } return false; }
2
@Override public boolean isBuffered() { //if(gcode==null) return false; if (Constants.GCDEF.G0.equals(gcode) || Constants.GCDEF.G1.equals(gcode) || Constants.GCDEF.G2.equals(gcode) || Constants.GCDEF.M106.equals(gcode) || Constants.GCDEF.M107.equals(gcode) || Constants.GCDEF.G30.equals(gcode) || Constants.GCDEF.G31.equals(gcode) || Constants.GCDEF.G32.equals(gcode)){ return true; } return false; }
8
public static int strxtoi(String hex) { final int ASCII_CUTOFF_INTS = 48; final int ASCII_CUTOFF_LETTERS = 65; final int ASCII_SUBTRACT_LETTERS = 55; final int BASE = 16; int sum = 0; for(int i = 0 ; i < hex.length() ; i++){ sum *= BASE; int val = (int) hex.charAt(i); if(val >= ASCII_CUTOFF_LETTERS){ // if a letter sum += val - ASCII_SUBTRACT_LETTERS; } else{ // if a digit sum += val - ASCII_CUTOFF_INTS;//get the ascii value, then subtract the cutoff. } } return sum; }
2
public int getMaxHP() { return maxHP; }
0
protected synchronized void paintComponent(Graphics g2) { if(!animate_) { return; } super.paintComponent(g2); Graphics2D g2D = (Graphics2D)g2; g2D.setFont(grFont); double timeSpan = settings.getTimeSpan(); panelHeight_ = pnLeft.getHeight() - 100 - SHIFT_Y - SHIFT_BOTTOM; int minWidth = pnLeft.getWidth() - 50 - 2 * SHIFT_X; panelWidth_ = minWidth; double sdWindowSize = ResourceWindow.this.slidingWindowSize; if(Double.compare(sdWindowSize, Double.MAX_VALUE) != 0) { panelWidth_ = (int)(minWidth * (settings.getTimeSpan() / sdWindowSize)); } panelWidth_ = (panelWidth_ < minWidth) ? minWidth : panelWidth_; scaleY_ = panelHeight_ / (float) numPE; scaleX_ = panelWidth_ / (float) (timeSpan); scaleY_ *= sliderY.getValue() * (float) 0.1; scaleX_ *= sliderX.getValue() * (float) 0.1; super.setPreferredSize(new Dimension((int) (timeSpan * scaleX_) + 2 * SHIFT_X, (int) ((numPE) * scaleY_) + SHIFT_Y + SHIFT_BOTTOM)); drawSchedulingQueue(timeSpan, g2D); drawGridsAndAxes(timeSpan, g2D); super.revalidate(); }
3
@Override public void removeLayoutComponent(Component component) { if (defaultComponents.contains(component)) { defaultComponents.remove(component); } if (bottomComponents.contains(component)) { bottomComponents.remove(component); } if (bottomCenter.contains(component)) { bottomCenter.remove(component); } }
3
public static List<?> GetAll(Class aClass) { if (aClass.equals(Transaction.class)) return allData.getAllTransactions(); if (aClass.equals(Transfer.class)) return allData.getAllTransfers(); if (aClass.equals(ExpenseCategory.class)) return allData.getAllExpenseCategories(); if (aClass.equals(PaymentCategory.class)) return allData.getAllPaymentCategories(); if (aClass.equals(WishListItem.class)) return allData.getAllWishListItems(); System.out.println("Objects for class :" + aClass.toString() + " are not found in the repository."); return null; }
6
@Override public String getElementAt(int index) { // TODO Auto-generated method stub return names[index]; }
0
public void method212(boolean flag, int j, int k, int l, int i1, int j1) { int k1 = 256; if(flag) k1 += 0x20000; l -= anInt290; i1 -= anInt291; if(j1 == 1 || j1 == 3) { int l1 = j; j = k; k = l1; } for(int i2 = l; i2 < l + j; i2++) if(i2 >= 0 && i2 < anInt292) { for(int j2 = i1; j2 < i1 + k; j2++) if(j2 >= 0 && j2 < anInt293) method214(i2, j2, k1); } }
9
public boolean equals(final Object obj) { if (obj instanceof Key) { final Key key = (Key) obj; return (key.node == node) && (key.blockIndex == blockIndex); } return false; }
2
private void parseBounds(RdpPacket_Localised data, BoundsOrder bounds) throws OrderException { int present = 0; present = data.get8(); if ((present & 1) != 0) { bounds.setLeft(setCoordinate(data, bounds.getLeft(), false)); } else if ((present & 16) != 0) { bounds.setLeft(setCoordinate(data, bounds.getLeft(), true)); } if ((present & 2) != 0) { bounds.setTop(setCoordinate(data, bounds.getTop(), false)); } else if ((present & 32) != 0) { bounds.setTop(setCoordinate(data, bounds.getTop(), true)); } if ((present & 4) != 0) { bounds.setRight(setCoordinate(data, bounds.getRight(), false)); } else if ((present & 64) != 0) { bounds.setRight(setCoordinate(data, bounds.getRight(), true)); } if ((present & 8) != 0) { bounds.setBottom(setCoordinate(data, bounds.getBottom(), false)); } else if ((present & 128) != 0) { bounds.setBottom(setCoordinate(data, bounds.getBottom(), true)); } if (data.getPosition() > data.getEnd()) { throw new OrderException("Too far!"); } }
9
public static void main(String... args) { int nodeNumber = 3; //number of nodes in the network int initialPort = 8000; //initial UDP port String userNamePrefix = "TestUser"; //userId common prefix /* * PART I : Network initialization */ //Create the environment and initialize all the node EnvironmentImpl env = new EnvironmentImpl(); env.registerNodes(nodeNumber, userNamePrefix, initialPort); //Nodes are registered to the Environment System.out.println("Registered Nodes: " + env.getAllNodes()); System.out.println("******************* Starting Nodes *******************************"); env.startupAll(); //CA is contacted by every Node // !!! The CA could be shut down, old nodes don't need to contact it anymore !!! System.out.println("******************* Bootstrapping Nodes *******************************"); env.bootstrapAll(); //Kademlia bootstrap procedure is completed by every Node //Build a new application upon the environment. //The use of Application class is not strictly necessary. It is just used to provide //a useful handle to a particular node, in order to differentiate it from the other //nodes of the network. Application appl = new Application(env); //register the application to a new node (the new node will be added to the environment) Node n = appl.registerNode("ApplicationNode", 10000); System.out.println("Registered Nodes: " + env.getAllNodes()); //initialize the new node try { n.init(); //the new node is initialized (startup + bootstrap) } catch (IOException ioe) { System.err.println("Error in node initialization"); System.exit(0); } //Method getNode() retrieves the new Node n = appl.getNode(); //Print the Nodes of the environment System.out.println(env); /* * PART II : RPCs */ //----Blocking RPC call try { System.out.println("Node \"" + n.getUserId() + "\" stores a content with the key " + NodeId.MAXIMUM); //if get() is called on the result of an RPC, the process is blocked for a network I/O request int replica = n.put(NodeId.MAXIMUM, new byte[6000], "ApplType", 3600000).get(); System.out.println("CONTENT STORED AT " + replica + " REPLICAS"); //print the Storages: K nodes are keeping the content in their stores System.out.println("STORAGES"); for (Node i : env.getAllNodes()) { System.out.println(i.getStorage()); } //Select another node to perform a findValue operation n = env.selectNode(userNamePrefix + "7"); System.out.println("Node \"" + n.getUserId() + "\" searches for a content with the key " + NodeId.MAXIMUM + "(blocking mode)"); Collection<StorageEntry> results = n.get(NodeId.MAXIMUM, null, null, false, nodeNumber).get(); if (results.size() == 0) { System.out.println("NO CONTENT FOUND!"); } else { System.out.println("CONTENTS FOUND:"); for (StorageEntry e : results) //print the found values { System.out.println("--> " + e); } } } catch (InterruptedException ie) { System.err.println("Interrupted"); } catch (ExecutionException e) { System.err.println("ExecutionException"); } //----Non-blocking RPC call System.out.println("Node \"" + n.getUserId() + "\" searches for a content with the key " + NodeId.MAXIMUM + "(blocking mode)"); //Retrieves the result of a findValue via observer. //The definition of the observer class is application-dependent. Here a simple stub is used. FutureObserver<Collection<StorageEntry>> observer = new FindNodeObserverStub(); ObservableFuture<Collection<StorageEntry>> result = n.get(NodeId.MAXIMUM, null, null, false, 10); result.addObserver(observer); /* * PART III : Shutdown & restart */ //requires confirm to go on System.out.println("Press a button to CONTINUE (you could also try to shutdown the CA...)"); try { bufReader.readLine(); } catch (IOException e) { e.printStackTrace(); } //unregisters the Application from its node //(it simply put NULL in appl.node, the node remains active) appl.unregister(); //shutdown every Node registered to the Environment, saving their states to disk env.shutDownAll(true); //reload all the saved nodes in the environment env.loadNetwork(); env.startupAll(); env.bootstrapAll(); //retrieves the application node by its name n = env.selectNode("ApplicationNode"); //print the Storages: stored contents are maintained for (Node x : env.getAllNodes()) { System.out.println(x.getStorage()); } //requires confirm to shutdown environment System.out.println("Press a button to EXIT"); try { bufReader.readLine(); } catch (IOException e) { e.printStackTrace(); } //shutdown without save env.shutDownAll(true); }
9
private static BigDecimal regraC(Transferencia transf) { long dias = calculaDiasEntreDatas(transf.getCreated(), transf.getAgenda()); BigDecimal valRetorno = null; if (dias > 30) { valRetorno = transf.getValor().multiply(new BigDecimal("0.012")); } else if (dias > 25) { valRetorno = transf.getValor().multiply(new BigDecimal("0.021")); } else if (dias > 20) { valRetorno = transf.getValor().multiply(new BigDecimal("0.043")); } else if (dias > 15) { valRetorno = transf.getValor().multiply(new BigDecimal("0.067")); } else if (dias > 10) { valRetorno = transf.getValor().multiply(new BigDecimal("0.074")); } else { valRetorno = transf.getValor().multiply(new BigDecimal("0.083")); } return valRetorno; }
5
private Object newInstance (Class type) { try { return type.newInstance(); } catch (Exception ex) { try { // Try a private constructor. Constructor constructor = type.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (SecurityException ignored) { } catch (NoSuchMethodException ignored) { if (type.isArray()) throw new JsonException("Encountered JSON object when expected array of type: " + type.getName(), ex); else if (type.isMemberClass() && !Modifier.isStatic(type.getModifiers())) throw new JsonException("Class cannot be created (non-static member class): " + type.getName(), ex); else throw new JsonException("Class cannot be created (missing no-arg constructor): " + type.getName(), ex); } catch (Exception privateConstructorException) { ex = privateConstructorException; } throw new JsonException("Error constructing instance of class: " + type.getName(), ex); } }
7
private void CriarEscola_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CriarEscola_ButtonActionPerformed if (NomeEscola_TextField.getText().equals("")) { JOptionPane.showMessageDialog(null, "Escreva um nome para a escola!", "Alerta!", JOptionPane.WARNING_MESSAGE); } else { try { a.criaEscola(NomeEscola_TextField.getText(), Rua_TextField.getText() + " " + CP_TextField.getText() + "-" + CP_TextField2.getText(), Localidade_TextField.getText()); JOptionPane.showMessageDialog(null, "Escola criada com sucesso!", "Sucesso!", JOptionPane.DEFAULT_OPTION); } catch (Exception ex) { JOptionPane.showMessageDialog(null,ex.getMessage(),"Erro!",JOptionPane.ERROR_MESSAGE); } /* Escola_ComboBox.removeAllItems(); for(Escola escola : a.getDAOEscola().values()) Escola_ComboBox.addItem(escola.getNome()); Escola_ComboBox1.removeAllItems(); for(Escola escola : a.getDAOEscola().values()) Escola_ComboBox1.addItem(escola.getNome()); Escola_ComboBox2.removeAllItems(); for(Escola escola : a.getDAOEscola().values()) Escola_ComboBox2.addItem(escola.getNome()); */ } }//GEN-LAST:event_CriarEscola_ButtonActionPerformed
2
public String getNom() { return nom; }
0
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: DefaultTableModel dft = (DefaultTableModel) jTable3.getModel(); dft.setRowCount(0); if (jRadioButton2.isSelected()) { try { ResultSet rs = DB.myConnection().createStatement().executeQuery("select * from book where BookID like '" + jTextField1.getText() + "%' order by BookID ASC"); while (rs.next()) { Vector v1 = new Vector(); v1.add(rs.getString("BookID")); v1.add(rs.getString("BookName")); dft.addRow(v1); } } catch (Exception e) { } } else if (jRadioButton1.isSelected()) { try { ResultSet rs = DB.myConnection().createStatement().executeQuery("select * from book where BookName like '" + jTextField1.getText() + "%' order by BookName ASC"); while (rs.next()) { Vector v2 = new Vector(); v2.add(rs.getString("BookID")); v2.add(rs.getString("BookName")); dft.addRow(v2); } } catch (Exception e) { } } }//GEN-LAST:event_jButton1ActionPerformed
6
private Expr statement() throws IOException { if (lookAheadToken.tag == '(' || lookAheadToken.tag == Tag.NUM || lookAheadToken.tag == Tag.REAL) { expression(); Expr t = e.gen(); return t.reduce(); } else if (lookAheadToken.tag == Tag.ID) { Token temp = lookAheadToken; match(Tag.ID); Word w = (Word) temp; if (lookAheadToken.tag == '=') { tempPostFixString += w.lexeme + " "; move(); Id id = symbolTable.get(temp); if (id == null) { error(w.lexeme + " not defined"); } Stmt s = new Set(id, expression()); tempPostFixString += "= "; return s.gen(); } else { lookAheadToken = temp; expression(); Expr t = e.gen(); return t.reduce(); } } else error("syntax error"); return null; }
6
private static LinkedList<CommMode> parseComm(String path) throws ParserConfigurationException, SAXException, IOException { // xml get root Document partXml = XmlReader.getDoc(path); Node partNod = partXml.getDocumentElement(); Element partElem = (Element) partNod; // the return LinkedList<CommMode> ret = new LinkedList<CommMode>(); // get comm nodes NodeList coms = partElem.getElementsByTagName("comm"); for (int i = 0; i < coms.getLength(); i++) { // the node Element node = (Element) coms.item(i); // get comm type String mode = node.getElementsByTagName("comm_type").item(0) .getTextContent(); // System.out.println("mode:" + mode); if (mode.equals(Airsched.MODE_SAMPLING)) { //SamplingComm smp = new } else if (mode.equals(Airsched.MODE_QUEUEING)) { } else { System.out.println("Mode exception:" + mode); } } return ret; // return null; }
3
public double getResult(String expressionCode) { StringBuffer expression2 = new StringBuffer(); String expression = (String)hashExpressions.get(expressionCode); int i = 0; int lastPoz = 0; for(; i < expression.length(); i++) if(i == expression.length() - 1 || Operator.isOperator(expression.charAt(i))) { String element = expression.substring(lastPoz, i); if(element.matches(".*[a-zA-Z].*")) { if(element.matches("E[0-9]{1,2}")) expression2.append((new Double(getResult(element))).toString()); else if(element.equals("n")) expression2.append(new Double(factor)); else expression2.append((String)hashContents.get(element)); } else { expression2.append(element); } lastPoz = i + 1; expression2.append(expression.charAt(i)); } return Calculate.evaluate(expression2.toString()); }
6
@Override public int read() throws IOException { if(bList.isEmpty()) { return -1; } else { //Damn the signed bytes return bList.pollFirst()&255; } }
1
private static String encode_base64(byte d[], int len) throws IllegalArgumentException { int off = 0; StringBuffer rs = new StringBuffer(); int c1, c2; if (len <= 0 || len > d.length) throw new IllegalArgumentException ("Invalid len"); while (off < len) { c1 = d[off++] & 0xff; rs.append(base64_code[(c1 >> 2) & 0x3f]); c1 = (c1 & 0x03) << 4; if (off >= len) { rs.append(base64_code[c1 & 0x3f]); break; } c2 = d[off++] & 0xff; c1 |= (c2 >> 4) & 0x0f; rs.append(base64_code[c1 & 0x3f]); c1 = (c2 & 0x0f) << 2; if (off >= len) { rs.append(base64_code[c1 & 0x3f]); break; } c2 = d[off++] & 0xff; c1 |= (c2 >> 6) & 0x03; rs.append(base64_code[c1 & 0x3f]); rs.append(base64_code[c2 & 0x3f]); } return rs.toString(); }
5
public static void combSort11(double arrayToSort[], int linkedArray[]) { int switches, j, top, gap; double hold1; int hold2; gap = arrayToSort.length; do { gap=(int)(gap/1.3); switch(gap) { case 0: gap = 1; break; case 9: case 10: gap=11; break; default: break; } switches=0; top = arrayToSort.length-gap; for(int i=0; i<top; i++) { j=i+gap; if(arrayToSort[i] > arrayToSort[j]) { hold1=arrayToSort[i]; hold2=linkedArray[i]; arrayToSort[i]=arrayToSort[j]; linkedArray[i]=linkedArray[j]; arrayToSort[j]=hold1; linkedArray[j]=hold2; switches++; }//endif }//endfor } while(switches>0 || gap>1); }
7
public static Map<Marker, Marker> collapseZeroGap(Markers markersOri) { Map<Marker, Marker> collapse = new HashMap<Marker, Marker>(); // Sort markers by start Markers sorted = new Markers(); sorted.add(markersOri); sorted.sort(false, false); // Create new set of markers Marker markerPrev = null; // Previous marker in the list Marker markerToAdd = null; int countCollapsed = 0; for (Marker m : sorted) { if (markerToAdd == null) markerToAdd = m.clone(); if (markerPrev != null) { // Find start, end and gap size int start = markerPrev.getEnd() + 1; int end = m.getStart() - 1; int gapSize = end - start + 1; if (gapSize <= 0) { countCollapsed++; if (markerToAdd.getEnd() < m.getEnd()) markerToAdd.setEnd(m.getEnd()); // Set new end for this marker (we are collapsing it with the previous one) // Do we need to correct frame information? if (markerToAdd.isStrandMinus() && (markerToAdd instanceof MarkerWithFrame) && (m instanceof MarkerWithFrame)) { MarkerWithFrame markerToAddWf = (MarkerWithFrame) markerToAdd; MarkerWithFrame mwf = (MarkerWithFrame) m; markerToAddWf.setFrame(mwf.getFrame()); } } else markerToAdd = m.clone(); // Get ready for next iteration } collapse.put(m, markerToAdd); markerPrev = m; } // Sanity check HashSet<Marker> collapsed = new HashSet<Marker>(); collapsed.addAll(collapse.values()); if ((markersOri.size() - countCollapsed) != collapsed.size()) throw new RuntimeException("Sanitycheck failed. This should never happen!\n\tmarkers.size: " + markersOri.size() + "\n\tcountCollapsed: " + countCollapsed + "\n\treplaced.size : " + collapsed.size()); return collapse; }
9
private void setGameCheck(Game game) { for (int y = 0; y < 9; y++) { for (int x = 0; x < 9; x++) { fields[y][x].setBackground(Color.WHITE); if (fields[y][x].getForeground().equals(Color.BLUE)) fields[y][x].setBackground(game.isCheckValid(x, y) ? Color.GREEN : Color.RED); } } }
4
@Nullable public T waitForResult() throws InterruptedException { if(!set) { synchronized (waitLock) { if(!set) { waitLock.wait(); } } } if(!set) { throw new IllegalStateException("Notified but never set: " + this); } try { //noinspection unchecked return (T)result; } catch (ClassCastException e) { throw new UnexpectedResultException("Return type was not what was expected. Received: " + result); } }
4
* @param unit The <code>Unit</code> that is building. * @param name The new settlement name. * @return An <code>Element</code> encapsulating this action. */ public Element buildSettlement(ServerPlayer serverPlayer, Unit unit, String name) { ChangeSet cs = new ChangeSet(); Game game = serverPlayer.getGame(); // Build settlement Tile tile = unit.getTile(); Settlement settlement; if (Player.ASSIGN_SETTLEMENT_NAME.equals(name)) { name = serverPlayer.getSettlementName(random); } if (serverPlayer.isEuropean()) { settlement = new ServerColony(game, serverPlayer, name, tile); serverPlayer.addSettlement(settlement); settlement.placeSettlement(false); } else { IndianNationType nationType = (IndianNationType) serverPlayer.getNationType(); UnitType skill = RandomChoice.getWeightedRandom(logger, "Choose skill", random, nationType.generateSkillsForTile(tile)); if (skill == null) { // Seasoned Scout List<UnitType> scouts = getGame().getSpecification() .getUnitTypesWithAbility(Ability.EXPERT_SCOUT); skill = Utils.getRandomMember(logger, "Choose scout", scouts, random); } settlement = new ServerIndianSettlement(game, serverPlayer, name, tile, false, skill, new HashSet<Player>(), null); serverPlayer.addSettlement(settlement); settlement.placeSettlement(true); for (Player p : getGame().getPlayers()) { if ((ServerPlayer)p == serverPlayer) continue; ((IndianSettlement)settlement).setAlarm(p, (p.isIndian()) ? new Tension(Tension.Level.CONTENT.getLimit()) : serverPlayer.getTension(p)); } } // Join. Remove equipment first in case role confuses placement. ((ServerUnit)unit).csRemoveEquipment(settlement, new HashSet<EquipmentType>(unit.getEquipment().keySet()), 0, random, cs); unit.setLocation(settlement); unit.setMovesLeft(0); // Update with settlement tile, and newly owned tiles. List<FreeColGameObject> tiles = new ArrayList<FreeColGameObject>(); tiles.addAll(settlement.getOwnedTiles()); cs.add(See.perhaps(), tiles); cs.addHistory(serverPlayer, new HistoryEvent(game.getTurn(), HistoryEvent.EventType.FOUND_COLONY) .addName("%colony%", settlement.getName())); // Also send any tiles that can now be seen because the colony // can perhaps see further than the founding unit. if (settlement.getLineOfSight() > unit.getLineOfSight()) { tiles.clear(); for (Tile t : tile.getSurroundingTiles(unit.getLineOfSight()+1, settlement.getLineOfSight())) { if (!tiles.contains(t)) tiles.add(t); } cs.add(See.only(serverPlayer), tiles); } // Others can see tile changes. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); }
9
private void restoreTree(List<Component> roots, Map<String, Object> stateMap) { List<Component> allChildren = new ArrayList<Component>(); for (Component root : roots) { if (root != null) { PropertySupport p = getProperty(root); if (p != null) { String pathname = getComponentPathname(root); if (pathname != null) { Object state = stateMap.get(pathname); if (state != null) { p.setSessionState(root, state); } else { log("No saved state for " + root); } } } } if (root instanceof Container) { Component[] children = ((Container) root).getComponents(); if ((children != null) && (children.length > 0)) { Collections.addAll(allChildren, children); } } } if (allChildren.size() > 0) { restoreTree(allChildren, stateMap); } }
9
public String getSaveEncoding() { return (String) saveEncodingComboBox.getSelectedItem(); }
0
private void cargaBDF(BufferedReader bf) throws IOException { String linea; int indice; double x,y,z,w; Nodo nodo; Elemento elemento; do { linea = bf.readLine(); if(linea.startsWith("GRID")) { indice = Integer.parseInt(linea.substring(9, 14)); x = Double.parseDouble(linea.substring(24,31)); y = Double.parseDouble(linea.substring(32,40)); z = Double.parseDouble(linea.substring(40)); nodo = new Nodo(new double[]{x,y,z}); nodos.put(new Integer(indice), nodo); } else if(linea.startsWith("CQUAD4")) { indice = Integer.parseInt(linea.substring(9, 14)); x = Double.parseDouble(linea.substring(25,32)); y = Double.parseDouble(linea.substring(33,40)); z = Double.parseDouble(linea.substring(41,48)); w = Double.parseDouble(linea.substring(49)); elemento = new Elemento(new int[]{(int)x,(int)y,(int)z,(int)w}); elementos.put(new Integer(indice), elemento); } else if(linea.startsWith("CTRIA3")) { indice = Integer.parseInt(linea.substring(9, 14)); x = Double.parseDouble(linea.substring(25,32)); y = Double.parseDouble(linea.substring(33,40)); z = Double.parseDouble(linea.substring(41)); elemento = new Elemento(new int[]{(int)x,(int)y,(int)z}); elementos.put(new Integer(indice), elemento); } }while(!linea.startsWith("ENDDATA")); }
4
@EventHandler public void WolfNightVision(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getWolfConfig().getDouble("Wolf.NightVision.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if ( plugin.getWolfConfig().getBoolean("Wolf.NightVision.Enabled", true) && damager instanceof Wolf && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, plugin.getWolfConfig().getInt("Wolf.NightVision.Time"), plugin.getWolfConfig().getInt("Wolf.NightVision.Power"))); } }
6
public void visitArrayRefExpr(final ArrayRefExpr expr) { // NullPointerException, ArrayIndexOutOfBoundsException, // ArrayStoreException sideEffects |= SideEffectChecker.THROW; if (expr.isDef()) { sideEffects |= SideEffectChecker.STORE; } sideEffects |= SideEffectChecker.ALIAS; expr.visitChildren(this); }
1
@Override public final void write(final String text) { if (text == null) { System.out.println(INVALID_STRING); return; } System.out.println(text); }
1
public void draw(GOut g) { if(state == 0) g.chcolor(255, 192, 192, 255); else if(state == 1) g.chcolor(192, 192, 255, 255); else if(state == 2) g.chcolor(192, 255, 192, 255); g.image(bg, Coord.z, sz); g.chcolor(); if((state & 1) != 0) g.image(ol, Coord.z, sz); else g.image(sl, Coord.z, sz); if((state & 2) != 0) g.image(or, Coord.z, sz); else g.image(sr, Coord.z, sz); }
5
public static void main(String[] args) { Game game = new Game(); game.setVisible(true); game.setResizable(false); }
0
private void registerListener(Object o) { Class<?> clazz = o.getClass(); Method [] methods = clazz.getDeclaredMethods(); for (Method m : methods) { if (m.isAnnotationPresent(EventCallback.class)){ EventCallback cb = (EventCallback) m.getAnnotation(EventCallback.class); if (cb.ignore()) continue; String signal = cb.signal(); if (cb.signal().equals("")){ signal = methodNameToSignal(m.getName()); } if (signal == null) { System.err.println("Signal not found for method : "+m); continue; } connectSignal(signal, findLocalMethod(m.getName()), cb.when()); } else if (m.getName().startsWith("on")){ String signal = methodNameToSignal(m.getName()); connectSignal(signal, findLocalMethod(m.getName()), CONNECT_BEFORE); } } }
7
public boolean isNumeric() { return (this == BYTE || this == SHORT || this == INTEGER || this == LONG || this == FLOAT || this == DOUBLE); }
5
public List<TopicObj> getTopicTable(PreparedStatement pre, boolean join) { List<TopicObj> items = new LinkedList<TopicObj>(); try { ResultSet rs = pre.executeQuery(); if (rs != null) { while (rs.next()) { TopicObj item = new TopicObj(); item.setTopicId(rs.getInt("topic_id")); item.setName(rs.getString("name")); item.setFileName(rs.getString("filename")); item.setPath(rs.getString("path")); item.setObjId(rs.getInt("obj_id")); if(join){ item.setObjName(rs.getString("obj_name")); } items.add(item); } } } catch (Exception ex) { ex.printStackTrace(); } return items; }
4
protected AbstractDefinition(Method method) throws DaoGenerateException { // 如果不传入method,则表示子类会自己根据需要,延迟初始化 if (method != null) { initDefinition(method); } }
1
public CheckResultMessage check15(int day) { int r1 = get(33, 5); int c1 = get(34, 5); int r2 = get(36, 5); int c2 = get(37, 5); BigDecimal b = new BigDecimal(0); if (checkVersion(file).equals("2003")) { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); b = getValue(r2 + 1 + day, c2 + 13, 9).add( getValue(r2 + 1 + day, c2 + 15, 9)).add( getValue(r2 + 1 + day, c2 + 17, 9)); if (0 != getValue(r1 + 2, c1 + 1 + day, 8).compareTo(b)) { return error("支付机构汇总报表<" + fileName + ">系统未增加银行已增加未达账项余额:" + day + "日错误"); } } catch (Exception e) { } } else { try { in = new FileInputStream(file); xWorkbook = new XSSFWorkbook(in); b = getValue1(r2 + 1 + day, c2 + 13, 9).add( getValue1(r2 + 1 + day, c2 + 15, 9)).add( getValue1(r2 + 1 + day, c2 + 17, 9)); if (0 != getValue1(r1 + 2, c1 + 1 + day, 8).compareTo(b)) { return error("支付机构汇总报表<" + fileName + ">系统未增加银行已增加未达账项余额:" + day + "日错误"); } } catch (Exception e) { } } return pass("支付机构汇总报表<" + fileName + ">系统未增加银行已增加未达账项余额:" + day + "日正确"); }
5
private void directionOrThrow(String direct) { boolean dire = direct.equals(UNDIRECTED) || direct.equals(DIRECTED); if (!dire) try { throw new IOException( "No Direction Found at first line of given File!"); } catch (IOException e) { } }
3
public final boolean method53(int i, Interface14 interface14) { anInt4994++; if (!(interface14 instanceof Class126)) return false; Class126 class126_3_ = (Class126) interface14; if (((Class126) this).anInt4991 != ((Class126) class126_3_).anInt4991) return false; if (i <= 50) return true; if (((Class126) this).anInt4992 != ((Class126) class126_3_).anInt4992) return false; if (((Class126) this).anInt4989 != ((Class126) class126_3_).anInt4989) return false; if ((((Class126) class126_3_).anInt4993 ^ 0xffffffff) != (((Class126) this).anInt4993 ^ 0xffffffff)) return false; if ((((Class126) this).anInt4982 ^ 0xffffffff) != (((Class126) class126_3_).anInt4982 ^ 0xffffffff)) return false; if (((Class126) this).anInt4981 != ((Class126) class126_3_).anInt4981) return false; if (!((Class126) class126_3_).aBoolean4990 != !((Class126) this).aBoolean4990) return false; return true; }
9
private static void startSession() { Session session = Session.getInstance(true); Pair<BigInteger, BigInteger> privateKeys = session.getPrivateKey(); System.out.println(""); System.out.println("Private key x: " + privateKeys.getFirst()); System.out.println("Private key y: " + privateKeys.getSecond()); System.out.println(""); System.out.println("Please introduce message to sign:"); String text = null; while (text == null) { try { text = (new BufferedReader(new InputStreamReader(System.in))) .readLine(); } catch (IOException e) { e.printStackTrace(); } } Pair<BigInteger, BigInteger> signature = DSA.sign(true, text, session.getGlobalKeyG(), session.getGlobalKeyP(), session.getGlobalKeyQ(), privateKeys.getFirst()); System.out.println("Signature (r,s): (" + signature.getFirst() + ", " + signature.getSecond() + ")"); System.out.println(""); System.out.println("Do you want to verify a message?"); System.out.println(" 1.Yes (y)"); System.out.println(" 2.No (press enter)"); String alg = null; try { alg = (new BufferedReader(new InputStreamReader(System.in))) .readLine(); } catch (IOException e) { e.printStackTrace(); } switch (alg) { case "y": verifyMessage(); break; default: System.out.println("Bye!"); System.exit(1); break; } }
4
final void method2964(byte i, OggPacket oggpacket) { anInt8990++; if ((((Class348_Sub23) this).anInt6868 ^ 0xffffffff) > -4) { int i_7_ = aVorbisInfo9006.headerIn(aVorbisComment9002, oggpacket); if (i_7_ < 0) throw new IllegalStateException(String.valueOf(i_7_)); if (((Class348_Sub23) this).anInt6868 == 2) { if (aVorbisInfo9006.channels > 2 || (aVorbisInfo9006.channels ^ 0xffffffff) > -2) throw new RuntimeException(String.valueOf(aVorbisInfo9006 .channels)); aDSPState8993 = new DSPState(aVorbisInfo9006); aVorbisBlock9000 = new VorbisBlock(aDSPState8993); aClass163_8994 = new Class163(aVorbisInfo9006.rate, Class22.anInt339); aClass348_Sub16_Sub2_8995 = new Class348_Sub16_Sub2(aVorbisInfo9006.channels); } } else { if (aVorbisBlock9000.synthesis(oggpacket) == 0) aDSPState8993.blockIn(aVorbisBlock9000); float[][] fs = aDSPState8993.pcmOut(aVorbisInfo9006.channels); aDouble9005 = aDSPState8993.granuleTime(); if (aDouble9005 == -1.0) aDouble9005 = (double) ((float) anInt9001 / (float) aVorbisInfo9006.rate); aDSPState8993.read(fs[0].length); anInt9001 += fs[0].length; Class348_Sub42_Sub4 class348_sub42_sub4 = aClass348_Sub16_Sub2_8995 .method2838(fs[0].length, aDouble9005, 1401320384); AbstractKeyboardListener.method2699(16383, (((Class348_Sub42_Sub4) class348_sub42_sub4) .aShortArrayArray9518), fs); for (int i_8_ = 0; i_8_ < aVorbisInfo9006.channels; i_8_++) ((Class348_Sub42_Sub4) class348_sub42_sub4) .aShortArrayArray9518[i_8_] = aClass163_8994.method1268(-56, (((Class348_Sub42_Sub4) class348_sub42_sub4) .aShortArrayArray9518[i_8_])); aClass348_Sub16_Sub2_8995.method2835(class348_sub42_sub4, 30700); } if (i > -91) method2961((byte) -106); }
9
public static void main(String... args) { int[] array = {-1, 12, 34, 123, 435, 9876, 0}; sort(array); for (int i = 0; i < array.length; i++) { System.out.println(array[i]); } }
1
public StringBuilder save() { StringBuilder data = new StringBuilder(); data.append(totalText.getText().substring(0, totalText.getText().indexOf(' '))); for(int x = 0; x<swingTimes.length; x++) { data.append(";" + swingTimes[x]); } data.append(System.getProperty("line.separator")); int i = 0; if(maxDir != 0 && maxFrame != 0) { for(int x = 0; x<hitboxes.length / maxDir; x++) { for(int y = 0; y<hitboxes.length / maxFrame; y++) { data.append(hitboxes[i].x + ";" + hitboxes[i].y + ";" + hitboxes[i].width + ";" + hitboxes[i].height + ";"); i++; } data.deleteCharAt(data.lastIndexOf(";")); data.append(System.getProperty("line.separator")); } } data.append("<BREAK>" + System.getProperty("line.separator")); return data; }
5
public String kertaaTama(int index){ String palautettava = ""; if (tila==KertausmaatinTila.TYHJA) { palautettava += kerrattavat.get(index)[0]; //näytä kanji tila = KertausmaatinTila.KANJI; } else if (tila == KertausmaatinTila.KANJI) { palautettava = kerrattavat.get(index)[1]; //näytä ääntämys tila = KertausmaatinTila.KANA; } else if (tila == KertausmaatinTila.KANA) { palautettava = kerrattavat.get(index)[1] + " " + kerrattavat.get(index)[2]; //näytä yhä ääntämys ja lisää suomennos tila = KertausmaatinTila.SUOMI; } return palautettava; }
3
@Override public boolean isLessThan(CardInterface card, int trump) { boolean retval; if (this.value == 0) { // fool will never get the trick if it wasn't the first card played if (card.getValue() == 0) { retval = false; } else { retval = true; } } else if (this.value == CardNames.getCardsPerNation() - 1) { // wizard on table, no other trick possible retval = false; } else if (card.getValue() == CardNames.getCardsPerNation() - 1) { // first wizard gets the trick retval = true; } else if (card.getNation() == trump) { retval = handleNewTrumpLaid(card, trump); } else if (card.getNation() == this.nation) { retval = handleSameNationLaid(card); } else { retval = false; } LOG.debug(String.format("%s is lower than %s (%s is Trump): %s", this.toString(), card.toString(), CardNames.getNationName(trump), retval)); return retval; }
6
public HashMap<String, Object> Match(String rank, String name, boolean strict, boolean verbose, Map<String, String> taxonomy) { String urlString = "http://api.gbif.org/v1/species/match?verbose=true"; URL url; URLConnection conn; InputStream is; if(strict) urlString += "&strict=true"; // urlString += "&verbose=" + (verbose? "true" : "false"); if(taxonomy.containsKey("kingdom")) urlString += "&kingdom=" + taxonomy.get("kingdom"); try { urlString += "&name=" + URLEncoder.encode(name, "UTF-8"); } catch (UnsupportedEncodingException ex) { System.out.println(ex.getMessage()); } try { url = new URL(urlString); conn = url.openConnection(); is = conn.getInputStream(); JsonFactory jsonFactory = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(jsonFactory); TypeReference<HashMap<String,Object>> typeRef = new TypeReference<HashMap<String,Object>>() {}; HashMap<String,Object> o = mapper.readValue(is, typeRef); return o; } catch (MalformedURLException ex) { System.out.println(ex.getMessage()); } catch (IOException ex) { System.out.println(ex.getMessage()); } return null; }
5
private boolean testEventListEquality(boolean ignoreMachine, List<Event> firstEvents, List<Event> secondEvents) { if(firstEvents.size() != secondEvents.size()) { return false; } for(int i=0; i<firstEvents.size(); i++) { if(!eventAreEqual(ignoreMachine, firstEvents.get(i), secondEvents.get(i))) { return false; } } return true; }
3
private void compute() { double[] weights = model.getWeights(); double wscale = model.getWscale(); // Unlike the C++ code in sgd, we would like to be RAII assert (u == null && b == null); int nPos = sequence.length(); u = new double[nPos][numLabels]; for (int pos = 0; pos < nPos; ++pos) { // For each feature from the sequence at position pos for (Offset offset : sequence.getOffsetsForU(pos)) { int l = offset.index; for (int y = 0; y < numLabels; ++y, ++l) { // Really tentative. Right now weights is actually // a matrix of FVxL, which is why this looks funny // This is the total score for outcome y at position pos for unigram features double acc = weights[l] * offset.value; u[pos][y] += acc; } } CollectionsManip.scaleInplace(u[pos], wscale); } // First dimension is the last position // Second dimension is label // Third is the last label b = new double[nPos-1][numLabels][numLabels]; for (int pos = 0; pos < nPos-1; ++pos) { for (Offset offset : sequence.getOffsetsForB(pos)) { int l = offset.index; for (int yi = 0; yi < numLabels; ++yi) { for (int yj = 0; yj < numLabels; ++yj, ++l) { double acc = weights[l] * offset.value; b[pos][yi][yj] += acc; } } } CollectionsManip.scaleInplace(b[pos], wscale); } }
8
public int getTopX(){if(dir=='u'||dir=='d')return x-17; return x-30;}
2
private static void readFilename(FileSystem fileSystem, String file, byte[] cmp) throws TestFailedException { FileHandle handle; try { handle = fileSystem.openFile(file, true, true); } catch (PathNotFoundException e) { throw new TestFailedException(e); } catch (AccessDeniedException e) { throw new TestFailedException("You have claimed that the file system is not read only", e); } catch (NotAFileException e) { throw new TestFailedException(file + " should be a file", e); } byte[] testBuffer = new byte[cmp.length]; ByteBuffer buf = ByteBuffer.wrap(testBuffer); int read = fileSystem.read(handle, buf, 0); if (read != cmp.length) throw new TestFailedException("Reading of " + file + " at position 0 failed. Should read " + cmp.length + " bytes, actual: " + read); try { byteArrayCompare(cmp, testBuffer); } catch (IOException e) { throw new TestFailedException("Reading of " + file + " at position 0 failed", e); } byte[] testBuffer2 = new byte[cmp.length - 4]; ByteBuffer buffer2 = ByteBuffer.wrap(testBuffer2); read = fileSystem.read(handle, buffer2, 4); if (read != cmp.length - 4) throw new TestFailedException("Reading of " + file + " at position 0 failed. Should read " + (cmp.length - 4) + " bytes, actual: " + read); byte[] cmp2 = new byte[cmp.length - 4]; System.arraycopy(cmp, 4, cmp2, 0, cmp2.length); try { byteArrayCompare(cmp2, testBuffer2); } catch (IOException e) { throw new TestFailedException("Reading of " + file + " at position 4 failed", e); } try { fileSystem.close(handle); } catch (DriveFullException e) { throw new TestFailedException(e); } }
8
private static void buildIndex(String dataFile) { System.out.println("Building Index ... "); String indexFile = dataFile + ".idx"; try { StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new FileReader(dataFile)); String line = null; String tmp = null; long offset = 0; long chrSize = 0; long chrOffset = 0; int lineLength = 0; boolean isFirst = true; while ((line = br.readLine()) != null) { offset += (line.length() + EXTRA); if (line.length() <= 0) continue; if (line.charAt(0) == ';') continue; if (line.charAt(0) == '>') { if (!isFirst) { // if (tmp.compareTo(chr) == 0) { // globalOffset = chrOffset; // charPerLine = lineLength; // } sb.append(tmp); sb.append("\t"); sb.append(Long.toString(chrSize)); sb.append("\t"); sb.append(Long.toString(chrOffset)); sb.append("\t"); sb.append(Long.toString(lineLength)); sb.append("\t"); sb.append(Long.toString(lineLength + EXTRA)); sb.append("\t"); sb.append(ENDOFLINE); indexMap.put( tmp, new String[] { Long.toString(chrOffset), Long.toString(lineLength) }); chrSize = 0; chrOffset = 0; lineLength = 0; } isFirst = false; lineLength = 0; int pos = line.indexOf(' '); if (pos == -1) pos = line.length(); tmp = line.substring(1, pos); chrOffset = offset; } else { chrSize += line.length(); if (lineLength < line.length()) lineLength = line.length(); } } // if (tmp.compareTo(chr) == 0) { // globalOffset = chrOffset; // charPerLine = lineLength; // } sb.append(tmp); sb.append("\t"); sb.append(Long.toString(chrSize)); sb.append("\t"); sb.append(Long.toString(chrOffset)); sb.append("\t"); sb.append(Long.toString(lineLength)); sb.append("\t"); sb.append(Long.toString(lineLength + EXTRA)); sb.append("\t"); sb.append(ENDOFLINE); br.close(); BufferedWriter bw = new BufferedWriter(new FileWriter(indexFile)); // bw.append(Integer.toString(charPerLine)); // bw.append("\n"); bw.append(sb.toString()); bw.close(); } catch (FileNotFoundException e) { System.err.println("Data file not found."); System.err.println("Abort!"); System.exit(1); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
9
@Override public void actionPerformed(ActionEvent e) { if(time == 7) t.stop(); System.out.println(); time++; for(Line line : l) line.split(); repaint(); }
2
public static void modifyType(ArrayList<Journal> journalList, JournalTypes journalTypes) { boolean singleMove; if (journalList.size() == 1) { singleMove = true; } else { int option = JOptionPane.showConfirmDialog(null, getBundle("BusinessActions").getString("APPLY_SAME_TYPE_FOR_ALL_JOURNALS"), getBundle("BusinessActions").getString("ALL"), JOptionPane.YES_NO_OPTION); singleMove = (option == JOptionPane.YES_OPTION); } if (singleMove) { Object[] types = journalTypes.getBusinessObjects().toArray(); int nr = JOptionPane.showOptionDialog(null, getBundle("BusinessActions").getString("CHOOSE_NEW_TYPE"), getBundle("BusinessActions").getString("CHANGE_TYPE"), JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, types, null); if(nr != JOptionPane.CANCEL_OPTION && nr != JOptionPane.CLOSED_OPTION){ for(Journal journal : journalList) { journal.setType((JournalType) types[nr]); } } } else { for(Journal journal : journalList) { Object[] types = journalTypes.getBusinessObjects().toArray(); int nr = JOptionPane.showOptionDialog(null, getBundle("BusinessActions").getString("CHOOSE_NEW_TYPE_FOR")+" " + journal.getName(), getBundle("BusinessActions").getString("CHANGE_TYPE"), JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, types, journal.getType()); if(nr != JOptionPane.CANCEL_OPTION && nr != JOptionPane.CLOSED_OPTION){ journal.setType((JournalType) types[nr]); } } } }
8
void checkModify() throws RuntimeException { if (isFrozen()) { String msg = getName() + " class is frozen"; if (wasPruned) msg += " and pruned"; throw new RuntimeException(msg); } wasChanged = true; }
2
public void setTytul(String tytul) { this.tytul = tytul; }
0
public ArrayList<Integer> getPathTo(Node target) { if(getShortestPathTo(target) == INFINITY) return null; else { // System.out.println("From " + source + " to " + target); int p = target.getId(); ArrayList<Integer> result = new ArrayList<>(); result.add(p); do{ p = pred[p]; result.add(p); }while(p != source.getId()); Collections.reverse(result); return result; } }
2
public void checkCollision() { for(int y = 0; y <mg.getMapSize().getY(); y++){ for(int x = 0; x <mg.getMapSize().getX(); x++){ if(mg.getCol()[x][y]){//Ends loop if not collision square if(player.getColRect().intersects(new Rectangle(mg.getTileSize().getX()*x, mg.getTileSize().getY()*y, mg.getTileSize().getX()*x+mg.getTileSize().getX(), mg.getTileSize().getY()*y+mg.getTileSize().getY()))){ Log.msg("Collision @ "+x+" "+y); } } } } }
4
public byte[] post(String url, Map<String, String> postParams) throws HttpException { int numRetries = retry ? maxRetries : 1; HttpPost httppost = null; List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); if (postParams != null && !postParams.isEmpty()) { for (Map.Entry<String, String> param : postParams.entrySet()) { nameValuePairs.add(new BasicNameValuePair(param.getKey(), param .getValue())); } } for (int i = 0; i < numRetries; i++) { try { httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httppost); StatusLine status = response.getStatusLine(); int statusCode = status.getStatusCode(); if (statusCode >= 300) { throw new HttpException(status.getReasonPhrase()); } HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toByteArray(entity); } return null; } catch (HttpException he) { httppost.abort(); throw he; } catch (Exception e) { httppost.abort(); } } // tried max times and errored, throw exception throw new HttpException("POST error: " + url + ", attempts:" + numRetries); }
9
@Override public void show() { Auction a = null; System.out.println(name + ", type in the required information for a new auction item." + "\n"); System.out.println("Name of product:"); try { productName = br.readLine(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Description of product:"); try { description = br.readLine(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Price of product:"); try { String stringToInt = br.readLine(); price = Integer.parseInt(stringToInt); } catch (Exception e) { System.out.println("The input wasn't a number or was out of bounds try again."); } System.out.println("Input expiration date of item up for bid"); try { String stringDate = br.readLine(); date = sdfc.parse(stringDate); // stringDate.parse(); } catch (Exception e) { Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_YEAR, 7); date = c.getTime(); System.out.println("This should have triggered:"+date); } // try{ // } // catch(Exception e){ // // a.timeLeftInMillis(); // } System.out.println("Enter total number of bids."); try{ String stringToInt = br.readLine(); bids = Integer.parseInt(stringToInt); } catch(Exception e){ System.out.println("Not a valid number try again."); } int id = as.searches.size()+1; a = new Auction(id, productName, description, price, bids, date); as.create(a); System.out.println(name + ", " + productName + " has been added to the auction." + "\n"); }
5
private void reconnect() { if (this.reconnecting) return; final Manager self = this; this.attempts++; if (attempts > this._reconnectionAttempts) { logger.fine("reconnect failed"); this.emitAll(EVENT_RECONNECT_FAILED); this.reconnecting = false; } else { long delay = this.attempts * this.reconnectionDelay(); delay = Math.min(delay, this.reconnectionDelayMax()); logger.fine(String.format("will wait %dms before reconnect attempt", delay)); this.reconnecting = true; final Future timer = this.reconnectScheduler.schedule(new Runnable() { @Override public void run() { EventThread.exec(new Runnable() { @Override public void run() { logger.fine("attempting reconnect"); self.emitAll(EVENT_RECONNECT_ATTEMPT, self.attempts); self.emitAll(EVENT_RECONNECTING, self.attempts); self.open(new OpenCallback() { @Override public void call(Exception err) { if (err != null) { logger.fine("reconnect attempt error"); self.reconnecting = false; self.reconnect(); self.emitAll(EVENT_RECONNECT_ERROR, err); } else { logger.fine("reconnect success"); self.onreconnect(); } } }); } }); } }, delay, TimeUnit.MILLISECONDS); this.subs.add(new On.Handle() { @Override public void destroy() { timer.cancel(false); } }); } }
3
@Override public Properties getOutputProperties() { Properties properties = new Properties(); properties.put(NAME, getName()); properties.put(Balances.LEFTNAME, leftName); properties.put(Balances.RIGHTNAME, rightName); properties.put(Balances.LEFTTOTALNAME, leftTotalName); properties.put(Balances.RIGHTTOTALNAME, rightTotalName); properties.put(Balances.LEFTRESULTNAME, leftResultName); properties.put(Balances.RIGHTRESULTNAME, rightResultName); ArrayList<String> leftTypesString = new ArrayList<>(); for(AccountType type:leftTypes){ leftTypesString.add(type.getName()); } properties.put(Balances.LEFTTYPES, Utils.toString(leftTypesString)); ArrayList<String> righttTypesString = new ArrayList<>(); for(AccountType type:rightTypes){ righttTypesString.add(type.getName()); } properties.put(Balances.RIGHTTYPES, Utils.toString(righttTypesString)); return properties; }
2
@Override public boolean equals(Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } PlayerData playerData = (PlayerData) o; if(id != playerData.id) { return false; } if(!name.equals(playerData.name)) { return false; } return true; }
5
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UsersSubscribeHashtags that = (UsersSubscribeHashtags) o; if (hashtagId != that.hashtagId) return false; if (userId != that.userId) return false; return true; }
5
public static final boolean fullDharokEquipped(Player player) { int helmId = player.getEquipment().getHatId(); int chestId = player.getEquipment().getChestId(); int legsId = player.getEquipment().getLegsId(); int weaponId = player.getEquipment().getWeaponId(); if (helmId == -1 || chestId == -1 || legsId == -1 || weaponId == -1) return false; return ItemDefinitions.getItemDefinitions(helmId).getName() .contains("Dharok's") && ItemDefinitions.getItemDefinitions(chestId).getName() .contains("Dharok's") && ItemDefinitions.getItemDefinitions(legsId).getName() .contains("Dharok's") && ItemDefinitions.getItemDefinitions(weaponId).getName() .contains("Dharok's"); }
7
@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 TaxonObservationFilterElement)) { return false; } TaxonObservationFilterElement other = (TaxonObservationFilterElement) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
5
@Override public Comment getComment(int id) { /* * gets a comment we a specific ID */ Comment comment = null; Session session = null; try { session = factory.openSession(); session.beginTransaction(); comment = (Comment) session.get(Comment.class, id); session.getTransaction().commit(); } catch (HibernateException e) { if (session != null) { session.getTransaction().rollback(); } } finally { if (session != null) { session.close(); } } return comment; }
3
@Test @SuppressWarnings({"unused", "null"}) public void testRecommendation() throws Exception { String filename = Common.DATASET_FILENAME; // First concept : a data model holds all the data. // Instantiate here, a file based data model. DataModel dataModel = null; // Second concept : a similarity allows to compare things, like user. // Instantiate here, the default pearson correlation similarity (ie unweighted). UserSimilarity userSimilarity = null; // Third concept : a neighborhood is a selection (ie subset) of things, like user. // Instantiate here, a neighborhood selecting at best the 2 nearest users. UserNeighborhood neighborhood = null; // Fourth concept : the recommender uses everything above do to the real recommendation. // Instantiate here, a generic user based recommender. UserBasedRecommender recommender = null; // Do a actual recommendation and print the results. List<RecommendedItem> recommendedItems = recommender.recommend(1, 100); for (RecommendedItem recommendedItem : recommendedItems) { System.out.println(recommendedItem); } // Observe by adding one recommendation to the datafile // the recommendation will not be displayed anymore // ie if a highly relevant item was not rated, it would be recommended }
1
public static void insert(String eDatabase, String table, byte[] etuple, String VALUES){ Connection gCon = null; // general connection to MYSQL Connection eCon = null; // connection to database Statement eStatement = null; // statements for the eDatabase try{ // Register JDBC driver Class.forName(DBConfig.driver); // Connect and initialize statements for General MYSQL and eDatabase System.out.println("Connecting to MYSQL..."); gCon = DriverManager.getConnection(DBConfig.url, DBConfig.user, DBConfig.password); eCon = DriverManager.getConnection(DBConfig.url + eDatabase, DBConfig.user, DBConfig.password); eStatement = eCon.createStatement(); if (!DatabaseProcess.checkDBExists(gCon,eDatabase)) { Exception e = new Exception("Requested database "+eDatabase+" doesn't exist"); throw(e); } String query = "INSERT INTO "+table + " VALUES(?,"+VALUES+");"; PreparedStatement ps = eCon.prepareStatement(query); ps.setBytes(1, etuple); ps.executeUpdate(); //eStatement.executeUpdate("INSERT INTO "+table + " VALUES(?,"+VALUES+");"); // Handle possible errors }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ e.printStackTrace(); }finally{ //finally block used to close resources try{ if((eStatement!=null)) { eStatement.close(); } }catch(SQLException se2){ }// nothing we can do try{ if(eCon !=null || gCon != null ) { eCon.close(); gCon.close(); } } catch(SQLException se){ se.printStackTrace(); } } System.out.println("Goodbye!"); }
8
private JSONWriter end(char mode, char c) throws JSONException { if (this.mode != mode) { throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); } this.pop(mode); try { this.writer.write(c); } catch (IOException e) { throw new JSONException(e); } this.comma = true; return this; }
3
private static String rmvPrePostSc(String target) { final char SC = '\''; // ' で囲まれていた場合のみ、削除する。 if(target.charAt(0) != SC || target.charAt(target.length() -1) != SC) return target; //前後1文字づつ削除 return StringUtils.substring(target, 1 , target.length() -1 ); }
2
private Color[] calculateColorPoints(int numberOfPoints, Point2D.Float startPoint, Point2D.Float endPoint, float t0, float t1) { // calculate the slope float m = (startPoint.y - endPoint.y) / (startPoint.x - endPoint.x); // calculate the y intercept float b = startPoint.y - (m * startPoint.x); // let calculate x points between startPoint.x and startPoint.y that // are on the line using y = mx + b. Color[] color; // if we don't have a y-axis line we can uses y=mx + b to get our points. if (!Float.isInfinite(m)) { float xDiff = (endPoint.x - startPoint.x) / numberOfPoints; float xOffset = startPoint.x; color = new Color[numberOfPoints + 1]; Point2D.Float point; for (int i = 0, max = color.length; i < max; i++) { point = new Point2D.Float(xOffset, (m * xOffset) + b); color[i] = calculateColour(colorSpace, point, startPoint, endPoint, t0, t1); xOffset += xDiff; } } // otherwise we have a infinite m and can just pick y values else { float yDiff = (endPoint.y - startPoint.y) / numberOfPoints; float yOffset = startPoint.y; color = new Color[numberOfPoints + 1]; Point2D.Float point; for (int i = 0, max = color.length; i < max; i++) { point = new Point2D.Float(0, yOffset); color[i] = calculateColour(colorSpace, point, startPoint, endPoint, t0, t1); yOffset += yDiff; } } return color; }
3
public void ouvrirEcriture(){ try{ // PrintWriter avec un auto flush sinon bloquant. // directement le flux logique. pf = new PrintWriter(s.getOutputStream(),true); // alternative // PrintStream ps = new PrintStream(s.getOutputStream()); }catch(IOException io){ System.out.println("echec de l'ouverture en ecriture"); io.printStackTrace(); } }
1
public boolean getBoolean(int index) throws JSONException { Object object = get(index); 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("JSONArray[" + index + "] is not a boolean."); }
6
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(frmConfima.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(frmConfima.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(frmConfima.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(frmConfima.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 frmConfima().setVisible(true); } }); }
6
public void updateColumnInfos() { if (this.getData() == null || this.getData().size() == 0) return; int colCnt = this.getData().get(0).length; initColInfoIfNull(colCnt); for (ColumnInfo ci : getColumnsInfos()){ ci.setMaxValue(Double.MIN_VALUE); ci.setMinValue(Double.MAX_VALUE); } for (int rowIdx = 0; rowIdx < this.getData().size(); rowIdx++) { double[] row = this.getData().get(rowIdx); for (int colIdx = 0; colIdx < row.length; colIdx++) { ColumnInfo ci = this.getColumnsInfos().get(colIdx); if (row[colIdx] < ci.getMinValue()) { ci.setMinValue(row[colIdx]); } if (row[colIdx] > ci.getMaxValue()) { ci.setMaxValue(row[colIdx]); } } } }
7
@Override public boolean equals(Object o) { if (o instanceof Pair<?, ?>) { Pair<?, ?> p = (Pair<?, ?>) o; return a.equals(p.a) && b.equals(p.b); } return false; }
8
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int length = Integer.parseInt(in.readLine()); String[] strArray = in.readLine().split(" "); int[] array1 = new int[length]; int[] array2 = new int[length]; for (int i = 0; i < strArray.length; i++) { array1[i] = Integer.parseInt(strArray[i]); array2[i] = Integer.parseInt(strArray[i]); } quickSort(array1); insertionSort(array2); System.out.println(qSwaps); System.out.println(iSwaps); System.out.println(iSwaps - qSwaps); for (int i = 0; i < array1.length; i++) { System.out.print(array1[i] + " "); } System.out.println(); for (int i = 0; i < array2.length; i++) { System.out.print(array2[i] + " "); } System.out.println(); }
3
public static int RoomService(Client joueur) { int tempDette = 0; int choiceInt = -1; boolean wrong = false; System.out.println("Que voulez vous prendre?" + "\n pour de la nourriture tapez 1 (50€)" + "\n pour de la boisson tapez 2"); do { String choice = keyboard.nextLine(); try { choiceInt = Integer.parseInt(choice); if (choiceInt != 1 && choiceInt != 2) { throw new Exception("not 1, 2"); } wrong = false; } catch (Exception e) { System.out.println("Mauvaise valeur inseree"); } } while (wrong); switch (choiceInt) { case 1: prendreNourriture(joueur); tempDette += 50; break; case 2: tempDette += prendreBoisson(joueur); break; } return tempDette; }
6
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); switch (displayedToolIndex) { case 1: if (this.getComponentCount() == 0) { this.add(imageIcon); } imageIcon.setLocation(new Point((int)startPoint.getX()-12, (int)startPoint.getY()-12)); break; case 2: if (this.getComponentCount() > 0) { this.remove(imageIcon); } g.drawLine((int)startPoint.getX(), (int)startPoint.getY(), (int)endPoint.getX(), (int)endPoint.getY()); break; case 3: if (this.getComponentCount() > 0) { this.remove(imageIcon); } g.drawPolygon( new int[] {(int)startPoint.getX(), (int)endPoint.getX(),(int)endPoint.getX(),(int)startPoint.getX()}, new int[] {(int)startPoint.getY(),(int)startPoint.getY(), (int)endPoint.getY(),(int)endPoint.getY()}, 4); break; } }
6
public void updatePosition() { if (xPos < xDestination){ prevXPos = xPos; xPos++; } //xPos = xPos + 2; else if (xPos > xDestination){ prevXPos = xPos; xPos--; } //xPos = xPos - 2; if (yPos < yDestination){ prevYPos = yPos; yPos++; } //yPos = yPos + 2; else if (yPos > yDestination){ prevYPos = yPos; yPos--; //yPos = yPos - 2; } if (xPos == xDestination && yPos == yDestination) { if(xDestination == cookingXPos){ if(xPos != prevXPos && yPos != prevYPos){ prevXPos = xPos; prevYPos = yPos; agent.msgAnimationReady(); } } } }
9
public void solve(){ BoardState cState = sState; visitedList = new ArrayList<BoardState>(); frontierList = new LinkedBlockingQueue<BoardState>(); long startTime, endTime, totalTime; //for time keeping startTime = System.nanoTime(); while (cState != null && !cState.equals(eState)){ //stop if all nodes explored or found solution if (!visitedList.contains(cState)) { //expand node if not already expanded for (Direction d : Direction.values()) { frontierList.add(new BoardState(cState, d)); } visitedList.add(cState); //add to explored list nodesExpanded++; } cState = frontierList.poll(); //get new node from frontier } endTime = System.nanoTime(); totalTime = endTime - startTime; if (cState == null) { System.out.println("Could not find solution after expanding " + nodesExpanded + " nodes. Searched for " + totalTime*1E-6 + "ms."); } else { Display out = new Display(); System.out.println("Solution found after expanding "+ nodesExpanded + " nodes. Searched for " + totalTime*1E-6 + "ms. Depth: " + cState.getDepth()); System.out.println(out.solutionToString(cState)); } }
5
public boolean canMove(Square[][] board, char c) { LocationSet[] legalMoves = legalMoves(board, c); for (int x = 0; x < legalMoves.length; x++) { for (int y = 0; y < legalMoves[x].destinationNum(); y++) { if (legalMoves[x].getIndex(y) != null) { return true; } } } return false; }
3
public static ArrayList<Stock> QueryMultiple(ArrayList<String> codes) { URL url; InputStream is = null; BufferedReader br; String line; Stock tmp; ArrayList<Stock> sList = new ArrayList<>(); String urlStr = ""; for (int i = 0; i < codes.size() - 1; i++) { urlStr += codes.get(i) + ","; } urlStr += codes.get(codes.size() - 1); urlStr = "http://finance.yahoo.com/d/quotes.csv?s=" + urlStr + "&f=nsl1"; try { url = new URL(urlStr); is = url.openStream(); // throws an IOException br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { tmp = parseStock(line); if (tmp != null) { sList.add(tmp); } } } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException ioe) { } } return sList; }
6
@Override public boolean equals(Object o) { if (o == null || !(o instanceof Book)) return false; final Book book = (Book) o; return Objects.equal(isbn, book.isbn) && Objects.equal(title, book.title) && authors.containsAll(book.authors) && book.authors.containsAll(authors) && Objects.equal(description, book.description) && Objects.equal(pages, book.pages) && Objects.equal(publishDate, book.publishDate); }
8
public void method() throws Exception { System.out.println("From ExceptionTest1 method !"); throw new Exception(); }
0
public Country getCountry(int id) { Country cnt = null; Connection con = null; Statement stmt = null; try { DBconnection dbCon = new DBconnection(); Class.forName(dbCon.getJDBC_DRIVER()); con = DriverManager.getConnection(dbCon.getDATABASE_URL(), dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD()); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("Select * From country Where cnt_id=" + id); if (rs.next()) { cnt = new Country(); cnt.setId(rs.getInt(1)); cnt.setCode(rs.getString(2)); cnt.setName(rs.getString(3)); } } catch (SQLException | ClassNotFoundException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } finally { try { if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } } return cnt; }
5
static int mapRejectReason(int state) { switch (state) { case 1: return ACTIVE_BID_CHANGED; case 11: case 12: case 13: case 14: return BID_NOT_IMPROVED; case 15: case 16: return PRICE_NOT_BEAT; default: return state; } }
7
private static void logic(long delta){ for (ListIterator<Asteroid> iterator = asteroidList.listIterator(0); iterator.hasNext();) { Asteroid asteroid = iterator.next(); asteroid.update(delta); if(asteroid.getHP() <= 0){ iterator.remove(); if(asteroid.getScale()>0.5f) try { iterator.add(new Asteroid("mainSpriteSheet", "2DShader", 19, 43, 32, 30, (int)(asteroid.getScale()), asteroid.getX(), asteroid.getY(), new Vector2f(asteroid.getVelocityVector().x/2, asteroid.getVelocityVector().y*2))); iterator.add(new Asteroid("mainSpriteSheet", "2DShader", 19, 43, 32, 30, (int)(asteroid.getScale()), asteroid.getX(), asteroid.getY(), new Vector2f(asteroid.getVelocityVector().x*2, asteroid.getVelocityVector().y/2))); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } player1.update(delta); for (Iterator<Bullet> iterator = bulletList.iterator(); iterator.hasNext();) { Bullet bullet = iterator.next(); bullet.update(delta); if (bullet.getDecayed()) iterator.remove(); } PhysicsEngine.physicsUpdate(delta); }
6
public void setFood(int food) { if (food >= 0) { this.food = food; } }
1
private void OpenActionPerformed( final java.awt.event.ActionEvent evt) { int returnVal = fileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { // Init TextArea to "" jTextArea1.setText(""); jTextArea2.setText(""); // Catch the current file path path = fileChooser.getSelectedFile().toString(); path = path.replace("\\", "/"); File file = fileChooser.getSelectedFile(); try { input = Methods.getFileAsString(path); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (file.getAbsolutePath().endsWith(".xml")) { jTextArea1.setText(input); try { JDOMConverter jdc = new JDOMConverter(path); jdc.convert(); output = jdc.toString(2); jTextArea2.setText(output); } catch (Exception e) { e.printStackTrace(); } } else if (file.getAbsolutePath().endsWith(".json")) { jTextArea2.setText(input); try { JSONConverter jsc = new JSONConverter(path); jsc.convert(); output = jsc.toString(2); /*output = converterToXML.convertToXML( path, false);*/ jTextArea1.setText(output); } catch (Exception e) { e.printStackTrace(); } } else { jTextArea1.setText("Select a XML file"); jTextArea2.setText("Select a JSON file"); } } else { System.out.println("File access cancelled by user."); } }
6
public boolean isLeaf() { return left == null && right == null; }
1