text
stringlengths
14
410k
label
int32
0
9
public String getMessage() { if (!specialConstructor) { return super.getMessage(); } StringBuffer expected = new StringBuffer(); int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected.append("..."); } expected.append(eol).append(" "); } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += " " + tokenImage[tok.kind]; retval += " \""; retval += add_escapes(tok.image); retval += " \""; tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected.toString(); return retval; }
9
private void handleInvocation( RemoteMethodEntry entry, Object[] arguments ) throws Exception { RemoteMethod remoteMethod = entry.remoteMethod; Match readMatch = remoteMethod.readMatch(); int readStates = remoteMethod.readStates(); if (readMatch.isMatch( readStates, getStates() ) || !protocol.notifyReadBlock(this, readMatch, readStates, getStates())) { if (entry.listener instanceof HasClient) { ((HasClient)entry.listener).setCurrentClient( this ); } entry.method.invoke( entry.listener, arguments ); } }
3
public void renderMap(EntityPlayer par1EntityPlayer, RenderEngine par2RenderEngine, MapData par3MapData) { for (int var4 = 0; var4 < 16384; ++var4) { byte var5 = par3MapData.colors[var4]; if (var5 / 4 == 0) { this.intArray[var4] = (var4 + var4 / 128 & 1) * 8 + 16 << 24; } else { int var6 = MapColor.mapColorArray[var5 / 4].colorValue; int var7 = var5 & 3; short var8 = 220; if (var7 == 2) { var8 = 255; } if (var7 == 0) { var8 = 180; } int var9 = (var6 >> 16 & 255) * var8 / 255; int var10 = (var6 >> 8 & 255) * var8 / 255; int var11 = (var6 & 255) * var8 / 255; if (this.gameSettings.anaglyph) { int var12 = (var9 * 30 + var10 * 59 + var11 * 11) / 100; int var13 = (var9 * 30 + var10 * 70) / 100; int var14 = (var9 * 30 + var11 * 70) / 100; var9 = var12; var10 = var13; var11 = var14; } this.intArray[var4] = -16777216 | var9 << 16 | var10 << 8 | var11; } } par2RenderEngine.createTextureFromBytes(this.intArray, 128, 128, this.bufferedImage); byte var15 = 0; byte var16 = 0; Tessellator var17 = Tessellator.instance; float var18 = 0.0F; GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.bufferedImage); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glDisable(GL11.GL_ALPHA_TEST); var17.startDrawingQuads(); var17.addVertexWithUV((double)((float)(var15 + 0) + var18), (double)((float)(var16 + 128) - var18), -0.009999999776482582D, 0.0D, 1.0D); var17.addVertexWithUV((double)((float)(var15 + 128) - var18), (double)((float)(var16 + 128) - var18), -0.009999999776482582D, 1.0D, 1.0D); var17.addVertexWithUV((double)((float)(var15 + 128) - var18), (double)((float)(var16 + 0) + var18), -0.009999999776482582D, 1.0D, 0.0D); var17.addVertexWithUV((double)((float)(var15 + 0) + var18), (double)((float)(var16 + 0) + var18), -0.009999999776482582D, 0.0D, 0.0D); var17.draw(); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glDisable(GL11.GL_BLEND); par2RenderEngine.bindTexture(par2RenderEngine.getTexture("/misc/mapicons.png")); Iterator var19 = par3MapData.playersVisibleOnMap.iterator(); while (var19.hasNext()) { MapCoord var20 = (MapCoord)var19.next(); GL11.glPushMatrix(); GL11.glTranslatef((float)var15 + (float)var20.centerX / 2.0F + 64.0F, (float)var16 + (float)var20.centerZ / 2.0F + 64.0F, -0.02F); GL11.glRotatef((float)(var20.iconRotation * 360) / 16.0F, 0.0F, 0.0F, 1.0F); GL11.glScalef(4.0F, 4.0F, 3.0F); GL11.glTranslatef(-0.125F, 0.125F, 0.0F); float var21 = (float)(var20.field_28217_a % 4 + 0) / 4.0F; float var23 = (float)(var20.field_28217_a / 4 + 0) / 4.0F; float var22 = (float)(var20.field_28217_a % 4 + 1) / 4.0F; float var24 = (float)(var20.field_28217_a / 4 + 1) / 4.0F; var17.startDrawingQuads(); var17.addVertexWithUV(-1.0D, 1.0D, 0.0D, (double)var21, (double)var23); var17.addVertexWithUV(1.0D, 1.0D, 0.0D, (double)var22, (double)var23); var17.addVertexWithUV(1.0D, -1.0D, 0.0D, (double)var22, (double)var24); var17.addVertexWithUV(-1.0D, -1.0D, 0.0D, (double)var21, (double)var24); var17.draw(); GL11.glPopMatrix(); } GL11.glPushMatrix(); GL11.glTranslatef(0.0F, 0.0F, -0.04F); GL11.glScalef(1.0F, 1.0F, 1.0F); this.fontRenderer.drawString(par3MapData.mapName, var15, var16, -16777216); GL11.glPopMatrix(); }
6
protected void onUpdateGameOver() { long time = System.currentTimeMillis(); int lap = ( int ) ( time - _gameOverStart ); if ( lap > GAME_OVER_DRAW_TIME ) { if ( !_isGameOverRev ) { if ( _gameOverPos.size() == GRID_Y ) { _isGameOverRev = true; _grid = new short[ GRID_Y ][ GRID_X ]; _gridColor = new short[ GRID_Y ][ GRID_X ]; } else { List< Integer > pos = new ArrayList<Integer>(); for ( int i = 0; i < GRID_X; i++ ) { pos.add( i ); } _gameOverPos.add( pos ); } } else { if ( _gameOverPos.size() == 0 ) { moveSq( SceneGame.SQ_START ); _pressEnterStart = System.currentTimeMillis(); } else { _gameOverPos.remove( _gameOverPos.size() - 1 ); } } _gameOverStart = time; } }
5
private void workloadClassify() { createRequestList(); Random rd=new Random(seed); double reservedMean=0.75; double ondemandMean=0.5; double spotMean=0.25; double std=0.3; int n=this.requestList.size(); int reservedCnt=17000; int spotCnt=120000; SortedMap<Double, RequestType> sm=new TreeMap<Double, RequestType>(); int k=0; RequestType type=RequestType.ONDEMAND; while(k<n) { double mean=0; RequestType typeCur=type; if(k<=reservedCnt) { mean=reservedMean; type=RequestType.RESERVED; }else if(k>reservedCnt && k<=(reservedCnt+spotCnt)){ mean=spotMean; type=RequestType.SPOT; }else{ mean=ondemandMean; type=RequestType.ONDEMAND; } double key=rd.nextGaussian()*std+mean; while(sm.get(key)!=null ||key<0||key>1) { key=rd.nextGaussian()*std+mean; } k++; sm.put(key, typeCur); } // Mapping int i=0; for(RequestType t: sm.values()) { requestList.get(i).setType(t); addNewWorkloadtoList(requestList.get(i)); i++; } //split those reserved request which have the duration greater than reservation length (in the simulation is 1 year) splitRequestOutLength(); //// resort list based on the initial time Collections.sort(getReserved(), new Comparator<ReservedRequest>() { @Override public int compare(ReservedRequest e1, ReservedRequest e2) { return new Long(e1.getInitialTime()).compareTo(new Long(e2 .getInitialTime())); // sort based on the start time } }); Collections.sort(getOndemand(), new Comparator<OndemandRequest>() { @Override public int compare(OndemandRequest e1, OndemandRequest e2) { return new Long(e1.getInitialTime()).compareTo(new Long(e2 .getInitialTime())); // sort based on the start time } }); Collections.sort(getSpot(), new Comparator<SpotRequest>() { @Override public int compare(SpotRequest e1, SpotRequest e2) { return new Long(e1.getInitialTime()).compareTo(new Long(e2 .getInitialTime())); // sort based on the start time } }); this.list=generateReservation(); Collections.sort(this.list, new Comparator<ReservationWorkload>() { @Override public int compare(ReservationWorkload r1,ReservationWorkload r2) { return new Long(r1.getStartTime()).compareTo(new Long(r2.getStartTime())); } }); }
8
public CompositeGateClass(String gateName, HDLTokenizer input, PinInfo[] inputPinsInfo, PinInfo[] outputPinsInfo) throws HDLException { super(gateName, inputPinsInfo, outputPinsInfo); partsList = new Vector(); internalPinsInfo = new Vector(); connections = new ConnectionSet(); isInputClocked = new boolean[inputPinsInfo.length]; isOutputClocked = new boolean[outputPinsInfo.length]; readParts(input); Graph graph = createConnectionsGraph(); // runs the topological sort, starting from the "master parts" node, // which connects to all the parts. This will also check for circles. Object[] topologicalOrder = graph.topologicalSort(partsList); if (graph.hasCircle()) throw new HDLException("This chip has a circle in its parts connections"); // create the partsOrder array, by taking from the topologicalOrder // only the Integer objects, which represent the parts. partsOrder = new int[partsList.size()]; int counter = 0; for (int i = 0; i < topologicalOrder.length; i++) { if (topologicalOrder[i] instanceof Integer) partsOrder[counter++] = ((Integer)topologicalOrder[i]).intValue(); } // for each input pin, check if there is a path in the graph to an output pin // (actually to the "master output", which all outputs connect to). // If there is, the input is not clocked. Otherwise, it is. for (int i = 0; i < inputPinsInfo.length; i++) isInputClocked[i] = !graph.pathExists(inputPinsInfo[i], outputPinsInfo); // for each output pin, check if there is a path in the graph from any input pin // (actually from the "master input", which connects to all inputs) to this output pin. // If there is, the output is not clocked. Otherwise, it is. for (int i = 0; i < outputPinsInfo.length; i++) isOutputClocked[i] = !graph.pathExists(inputPinsInfo, outputPinsInfo[i]); }
5
@Override public Auctioneer getAuctionHouse(String chain, String areaNameOrBranch) { for (final Auctioneer C : auctionHouseList) { if((C.auctionHouse().equalsIgnoreCase(chain)) &&(C.auctionHouse().equalsIgnoreCase(areaNameOrBranch))) return C; } final Area A=findArea(areaNameOrBranch); if(A==null) return null; for (final Auctioneer C : auctionHouseList) { if((C.auctionHouse().equalsIgnoreCase(chain)) &&(getStartArea(C)==A)) return C; } return null; }
7
public ArrayList<Bank> withBanks() { if (!Constants.Banking) { return null; } Connection conn = null; ResultSet rs = null; PreparedStatement ps = null; ArrayList<Bank> banks = new ArrayList<Bank>(); try { conn = iConomy.getiCoDatabase().getConnection(); ps = conn.prepareStatement("SELECT * FROM " + Constants.SQLTable + "_BankRelations WHERE account_name = ?"); ps.setString(1, this.name); rs = ps.executeQuery(); while (rs.next()) { Bank bank = new Bank(rs.getInt("bank_id")); banks.add(bank); } } catch (Exception e) { return null; } finally { if (ps != null) try { ps.close(); } catch (SQLException ex) { } if (conn != null) try { conn.close(); } catch (SQLException ex) { } } return banks; }
7
@Override public ArrayList<seed> move(ArrayList<Pair> treelist, double width, double length, double s) { // TODO Auto-generated method stub ArrayList<seed> seedlist = new ArrayList<seed>(); for (double i = distowall; i < width - distowall; i = i + distoseed) { for (double j = distowall; j < length - distowall; j = j + distoseed) { Random random = new Random(); seed tmp; if (random.nextInt(2) == 0) tmp = new seed(i, j, false); else tmp = new seed(i, j, true); boolean add = true; for (int f = 0; f < treelist.size(); f++) { if (distance(tmp, treelist.get(f)) < distotree) { add = false; break; } } if (add) { seedlist.add(tmp); } } } System.out.printf("seedlist size is %d", seedlist.size()); return seedlist; }
6
public JPanel Menu() { JPanel buttons = new JPanel(); buttons.setLayout(new GridBagLayout()); buttons.setBackground(new Color(255, 231, 186)); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(5,5,5,5); ImageIcon titleImg = new ImageIcon("ui/title.png"); JLabel title = new JLabel(titleImg); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; buttons.add(title,gbc); JButton newGame = new JButton("New Game"); newGame.setFont(new Font("Arial", Font.BOLD, 17)); gbc.gridx = 0; gbc.gridy = 2; gbc.gridwidth = 2; gbc.fill = GridBagConstraints.HORIZONTAL; newGame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if(settings == null) { new SudokuGUI(1, main); } else { new SudokuGUI(settings.difficulty, main); settings.setVisible(false); if(highscores != null) { highscores.setVisible(false); } } setVisible(false); } }); buttons.add(newGame,gbc); JButton continueGame = new JButton("Continue Game"); continueGame.setFont(new Font("Arial", Font.BOLD, 17)); gbc.gridx = 0; gbc.gridy = 4; gbc.gridwidth = 2; gbc.fill = GridBagConstraints.HORIZONTAL; continueGame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { File f = new File("save.txt"); if(f.exists()) { System.out.println("Continue"); ContinueFileParser c = new ContinueFileParser(f); try { c.Parse(); } catch (FileNotFoundException e) { e.printStackTrace(); } new SudokuGUI(c.getBoardArray(), c.getDifficulty(), c.getEditableArray(), main, c.getTime()); dispose(); } } }); buttons.add(continueGame,gbc); JButton setting = new JButton("Settings"); setting.setFont(new Font("Arial", Font.BOLD, 17)); gbc.weightx = 0.5; gbc.gridx = 0; gbc.gridy = 8; gbc.gridwidth = 1; gbc.fill = GridBagConstraints.HORIZONTAL; setting.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (settings!=null) { settings.setVisible(true); } else { settings = new SettingGUI(); } } }); buttons.add(setting,gbc); JButton hiscore = new JButton("High Score"); hiscore.setFont(new Font("Arial", Font.BOLD, 17)); gbc.weightx = 0.5; gbc.gridx = 1; gbc.gridy = 8; gbc.gridwidth = 1; hiscore.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (highscores!=null) { highscores.setVisible(true); } else { highscores = new HighGUI(); } } }); buttons.add(hiscore,gbc); return buttons; }
6
private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed int linhaSelecionada = -1; linhaSelecionada = tabela.getSelectedRow(); if (linhaSelecionada >= 0) { int idUsuario = (int) tabela.getValueAt(linhaSelecionada, 0); FuncionarioController fc = new FuncionarioController(); if (fc.remove(idUsuario)) { JOptionPane.showMessageDialog(null, "Funcionário excluido com sucesso."); modelo.removeRow(linhaSelecionada); } } else { JOptionPane.showMessageDialog(null, "Nenhuma linha foi selecionada."); } }//GEN-LAST:event_btExcluirActionPerformed
2
@Override public void setImages() { if (waitImage == null) { File imageFile = new File(Structure.baseDir + "topdownturret40.png"); try { waitImage = ImageIO.read(imageFile); } catch (IOException e) { e.printStackTrace(); } } if (attackImage == null) { File imageFile = new File(Structure.baseDir + "turretFire.png"); try { attackImage = ImageIO.read(imageFile); } catch (IOException e) { e.printStackTrace(); } } if (upgradeImage == null) { File imageFile = new File(Structure.baseDir + "topdownTurret40.png"); try { upgradeImage = ImageIO.read(imageFile); } catch (IOException e) { e.printStackTrace(); } } if (explodeImage == null) { File imageFile = new File(Structure.baseDir + "explosion-sprite40.png"); try { explodeImage = ImageIO.read(imageFile); } catch (IOException e) { e.printStackTrace(); } } }
8
public void run() { while(!isClosed) { final String currentSpin = spinLabel.getText(); final String nextSpin; if(currentSpin.equals("-")) nextSpin = "\\"; else if(currentSpin.equals("\\")) nextSpin = "|"; else if(currentSpin.equals("|")) nextSpin = "/"; else nextSpin = "-"; if(getOwner() != null) { getOwner().runInEventThread(new Action() { public void doAction() { spinLabel.setText(nextSpin); } }); } try { Thread.sleep(100); } catch(InterruptedException e) {} } }
6
private static void printLines(String name, InputStream ins) throws Exception { String line = null; BufferedReader in = new BufferedReader(new InputStreamReader(ins)); while ((line = in.readLine()) != null) { System.out.println(name + " " + line); } }
1
protected SoundPlayer() { this.buffers = new ArrayList<SoundPlay>(); AudioFormat format = new AudioFormat(44100.0f, 16, 2, true, false); try { this.line = AudioSystem.getSourceDataLine(format); this.line.open(format, 4410); this.line.start(); this.thread = new Thread(new Runnable() { @Override public void run() { SoundPlayer self = SoundPlayer.this; while(true) { int bytesToWrite = self.line.available(); if(bytesToWrite > 0) { byte[] bytes = self.readBytes(bytesToWrite); int writtenBytes = 0; while(writtenBytes != bytesToWrite) { writtenBytes += self.line.write(bytes, writtenBytes, bytesToWrite - writtenBytes); } } try { Thread.sleep(1); } catch(InterruptedException e) { throw new RuntimeException(e); } } } }); this.thread.setDaemon(true); this.thread.start(); } catch(Exception e) { throw new RuntimeException(e); } }
5
private void runTestsWithApexQuery() throws ConnectionException { List<String> declaredClassNames = this.getClassNames(); List<String> classList = new ArrayList<String>(); System.out.println("Declared classes to test: "); for (String f : declaredClassNames) { System.out.println("\t" + f); } List<String> classNames = this.getAllClassNames(); for (String className : classNames) { if (declaredClassNames.contains(className) || className.matches(this.m_regex)) { System.out.println("Matched " + className + ". Added."); classList.add(className); } } RunTestsRequest runTestsRequest = new RunTestsRequest(); runTestsRequest.setClasses(classList.toArray(new String[classList .size()])); runTestsRequest.setAllTests(false); System.out.println("Sending runTests request..."); try { RunTestsResult result = this.salesforceConnection() .getApexConnection().runTests(runTestsRequest); System.out.println("Total Tests Run: " + result.getNumTestsRun()); System.out .println("Total Tests Failed: " + result.getNumFailures()); System.out.println("Total Time: " + result.getTotalTime()); for (RunTestFailure t : result.getFailures()) { System.out.println(t.getClass() + "." + t.getMethodName()); System.out.println(t.getMessage()); System.out.println(t.getStackTrace()); System.out.println("*****************"); } if (result.getNumFailures() > 0 && this.failOnError()) { System.exit(1); } } catch (ConnectionException e) { e.printStackTrace(); } }
8
@SuppressWarnings("unchecked") private Item[] resize(int newCapacity) { Item[] t = (Item[]) new Object[newCapacity]; for (int i = 0, j = front; i < size(); i++, j = (j + 1) % N) t[i] = q[j]; N = newCapacity; front = 0; return t; }
1
public T get(int index) { if (index < 0 || index >= this.size) throw new IndexOutOfBoundsException(); // handle ask for head if (index == 0) return this.head.data; // handle ask for tail else if (index == this.size - 1) return this.tail.data; // handle ask for anything else else { MyNode current = this.head; for (int i = 0; i < index; i++) current = current.next; return current.data; } }
5
@Override public Connection open() { if (initialize()) { try { this.connection = DriverManager.getConnection("jdbc:sqlite:" + sqlFile.getAbsolutePath()); return this.connection; } catch (SQLException e) { this.writeError("SQLite exception on initialize " + e, true); } } return this.connection; }
2
public void update() throws ModelException { TradeKingForeman foreman = new TradeKingForeman(); XMLHandler handler = new XMLHandler(); try { response = foreman.makeAPICall(OrdersBuilder.preview(a.getId(), b.build().toString(), ResponseFormat.XML)); } catch (ForemanException | UtilityException e) { throw new ModelException("Make API Call", e); } try { map = handler.parseMarketOrderPreview(response.toString()); } catch (UtilityException e) { throw new ModelException("", e); } }
2
@Override public int getGrade(Node<T> n) { if (!(n instanceof BinaryNodePS)) { throw new DifferentNodeTypesException(); } else if (isSafe() && !contains(n)) { throw new NodeNotFoundException(); } int grade = 0; BinaryNodePS<T> bn = (BinaryNodePS<T>) n; if (bn.getLeft() != null) { grade++; } if (bn.getRight() != null) { grade++; } return grade; }
5
public void register(PeerActivityListener listener) { this.listeners.add(listener); }
0
public Vector<Affix> getAffixList(String _type){ StringBuffer sb= new StringBuffer(""); String str = null; String[] affixlist; FileReader reader = null; try { if(_type.equals("p")){ reader = new FileReader("g:\\prefixlist.txt"); }else if(_type.equals("s")){ reader = new FileReader("g:\\suffixlist.txt"); } BufferedReader br = new BufferedReader(reader); while((str = br.readLine()) != null) { affixlist = str.split(","); if(_type.equals("p")){ prefixList.add(new Affix(new Integer(affixlist[0]).intValue(),new Integer(affixlist[4]).intValue(),affixlist[5],affixlist[6],affixlist[3],affixlist[1])); }else if(_type.equals("s")){ suffixList.add(new Affix(new Integer(affixlist[0]).intValue(),new Integer(affixlist[4]).intValue(),affixlist[5],affixlist[6],affixlist[3],affixlist[1])); } } br.close(); reader.close(); //System.out.println("Affix list generated, prefix length is:"+ prefixList.size()+", suffix length is: "+suffixList.size()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(_type.equals("p")){ return prefixList; }else if(_type.equals("s")){ return suffixList; } return null; }
8
private void predictClassLabel(Instance instance){ int size = model.getNumOfClassLabel(); double[] likelihoods = new double[size]; for(int i=0;i<size;i++){ likelihoods[i] = (double)1; } for(int i=0;i<size;i++){ double[][][] attributes_likelihoods = model.getAttributes_likelihoods(); for(int j=0;j<attributes_likelihoods.length;j++){ String votes[] = instance.getVotes(); if(votes[j].equals("1")){ if(attributes_likelihoods[j][i][0] != 0){ likelihoods[i] *= attributes_likelihoods[j][i][0]; //System.out.println(Math.log(attributes_likelihoods[j][i][0])); } else{ System.out.println("error!! P(C) = 0"); } } else if(votes[j].equals("-1")){ if(attributes_likelihoods[j][i][1] != 0){ likelihoods[i] *= attributes_likelihoods[j][i][1]; //System.out.println(Math.log(attributes_likelihoods[j][i][1])); } else{ System.out.println("error!! P(C) = 0"); } } else{ } } double[] classLabelLikelihoods = model.getClassLabel_likelihoods(); likelihoods[i] *= classLabelLikelihoods[i]; //System.out.println(likelihoods[i]); } double max = likelihoods[0]; int max_index = 0; for(int i=1;i<11;i++){ if(likelihoods[i] > max){ max = likelihoods[i]; max_index = i; } } instance.setPartyByClassLabel(max_index+1); //System.out.println("===================="); }
9
public static int uniquePaths3(int m, int n) { m--; n--; double numerator = 1; double denominator1 = 1; double denominator2 = 1; int i = 1; while (true) { if (i <= m + n) numerator *= i; else break; i++; } i = 1; while (true) { if (i <= m) denominator1 *= i; else break; i++; } i = 1; while (true) { if (i <= n) denominator2 *= i; else break; i++; } double result = numerator / denominator1 / denominator2; return (int) result; }
6
@Override public Boolean modificarCliente(TCliente cliente) throws Exception { Statement query = null; Connection connection = null; String contenido_query = "UPDATE Clientes SET DNI='" + cliente.getDNI() + "', Nombre='" + cliente.getNombre() + "', Apellidos='" + cliente.getApellidos()+ "', Fecha_nacimiento=STR_TO_DATE('" + cliente.getFechaNacimiento() + "', '%d/%m/%Y'), Tipo='"; String final_query = "WHERE id_cliente = " + cliente.getId() + ";"; try { connection = (Connection) TransactionManager.obtenerInstanacia().getTransaccion().getResource(); query = connection.createStatement(); } catch (SQLException e) { throw new SQLException("No se ha podido realizar la conexión con la base de datos. \nEs posible que haya olvidado crear o iniciar la transacción" + "\nError: " + e.getMessage()); } //Diferenciar tipo de cliente if (cliente.getClass().equals(TClienteNormal.class)) { TClienteNormal temp = (TClienteNormal) cliente; contenido_query += "normal' " + final_query; try { //por si acaso estuviera en la otra tabla, lo borro query.executeUpdate("DELETE FROM ClientesVip where id_cliente = '" + cliente.getId() + "';"); } catch (SQLException ex) { throw new SQLException("No se ha podido modificar cliente \nError: " + ex.getMessage()); } try { //Si ha cambiado de VIP a Normal, hay que darlo de alta, en otro caso, saltará al cath query.executeUpdate("INSERT INTO ClientesNormales(id_cliente,QuiereVip) VALUES('" + temp.getId() + "', '" + temp.isQuierevip() + "');" ); } catch (SQLException ex) { try { query.executeUpdate("UPDATE ClientesNormales SET QuiereVip='" + temp.isQuierevip() + "');"); } catch (SQLException ex2) { throw new Exception("Error al actualizar en la tabla de clientes normales\nError: " + ex2.getMessage()); } } } else { TClienteVip temp = (TClienteVip) cliente; contenido_query += "VIP' " + final_query; try { //por si acaso estuviera en la otra tabla, lo borro query.executeUpdate("DELETE FROM ClientesNormales where id_cliente = '" + cliente.getId() + "';"); } catch (SQLException ex) { throw new SQLException("No se ha podido modificar cliente \nError: " + ex.getMessage()); } try { //Si ha cambiado de VIP a Normal, hay que darlo de alta, en otro caso, saltará al cath query.executeUpdate("INSERT INTO ClientesVip(id_cliente,Financiacion) VALUES('" + temp.getId() + "', '" + temp.getFinanciacion()+ "');" ); } catch (SQLException ex) { try { query.executeUpdate("UPDATE ClientesVip SET Financiacion=" + temp.getFinanciacion() + ";"); } catch (SQLException ex2) { throw new Exception("Error al actualizar en la tabla de clientes VIP\nError: " + ex2.getMessage()); } } } System.out.println(contenido_query); query.executeUpdate(contenido_query); return false; }
8
private JSONWriter append(String string) throws JSONException { if (string == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(string); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); }
7
@Override public PropertyFilter getFilter(int index) throws IndexOutOfBoundsException { return (PropertyFilter) filters.get(index); }
0
@Override public int hashCode() { int hash = 3; hash = 61 * hash + (this.id != null ? this.id.hashCode() : 0); hash = 61 * hash + (this.login != null ? this.login.hashCode() : 0); hash = 61 * hash + (this.password != null ? this.password.hashCode() : 0); hash = 61 * hash + (this.credentials != null ? this.credentials.hashCode() : 0); hash = 61 * hash + (this.messagesesToUser != null ? this.messagesesToUser.hashCode() : 0); hash = 61 * hash + (this.messagesesFromUser != null ? this.messagesesFromUser.hashCode() : 0); hash = 61 * hash + (this.mapses != null ? this.mapses.hashCode() : 0); return hash; }
7
public boolean addTrainerToBooking(Connection conn) throws SQLException { boolean success = false; int trainerID = 0; String sportsType = sb.getSportsType(); String SQLString1 = "select trainerID from trainer where sportstype = ?"; String SQLString2 = "insert into trainerBooking values(?,to_timestamp(?))"; PreparedStatement statement1 = null; PreparedStatement statement2 = null; try { statement1 = conn.prepareStatement(SQLString1); statement1.setString(1, sportsType); ResultSet rs = statement1.executeQuery(); while (rs.next()) { trainerID = rs.getInt(1); } } catch (Exception e) { System.out.println("Fail in BookingMapper - addTrainerToBooking #1"); System.out.println(e.getMessage()); } try { statement2 = conn.prepareStatement(SQLString2); statement2.setInt(1, trainerID); statement2.setString(2, sb.getSportsDate()); success = true; statement2.executeUpdate(); } catch (Exception e) { System.out.println("Fail in Booking Mapper - AddTrainerToBooking #2"); System.out.println(e.getMessage()); } return success; }
3
@Test public void resolve() { int N=20; long [][] grid=new long[N+1][N+1]; for(int i=N;i>=0;i--){ for(int j=N;j>=0;j--){ if(i==N||j==N){ grid[i][j]=1; }else{ grid[i][j]=grid[i][j+1]+grid[i+1][j]; } } } print(grid[0][0]); }
4
private void playString(String playString) { //@TODO code to play string in morse :) //@TODO NEEDS ByteArrayOutpuStream to work! ByteArrayOutputStream bbout = new ByteArrayOutputStream(); char charToPlay; int sLength = playString.length(); byte[] playWave = new byte[32]; //byte[] constructionOne; //ByteBuffer bb = ByteBuffer.wrap(playWave); for (int step = 0; step < sLength; step++) { charToPlay = playString.charAt(step); if (charToPlay == ' ') { bbout.write(WavePackage.WaveTools.combineByteArray(playWave, this.elements.interWordSpacing), 0, elements.interWordSpacing.length); } else { if (this.elements.farnsworthSpacing) { //@TODO code to insert farnsworth spaced silence bbout.write(WavePackage.WaveTools.combineByteArray(playWave, this.elements.interCharacterFarnsworthPCM), 0, elements.interCharacterFarnsworthPCM.length); } else { try { bbout.write(WavePackage.WaveTools.combineByteArray(playWave, this.elements.interCharacterPCM)); } catch (IOException e) { System.err.println("e"); } //playWave = constructionOne; } } char toLower = Character.toLowerCase(charToPlay); String morseString = morseDict.morseDictionary.get(toLower); for (int x = 0; x < (morseString.length()); x++) { char ditOrDah = morseString.charAt(x); if (ditOrDah == '.') { try { bbout.write(WavePackage.WaveTools.combineByteArray(playWave, this.elements.ditElementPCM)); } catch (IOException e) { System.err.println(e); } } if (ditOrDah == '-') { try { bbout.write(WavePackage.WaveTools.combineByteArray(playWave, this.elements.dahElementPCM)); } catch (IOException e) { System.err.println(e); } } } } playWave = bbout.toByteArray(); byte[] header = WavePackage.WaveTools.createWaveHeaderForPcm(playWave, 16000, (short) 16); WavePackage.WaveTools.saveToWaveFile(header, "firstTest.wav"); WavePackage.PlayByteWaveAudio player = new WavePackage.PlayByteWaveAudio(header); }
9
@Override public boolean equals(Object obj) { Boolean totuus = false; if (obj instanceof OstosLista) { OstosLista toinen = (OstosLista)obj; if (this.size() <= toinen.size()) { OstosLista tmp = new OstosLista(this); for (int i = 0; i < toinen.size(); i++) { for (int j = 0; j < tmp.size(); j++) { Object a = toinen.get(i); Object b = tmp.get(j); // System.out.println("a: " + a); // System.out.println("b: " + b); if (a.equals(b)) { tmp.remove(a); } } } if (tmp.isEmpty()) { totuus = true; } } return totuus; } else { return totuus; } }
6
void initGame() { HexOperations.setXYasVertex(false); HexOperations.setHeight(HEXSIZE); HexOperations.setBorders(BORDERS); for (int i = 0; i < BSIZE; i++) { for (int j = 0; j < BSIZE; j++) { board[i][j] = EMPTY; } } //set up board here for (int i = 0; i < BSIZE; i++) { for (int j = 0; j < BSIZE; j++) { MapObject temp = Game.getMapObject(i, j); if (temp instanceof Worm) { board[i][j] = "W:" + temp.getWeight(); } if (temp instanceof Bacteria) { board[i][j] = "(B)"; } } } }
6
public String getJson() { try { /* Create a URL obj from strings */ url = new URL((QUERY_URL.concat(word)).replace(" ", "%20")); System.out.println(fullUrl); conn = url.openConnection(); // Get the response rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = ""; while ((line = rd.readLine()) != null) { json = json.concat(line); } rd.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } return json; }
3
public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Usuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Usuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Usuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Usuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { Usuarios dialog = new Usuarios(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
6
public WumpusPerception eventTurnLeft(AID hunterAID) { if(log.isLoggable(Logger.INFO)) log.log(Logger.INFO, "eventTurnLeft()"); Hunter hunter = getHunter(hunterAID); hunter = hunter.turnLeft(); int xCoord = hunter.getxCoord(); int yCoord = hunter.getyCoord(); WumpusPerception perception = getPerception(worldMap[xCoord][yCoord]); notifyHunterListListeners(); notifyWorldModelListeners(); return perception; }
1
public PisteTest() { }
0
public void startGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { Logger.getLogger(LoginScreen.class.getName()) .log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(LoginScreen.class.getName()) .log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(LoginScreen.class.getName()) .log(Level.SEVERE, null, ex); } catch (UnsupportedLookAndFeelException ex) { Logger.getLogger(LoginScreen.class.getName()) .log(Level.SEVERE, null, ex); } // Display the Login Page login.setVisible(true); }
4
private void processFiles( List<String> files ) { Parser parser = new Parser(); Table table = null; List<String> classNames = new ArrayList<String>(); for ( String file : files ) { table = parser.parse( file ); table.setPackage( basePkg ); if ( classNames.contains( table.getDomName() ) ) { throw new IllegalArgumentException( "This class name is used multiple times, " + table.getDomName() ); } classNames.add( table.getDomName() ); generateAll( table ); } ForeignKeyGenerator foreignKey = new ForeignKeyGenerator( Parser.getForeignKeyList(), Parser.getTableMap() ); foreignKey.createForeignKeys(); SessionFactoryGenerator sfg = new SessionFactoryGenerator( basePkg ); printPath( sfg.createSession() ); MybatisConfigGenerator mcg = new MybatisConfigGenerator( classNames, basePkg, databaseType ); printPath( mcg.createConfiguration() ); printPath( "sql/_CreateTables.sql" ); printPath( "sql/_AlterTables.sql" ); printPath( "sql/_DropTables.sql" ); System.out.println( "\nDone." ); }
2
public Subject(SubjectID primary, Node memberNode) throws XPathExpressionException { // Get the restrictions. this.restrictions = null; String restrictions = Utilities.getAttributeValue(memberNode, "restrictions"); if(!Utilities.isNullOrWhitespace(restrictions)) { this.restrictions = Restrictions.valueOf(restrictions); } // Decode the unique ids. this.ids = new ArrayList<SubjectID>(); this.ids.add(primary); NodeList idNodes = Utilities.selectNodes(memberNode, "./m:UniqueID", XMLLabels.STANDARD_NAMESPACES); for(int i = 0; i < idNodes.getLength(); ++i) { Node id = idNodes.item(i); String domain = Utilities.getAttributeValue(id, "domain"); if(domain != null) { Contributor contributor = Contributor.findContributor(domain); String idVal = id.getTextContent(); SubjectID sid = new SubjectID(contributor, idVal); if(!this.ids.contains(sid)) { this.ids.add(sid); } } } // Decode the name. this.name = new SubjectName(Utilities.selectSingleNode(memberNode, "./m:Name", XMLLabels.STANDARD_NAMESPACES)); // Address // Education // Certification // License // Disciplinary // Clinical Status // Occupation // Personal // Membership // Attachement // Modified Date // Xtensible // Other... XPath to all: // "./.[namespace-uri() != \"" + namespaces.get("m") + "\" & name()]" }
4
public Token next() throws IOException { String lexeme = ""; int value = 0; int count = 0; do { value = read(); if (value == EOF) { return Token.generate(Token.Kind.EOF, lineNumber, charPosition); } if (value == WS || value == TAB) { continue; } lexeme += (char) value; if ((lexeme + (char) nextChar).equals("//")) { while (!(nextChar == NL || nextChar == EOF || nextChar == ENTER)) { read(); } lexeme = ""; continue; } if (!Token.isToken(lexeme + (char) nextChar)) { return Token.generate(lexeme, lineNumber, charPosition - count); } ++count; } while (true); }
9
public void sendOrder() { //query the orders table by order number // ArrayList<Item> order = new ArrayList<Item>(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String commandArg = null; System.out.println("Please enter the name of the manufacturer."); String manu = ""; try { commandArg = br.readLine(); } catch (IOException ioe) { System.out.println("Error reading manufacturer. Exiting..."); System.exit(1); } manu = commandArg; System.out.println("Enter products in the form 'model_number quantity'. Type 'done' when finished"); boolean continueOrder = true; String productQuery = ""; ArrayList<String> products = new ArrayList<String>(); int productCounter = 0; while (continueOrder == true) { try { productQuery = br.readLine(); } catch (IOException ioe) { System.out.println("Error"); } if (!productQuery.equals("done")) { products.add(productQuery); productCounter++; } else continueOrder = false; } // System.out.println("oi"); for (int i = 0; i < productCounter; i++) { String[] parts = products.get(i).split(" "); String modNum = parts[0]; int qty = Integer.parseInt(parts[1]); Item item = new Item(modNum, qty); // System.out.println("hey"); order.add(item); // String qry = " " + parts[0] + "=" + "'" + parts[1] + "'" + " "; // queries.add(qry); } ExternalWorldInterface e_w_i = new ExternalWorldInterface(custConn); int random1 = (int)(Math.random()*9 + 1); int random2 = (int)(Math.random()*9 + 1); int random3 = (int)(Math.random()*9 + 1); int random4 = (int)(Math.random()*9 + 1); String shipid = "111" + random4 + random3 + random2 + random1; String SNinsert = "INSERT INTO ShippingNotice(shipID, manufacturer) VALUES ('" + shipid + "', '" + manu + "')"; Statement stm = null; ResultSet rs; try { stm = custConn.getConnection().createStatement(); rs = stm.executeQuery(SNinsert); } catch (Exception e) { System.out.println("Error inserting into ShippingNotice. Exiting"); System.exit(1); } //insert into shipped items for (int i = 0; i < productCounter; i++) { Item t = order.get(i); String SIinsert = "INSERT INTO ShippedItems(model_number, quantity, shipID) VALUES ('" + t.modNum + "', '" + t.qty + "', '" + shipid + "')"; try { // Statement stt = custConn.getConnection().createStatement(); rs = stm.executeQuery(SIinsert); System.out.println("inserted into shipped items"); } catch (Exception e) { System.out.println("Unable to insert into shipped items"); System.exit(1); } } System.out.println("Sent!"); System.out.println("ORDER SUMMARY"); System.out.println("Manufacturer: " + manu); for(int i = 0; i < productCounter; i++) { Item t = order.get(i); System.out.print("Item/Quantity: "); System.out.println(t.modNum + "/" + t.qty); } e_w_i.receiveShippingNotice(shipid, manu, order); e_w_i.receiveShipment(shipid); }
9
final public void setConfidence(int new_confidence) { throw new UnsupportedOperationException("setConfidence not implemented"); }
0
public static void log() { boolean full = larvikGaming.getConfig().getBoolean("Full-Logger", true); boolean info = larvikGaming.getConfig().getBoolean("Info-Logger", false); boolean warning = larvikGaming.getConfig().getBoolean("Warning-Logger", true); boolean severe = larvikGaming.getConfig().getBoolean("Severe-Logger", true); File log_lck = new File(log_file + ".lck"); File info_lck = new File(info_file + ".lck"); File warning_lck = new File(warning_file + ".lck"); File severe_lck = new File(severe_file + ".lck"); if (log_lck.exists()) { log_lck.delete(); } if (info_lck.exists()) { info_lck.delete(); } if (warning_lck.exists()) { warning_lck.delete(); } if (severe_lck.exists()) { severe_lck.delete(); } log.setLevel(Level.ALL); //Handler[] mcHandler = log.getHandlers(); //mcHandler[0].setLevel(Level.INFO); if (full) full(); if (info) info(); if (warning) warning(); if (severe) severe(); }
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Vak other = (Vak) obj; if (id != other.id) return false; return true; }
4
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; WordAttributes other = (WordAttributes) obj; if (color == null) { if (other.color != null) return false; } else if (!color.equals(other.color)) return false; if (startsWithPhrase != other.startsWithPhrase) return false; if (transport != other.transport) return false; return true; }
8
private void restoreBlogStatus() { try { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(statusFilename))); String line = null; while ((line = reader.readLine()) != null) { if (!line.contains("<article")) { continue; } HashMap<String, String> status = new HashMap<String, String>(); for (String attr : STATUS_NAME) { Pattern p = Pattern.compile(attr + "=\"(.+?)\""); Matcher m = p.matcher(line); while (m.find()) { status.put(attr, m.group(1)); } } articleStatus.add(status); } } finally { if (reader != null) { reader.close(); } } } catch (FileNotFoundException e) { syncBlogStatus(); } catch (IOException e) { e.printStackTrace(); } }
7
private void addState(SearchState state, int dist, int edgeDist) { int estimatedDist = dist + h.estimateCostToGoal(state); if (estimatedDist >= OO) return; SearchState oldState = stateSet.get(state); if (oldState == null) { stateSet.put(state, state); oldState = state; } if (state.prevState != null) oldState.backLinks.add(new BackLink(state.prevState, edgeDist, state.prevPieceIndex)); Integer curDist = stateDistMap.get(state); if (curDist == null || dist < curDist) { oldState.prevState = state.prevState; oldState.prevPieceIndex = state.prevPieceIndex; stateDistMap.put(oldState, dist); stateDistQueue.add(new StateDist(oldState, estimatedDist)); } }
5
private void loadFile() throws IOException { InputStream inp = new FileInputStream(inputFile); //InputStream inp = new FileInputStream("workbook.xlsx"); Workbook wb = new XSSFWorkbook(inp); Sheet sheet = wb.getSheetAt(0); int lastRowNum = sheet.getLastRowNum(); for (int i = 0; i <= lastRowNum; i++) { Row row = sheet.getRow(i); List<String> list = Lists.newLinkedList(); int lastCellNum = row.getLastCellNum(); for (int j = 0; j < lastCellNum; j++) { if (i == 0) { tabList.add(getValueFromCell(row.getCell(j))); } else { list.add(getValueFromCell(row.getCell(j))); } } if (i != 0) this.data.add(list); } inp.close(); }
4
public double reduceDamage(double damage){ double temp = damage - armorItem.getDefenseScore(); if(temp <0) temp = 0; return temp; }
1
* @return the id of the new version */ public int newVersion( String shortName, String longName, String group, short backup, boolean partial ) { short gId = findGroup( group ); if ( gId == 0 && group != null && group.length()> 0 ) { Group g = new Group( (short)0, group ); groups.add( g ); gId = (short)groups.size(); } versions.add( new Version(gId, (partial)?backup:Version.NO_BACKUP, shortName, longName) ); int vId = versions.size(); // now go through the graph, looking for any pair // containing the backup version and adding to it // the new version. Q: does that apply also to hints? if ( partial ) { for ( int i=0;i<pairs.size();i++ ) { Pair p = pairs.get( i ); if ( p.versions.nextSetBit(backup)==backup ) p.versions.set(vId); } } return vId; }
7
protected Hashtable<String, Object> communicateWithNeo4jServer(String json) throws SystemFailure { Hashtable<String, Object> responseData = null; HttpPost createNodePost = new HttpPost(_serverUrl); createNodePost.setHeader("Accept", "application/json; charset=UTF-8"); createNodePost.setHeader("Content-Type", "application/json"); StringEntity jsonEntity; try { jsonEntity = new StringEntity(json); } catch (UnsupportedEncodingException e) { throw new SystemFailure("communicateWithNeo4jServer - problem encoding json as a StringEntity:\n" + json, e); } createNodePost.setEntity(jsonEntity); String createNdFailStr = null; CloseableHttpResponse response = null; Exception err = null; try { response = _httpclient.execute(createNodePost); if (response.getStatusLine().getStatusCode() != 200) { createNdFailStr = "communicateWithNeo4jServer - request had non-200 response, request JSON:\n" + json + "\n\nReason:\n\n" + response.getStatusLine().getReasonPhrase(); // if there is a response entity, attach that to the message too HttpEntity entity = response.getEntity(); if (entity != null) { String errResponseStr = EntityUtils.toString(entity); createNdFailStr = createNdFailStr + ", response entity:\n" + errResponseStr; } //LOG.warn(createNdFailStr); } else { HttpEntity entity = response.getEntity(); if (entity != null) { String responseStr = EntityUtils.toString(entity); if (LOG.isDebugEnabled()) { LOG.debug("communicateWithNeo4jServer - response is:\n" + responseStr); } Gson gson = new Gson(); responseData = gson.fromJson(responseStr, Hashtable.class); } } } catch (Exception e) { //LOG.warn("sendCreateNodeJson - problem making create node request, JSON:\n" + json, e); err = e; } finally { try { response.close(); } catch (IOException e) { LOG.warn("sendCreateNodeJson - problem closing response", e); } } if (createNdFailStr != null) { throw new SystemFailure("communicateWithNeo4jServer - " + createNdFailStr); } if (err != null) { throw new SystemFailure("Exception thrown while communicating with neo4j", err); } return responseData; }
9
protected void buildDesc(Room room, int dir, String designDescription) { synchronized(("SYNC"+room.roomID()).intern()) { room=CMLib.map().getRoom(room); if(dir>=0) { Exit E=room.getExitInDir(dir); if((!E.isGeneric())&&(room.getRawExit(dir)==E)) { E=generify(E); room.setRawExit(dir,E); } E.setDescription(designDescription); CMLib.database().DBUpdateExits(room); } else { Room returnRoom = null; for(int d=0;d<Directions.NUM_DIRECTIONS();d++) { if(room.getRoomInDir(d)!=null) returnRoom=room.getRoomInDir(d); } room.setDescription(designDescription); if(room instanceof GridLocale) { ((GridLocale)room).clearGrid(returnRoom); ((GridLocale)room).buildGrid(); } CMLib.database().DBUpdateRoom(room); LandTitle T=CMLib.law().getLandTitle(room); if(T != null) T.updateLot(null); } } }
7
public void startupScan(Path directory) { String status = db.getConfig("startupScan"); // Check if user disabled the scan if(status != null && !status.equals("true")) { logger.info("Startup scan is disabled."); return; } for(File file : directory.toFile().listFiles()) { if(file.isDirectory()) { // Call itself recursively for directories startupScan(directory.resolve(file.toPath())); } else { // If the file doesn't already exist, we can just copy it over if(!FileOp.convertPath(file.toPath()).toFile().exists()) { Path targetDirectory = FileOp.convertPath(file.toPath()).getParent(); FileOp.copy(file.toPath(), targetDirectory); logger.info("Startup: Found new file " + file.toString()); } // The file does exist, so determine if the file has been changed. If it // hasn't, we need to create a revision for this file. else if(!FileOp.isEqual(file.toPath(), FileOp.convertPath(file.toPath()))) { // Create the diff Path diffFile = FileOp.createPatch(FileOp.convertPath(file.toPath()), file.toPath()); // Difference in file sizes long delta = FileOp.fileSize(file.toPath()) - FileOp.fileSize(FileOp.convertPath(file.toPath())); // Store the revision FileHistory fileHist = new FileHistory(file.toPath()); fileHist.storeRevision(diffFile, null, FileOp.fileSize(file.toPath()), delta); // Finally, copy the file over Path targetDirectory = FileOp.convertPath(file.toPath()).getParent(); FileOp.copy(file.toPath(), targetDirectory); logger.info("Startup: Found modified file " + file.toString()); } } } }
6
public static int[] solution(int N, int[] A) { int[] result = new int[N]; int maxCounter = 0; int inc = 0; for(int i = 0 ; i < A.length ; i++){ if(A[i] <= N){ if(result[A[i] - 1] < inc) { result[A[i] - 1] = inc; } result[A[i] - 1]++; if(result[A[i] - 1] > maxCounter){ maxCounter = result[A[i] - 1]; } } else if(A[i] == N + 1){ inc = maxCounter; } } for (int i = 0; i < result.length; i++) { if(result[i] < inc){ result[i] = inc; } } return result; }
7
public JSONWriter array() throws JSONException { if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { this.push(null); this.append("["); this.comma = false; return this; } throw new JSONException("Misplaced array."); }
3
public static void main(String[] args) throws IOException { CovertChannel cc = new CovertChannel(); boolean verbose = false; //used to determine whether we will create a log file // LOW and HIGH are constants defined in the SecurityLevel // class, such that HIGH dominates LOW. SecurityLevel low = SecurityLevel.LOW; SecurityLevel high = SecurityLevel.HIGH; //get file name as a string to pass with subject creation String filename = ""; if (args[0].equals("v")){ filename = args[1]; verbose = true; }else{ filename = args[0]; } // We add two subjects, one high and one low. cc.createSubject("hal", high, filename); cc.createSubject("lyle", low, filename); // lyle deletes hal's .out file, order is important FileInputStream inputstream = new FileInputStream(new File(filename)); File log = null; FileWriter writer = null; if (verbose){ log = new File("log"); if (log.exists()){ log.delete(); log = new File("log"); } writer = new FileWriter(log); } int inputByte = 0; int totalBits = 0; // long startTime = System.nanoTime(); while (inputstream.available() > 0){ inputByte = inputstream.read(); for (int i = 7; i > -1; --i){ int bit = (inputByte >> i) & 1; if (bit == 0) { cc.create("hal", "obj"); //write out to log if (verbose) writer.write("CREATE HAL OBJ\n"); } cc.create("lyle", "obj"); cc.write("lyle", "obj", 1); cc.read("lyle", "obj"); cc.destroy("obj"); //should pass subject to do a check cc.run(); //write out to log if (verbose){ writer.write("CREATE LYLE OBJ\n"); writer.write("WRITE LYLE OBJ 1\n"); writer.write("READ LYLE OBJ\n"); writer.write("DESTROY LYLE OBJ\n"); writer.write("RUN LYLE\n\n"); } ++totalBits; } } // long estimatedTime = System.nanoTime() - startTime; // System.out.println("Estimated Average Bandwidth (bits/ms): " + (totalBits / (estimatedTime / 1000000))); if (verbose) writer.close(); }
9
public static String analyzeMessage(UserNChatThread user, String chat){ String outputText = "null test"; if( !chat.equals("") ){ if( chat.charAt(0) == '/' ){ outputText = executeCommand(user, chat); }else{ outputText = chat; } } return outputText; }
2
public QuestionPanel() { setFocusable(false); questionTextArea = new SingleQuestionTextArea(); answerTextArea = new SingleQuestionTextArea(); BoxLayout boxLayout = new BoxLayout(this, BoxLayout.Y_AXIS); setLayout(boxLayout); add(questionTextArea); add(Box.createVerticalStrut(10)); add(answerTextArea); QuestionManager.getInstance().addListener(this); }
0
private static Point[][] get16PlayersPositions() { int maxPlayers = 16; Point[][] pos = new Point[8][128]; for(int i = 0; i < maxPlayers;i++ ){ pos [0][i] = new Point(0,2*i); } for(int i = 0; i < maxPlayers/2;i++ ){ pos [1][i] = new Point(2 ,1+4*i); } for(int i = 0; i < maxPlayers/4;i++ ){ pos [2][i] = new Point(4 ,3+8*i); } for(int i = 0; i < maxPlayers/8;i++ ){ pos [3][i] = new Point(6 ,7+16*i); } for(int i = 0; i < maxPlayers/16;i++ ){ pos [4][i] = new Point(8 ,15+32*i); } return pos; }
5
*/ private void getSpectrumForQuery(String searchName) { List<String> result = new ArrayList<String>(); try { DbAccessor.createConnection(); CompoundLogic compoundLogic = new CompoundLogic(); LOGGER.info("search records by keyword || " + searchName); List<Compound> compoundList = compoundLogic.getCompoundListByKeyword(searchName); DbAccessor.closeConnection(); for (Compound compound : compoundList) { String prefix = SiteUtil.getServerPrefixByRecordId(compound.getId()); result.add(String.format("%s\t%s\t%s", compound.getTitle(), compound.getId(), prefix)); } } catch (SQLException e) { LOGGER.error(e.getMessage(), e); return; } List<GuiDbTableRow> oGuiDbTableRows = new ArrayList<GuiDbTableRow>(); for (int i = 0; i < result.size(); i++) { String nameId = (String) result.get(i); String[] cutNameId = nameId.split("\t"); String index = String.valueOf(i + 1); String recordId = cutNameId[1]; String recordTitle = cutNameId[0]; String sitePrefix = cutNameId[2]; String contributor = SiteUtil.getSiteNameByRecordIdPrefix(sitePrefix); GuiDbTableRow guiDbTableRow = new GuiDbTableRow(index, recordId, recordTitle, contributor); oGuiDbTableRows.add(guiDbTableRow); } if (StringUtils.isBlank(searchName)) { for (GuiDbTableRow row : oGuiDbTableRows) { guiDbTableRowMap.put(row.getRecordId(), row); } } fillGuiDbTableData(oGuiDbTableRows); }
5
public int longestIncreasingSub(int[] arr) { int longestSSCount = 0; int currIndex = 0; int n = arr.length; int[] lis = new int[n]; int[] path = new int[n]; for (int i = 0; i < n; i++) { lis[i] = 1; path[i] = -1; } for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { if(arr[i] > arr[j] && (lis[j] + 1 > lis[i])){ lis[i] = lis[j] + 1; path[i] = j; } } if(lis[i] > longestSSCount) { longestSSCount = lis[i]; currIndex = i; } } int prevIndex = path[currIndex]; while(prevIndex >= 0){ System.out.print(arr[currIndex]+"\t"); prevIndex = path[currIndex]; currIndex = prevIndex; } return longestSSCount; }
7
public static void moveElementToHead(Vector someVector, int index) { // size is useful int size = someVector.size(); // validate parameters // also leave if element is already at the head if ((someVector == null) || (index <= 0) || (index >= size)) { return ; } // end if // grab the element to be moved Object theNewHead = someVector.get(index) ; // move everyone further headward one spot tailward for (int position = index - 1; position >= 0; position --) { someVector.set(position + 1, someVector.get(position)) ; } // end for // set the movee headmost someVector.set(0, theNewHead) ; // done return ; } // end method moveElementToTop
4
public String encrypt(String inputFileName, String key) throws Exception { SecretKeySpec tempKey = null; System.out.println("Encrypted File: " + inputFileName); FileInputStream inputStream = new FileInputStream(inputFileName); // create the output file after encryption add an extension .cheng File tmpFile = new File(inputFileName); String outFileName = this.saveDir.getAbsolutePath() + "/" + tmpFile.getName() + ".cheng"; FileOutputStream outputStream = new FileOutputStream(outFileName); // if user has put in the key, generate a key by the string that user // has put in if (key != null) { tempKey = this.generateKey(key); } else { // otherwise use defaultkey initialized before tempKey = FileEncryptor.defaultKey; } cypher.init(Cipher.ENCRYPT_MODE, tempKey); // read and write from inputfile to outputfile through a buffer bytes // this buff array could be improved by using PureBAOS class, but I // haven't fully // understand the GZIP mechanism // ***********************// // get help form Ru Peng student ID: G00307401 // I was used PureBAOS to create dynamic buffer before,but not work // **********************// byte[] b = new byte[20480]; while (inputStream.read(b) > 0) { outputStream.write(cypher.doFinal(b)); } inputStream.close(); outputStream.close(); System.out.println("To: " + outFileName); return outFileName; }
2
public static void main(String args[]) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); for (int N,t=1;(N=parseInt(in.readLine().trim()))!=0;t++) { String num=""; int cant=0; sb.append("Case ").append(t).append(":\n"); for(int i=0;i<N;i++) { String s=in.readLine().trim(); if(num.length()==0||Long.parseLong(num)+cant!=Long.parseLong(s)){ if(num.length()>1) { if(cant>1)sb.append(num).append("-").append(cota(num,cant)).append("\n"); else sb.append(num).append("\n"); } num=s;cant=1; } else cant++; } if(num.length()>1) { if(cant>1)sb.append(num).append("-").append(cota(num,cant)).append("\n"); else sb.append(num).append("\n"); } sb.append("\n"); } System.out.print(new String(sb)); }
8
public boolean AddUser(IrcUser user){ return Users.add(user);}
0
@PUT @Path("/modifyEvent") @Consumes(MediaType.APPLICATION_JSON) public Response modifyEvent(String jsonObject) { Gson gson = new GsonBuilder().setDateFormat(WS_DATE_PATTERN).create(); Event event = null; try { event = gson.fromJson(jsonObject, Event.class); } catch (JsonSyntaxException e1) { try { gson = new GsonBuilder().setDateFormat(JS_DATE_FORMAT).create(); event = gson.fromJson(jsonObject, Event.class); } catch (JsonSyntaxException e) { e.printStackTrace(); return makeCORS(Response.status(400)); } } EventMongoDAO mc = null; try { mc = EventMongoDAO.getInstance(); } catch (UnknownHostException e) { e.printStackTrace(); return makeCORS(Response.status(503)); } if (event.getId() != null ) { if(mc.exists(event.getId())){ mc.update(event); String toReturn = gson.toJson(event); return makeCORS(Response.ok().entity(toReturn)); } else { return makeCORS(Response.status(204)); } } else { return makeCORS(Response.status(400)); } }
5
public static Mask buildSobelMask(Direction d) { switch (d) { case VERTICAL: double[][] dValues = { { 1, 0, -1 }, { 2, 0, -2 }, { 1, 0, -1 } }; return new Mask(dValues); case HORIZONTAL: double[][] aValues = { { 1, 2, 1 }, { 0, 0, 0 }, { -1, -2, -1 } }; return new Mask(aValues); case DIAGONAL: double[][] bValues = { { 2, 1, 0 }, { 1, 0, -1 }, { 0, -1, -2 } }; return new Mask(bValues); case INVERSE_DIAGONAL: double[][] cValues = { { 0, -1, -2 }, { 1, 0, -1 }, { 2, 1, 0 } }; return new Mask(cValues); } return null; }
4
public void keyReleased(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_A) { dx = 0; } if (key == KeyEvent.VK_D) { dx = 0; } if (key == KeyEvent.VK_W) { dy = 0; } if (key == KeyEvent.VK_S) { dy = 0; } }
4
protected boolean checkAreas() { boolean result = false; synchronized (planAreas) { for (PlanArea area : planAreas) { if (!area.isCommitted()) { continue; } if (area.buildFromSupply(1)) { result = true; } } } return result; }
3
public void addTriangles( ArrayList<Triangle> triangles ) { int size = triangles.size(); this.triangles.addAll( triangles ); if ( resource.getVbo().capacity() > resource.getVbo().limit() + ( size * 3 * 9 ) ) { FloatBuffer tmpVbo = Utils.createFlippedBuffer( triangles ); resource.getVbo().limit( tmpVbo.capacity() ); resource.getVbo().put( tmpVbo ); resource.getVbo().flip(); tmpVbo.flip(); bufferSubData( GL_ARRAY_BUFFER, resource.getVboIndex(), resource.getVbo().limit() * 4, tmpVbo ); } else { FloatBuffer tmpVbo = BufferUtils.createFloatBuffer( resource.getVbo().limit() + ( size * 3 * 9 ) ); tmpVbo.put( resource.getVbo() ); tmpVbo.put( Utils.createFlippedBuffer( triangles ) ); resource.setVbo( (FloatBuffer) tmpVbo.flip() ); bufferData( GL_ARRAY_BUFFER, resource.getVboIndex(), resource.getVbo() ); IntBuffer tmpIbo = BufferUtils.createIntBuffer( resource.getIbo().capacity() + ( size * 3 ) ); tmpIbo.put( resource.getIbo() ); tmpIbo.put( Utils.createRegularFlippedBuffer( size * 3, resource.getIbo().capacity() ) ); resource.setIbo( (IntBuffer) tmpIbo.flip() ); bufferData( GL_ELEMENT_ARRAY_BUFFER, resource.getIboIndex(), resource.getIbo() ); } }
1
@Override public Class<?> getColumnClass(int sarakeIndeksi) { return tyypit[sarakeIndeksi]; }
1
public void updateLeft(){ if(left > 0){ for(int i=0; i<height+top; i++){ for(int j=0; j<left; j++){ drawDiamond(j, i); } } } else if(left < 0){ for(int i=top; i<height+top; i++){ for(int j=-1; j>left-1; j--){ drawDiamond(j, i); } } } }
6
private int search(TreeNode root, String query, int d, int length){ if(root == null) return length; if(root.value != null) length = d; if(d == query.length()) return length; char c = query.charAt(d); if(root.children.containsKey(c)){ return search(root.children.get(c), query, d + 1, length); } else return d; }
4
public static void main(String[] args) { if (args.length != 3) { System.out.println(USAGE); System.exit(0); } String name = args[0]; InetAddress addr = null; int port = 0; Socket sock = null; // check args[1] - the IP-adress try { addr = InetAddress.getByName(args[1]); } catch (UnknownHostException e) { System.out.println(USAGE); System.out.println("ERROR: host " + args[1] + " unknown"); System.exit(0); } // parse args[2] - the port try { port = Integer.parseInt(args[2]); } catch (NumberFormatException e) { System.out.println(USAGE); System.out.println("ERROR: port " + args[2] + " is not an integer"); System.exit(0); } // try to open a Socket to the server try { sock = new Socket(addr, port); } catch (IOException e) { System.out.println("ERROR: could not create a socket on " + addr + " and port " + port); } // create Peer object and start the two-way communication try { Peer client = new Peer(name, sock); Thread streamInputHandler = new Thread(client); streamInputHandler.start(); client.handleTerminalInput(); client.shutDown(); } catch (IOException e) { e.printStackTrace(); } }
5
public static Packet parse(DatagramPacket packet) throws IllegalArgumentException, AssertionError { Packet rad; try { ByteBuffer bb = ByteBuffer.wrap(packet.getData()); int packetCode = bb.get(); int packetIdentifier = bb.get(); int packetLength = bb.getShort(); if(packetLength != packet.getLength()) throw new AssertionError("Invalid package length. Discarding package."); byte[] packetData = new byte[AUTH_FIELDLENGTH]; bb.get(packetData, 0, AUTH_FIELDLENGTH); rad = new Packet(packetCode, packetIdentifier, packetData); while(bb.position() < packetLength) { int attrCode = bb.get(); int attrLength = bb.get(); int attrLengthWithoutHeader = attrLength-Attribute.HEADER_SIZE; byte[] attrData = new byte[attrLengthWithoutHeader]; bb.get(attrData, 0, attrLengthWithoutHeader); rad.addAttribute(attrCode, attrLength, attrData); } } catch (AssertionError ex) { System.out.println(ex.getMessage()); rad = null; } return rad; }
3
private List<Class<?>> getTypeHierarchy(Class<?> type) { if (type.isPrimitive()) { type = primitiveTypeToWrapperMap.get(type); } Set<Class<?>> typeHierarchy = new LinkedHashSet<Class<?>>(); collectTypeHierarchy(typeHierarchy, type); if (type.isArray()) { typeHierarchy.add(Object[].class); } typeHierarchy.add(Object.class); return new ArrayList<Class<?>>(typeHierarchy); }
7
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked JTextPane jtp = new JTextPane(); jtp.setBackground(Color.white); jtp.setText(text); boolean show = true; try { jtp.print(null, null, show, null, null, show); } catch (java.awt.print.PrinterException ex) { ex.printStackTrace(); } }//GEN-LAST:event_jButton1MouseClicked
1
public Object clone() throws CloneNotSupportedException { CompassPlot clone = (CompassPlot) super.clone(); if (this.circle1 != null) { clone.circle1 = (Ellipse2D) this.circle1.clone(); } if (this.circle2 != null) { clone.circle2 = (Ellipse2D) this.circle2.clone(); } if (this.a1 != null) { clone.a1 = (Area) this.a1.clone(); } if (this.a2 != null) { clone.a2 = (Area) this.a2.clone(); } if (this.rect1 != null) { clone.rect1 = (Rectangle2D) this.rect1.clone(); } clone.datasets = (ValueDataset[]) this.datasets.clone(); clone.seriesNeedle = (MeterNeedle[]) this.seriesNeedle.clone(); // clone share data sets => add the clone as listener to the dataset for (int i = 0; i < this.datasets.length; ++i) { if (clone.datasets[i] != null) { clone.datasets[i].addChangeListener(clone); } } return clone; }
7
public synchronized WorkerThread borrowThread() { // TODO Auto-generated constructor stub if (idleThreads.isEmpty()) { return null; } return idleThreads.remove(0); }
1
public Elevator CallDown(int fromFloor){ //check for error cases if ((fromFloor>super.numFloors) || (fromFloor<0)){ System.out.println("This floor does not exist"); } //first we will send the first idle elevator for (Elevator e: elevators){ synchronized(e){ //if the elevator is idle //or if the elevator is above the rider and it's going down if(e.getMyDirection()==Elevator.DIRECTION_NEUTRAL){//direction2 is going upwards //add in condition about space e.addFloor(fromFloor); e.getDownBarriers()[fromFloor].arrive(); return e; } } } //else we will send the first elevator going in the correct elevator for (Elevator e: elevators){ synchronized(e){ if (fromFloor==super.numFloors && e.getMyDirection()==Elevator.DIRECTION_UP){ e.addFloor(fromFloor); e.getDownBarriers()[fromFloor].arrive(); return e; } if (e.getMyDirection()==Elevator.DIRECTION_DOWN && e.getFloor()>=fromFloor){ e.addFloor(fromFloor); e.getDownBarriers()[fromFloor].arrive(); return e; } } } //else if there are no elevators return null; }
9
public final EsperParser.forloop_return forloop() throws RecognitionException { EsperParser.forloop_return retval = new EsperParser.forloop_return(); retval.start = input.LT(1); Object root_0 = null; Token ENDFOR46=null; EsperParser.for__return for_45 =null; Object ENDFOR46_tree=null; try { // C:\\Users\\Alex\\Dropbox\\EclipseWorkspace\\esper-compiler\\src\\compiler\\Esper.g:62:9: ( for_ ENDFOR ) // C:\\Users\\Alex\\Dropbox\\EclipseWorkspace\\esper-compiler\\src\\compiler\\Esper.g:62:11: for_ ENDFOR { root_0 = (Object)adaptor.nil(); pushFollow(FOLLOW_for__in_forloop621); for_45=for_(); state._fsp--; adaptor.addChild(root_0, for_45.getTree()); ENDFOR46=(Token)match(input,ENDFOR,FOLLOW_ENDFOR_in_forloop623); ENDFOR46_tree = (Object)adaptor.create(ENDFOR46) ; adaptor.addChild(root_0, ENDFOR46_tree); } retval.stop = input.LT(-1); retval.tree = (Object)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { // do for sure before leaving } return retval; }
1
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Tag tag = (Tag) o; return type == tag.type && value.equals(tag.value); }
4
public void bet (String[][] playerName,int[][] price,boolean cpu){ for(int i=0;i < menberNum;i++){ if(i==0){ if(cpu==true){ /////cpuの賭け金の設定 if(price[0][0]>cpuPrice*0.4){ //4割を切るまでは price[0][1] =(int)(price[0][0]*0.2);//10分の1を賭ける }else{ price[0][1] =price[0][0]; //4割を切ると全賭け } System.out.println(playerName[0][0]+"の賭け金は"+price[0][1]+"です"); ////////////////配列0番が親 }else{ System.out.print(playerName[0][0]+"の賭け金を入力してください>"); ////////////////配列0番が親 price[0][1] = scan.nextInt(); if(price[0][1]>price[0][0]){ System.out.print(playerName[0][0]+"の所持金が足りません"); i--; continue; }} }else{ System.out.print(playerName[i][0]+"の賭け金を入力してください>"); ////////////////子供 price[i][1] = scan.nextInt(); if(price[i][1]>price[i][0]){ System.out.print(playerName[i][0]+"の所持金が足りません"); i--; continue; } } } }
6
public UpgradeType getType() { return type; }
0
private static Image getImage(String filename) { // to read from file ImageIcon icon = new ImageIcon(filename); // try to read from URL if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) { try { URL url = new URL(filename); icon = new ImageIcon(url); } catch (Exception e) { /* not a url */ } } // in case file is inside a .jar if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) { URL url = StdDraw.class.getResource(filename); if (url == null) throw new IllegalArgumentException("image " + filename + " not found"); icon = new ImageIcon(url); } return icon.getImage(); }
6
public String obfuscateText(String _text) { // Obfuscated code will return by using StringBuilder; StringBuilder sb = new StringBuilder(); // Change text to Char array. char ch[] = _text.toCharArray(); // Make String array per 1 character from ch[]. // This String array uses to check key character and etc. String[] choppedText = new String[_text.length()]; for (int i = 0; i < _text.length(); i++) { choppedText[i] = String.valueOf(ch[i]); } // Obfuscate text with escaping. for (int i = 0; i < _text.length(); i++) { // Set top of the code. if (i == 0) { // Insert JavaScript code to enable execute. if (_keyChar == "%") { // If key character is "%", no needs replace method. sb.append("eval(unescape('"); } else { // If key character isn't "%", it needs more "(". // Because of to replacet "%" with replace method. sb.append("eval(unescape(('"); } } // Measures to line separator character. if (choppedText[i].matches(System.getProperty("line.separator"))) { // If line separator character has detected, ignore. } else { // Change character to binary code likes "%0A". sb.append(_keyChar + Integer.toHexString(ch[i])); } // Set bottom of the code. if (i == (_text.length() - 1)) { // Insert JavaScript code to enable execute. if (_keyChar == "%") { // If key character is "%", no needs replace method. sb.append("'));"); } else { // If key character isn't "%", it needs replace method. // This section will add like "'.)replace(/@/g, '%')));". sb.append("').replace(/" + _keyChar + "/g, '%')));"); } } } return new String(sb).replace(_keyChar + "9", _keyChar + "09").replace(_keyChar + "a", _keyChar + "0a"); }
7
public static void main( String[ ] args ) throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) ); String line = in.readLine( ); int t = Integer.parseInt( line ); int arr[][] = new int[ t + 1 ][ t + 1 ]; int dp[][] = new int[ t + 1 ][ t + 1 ]; for ( int i = 0; i < t; i++ ) { int cad[] = atoi( in.readLine( ) ); for ( int j = 0; j < cad.length; j++ ) { arr[ i + 1 ][ j + 1 ] = cad[ j ]; } } for ( int i = 0; i < arr.length; i++ ) { arr[ 0 ][ i ] = 0; arr[ i ][ 0 ] = 0; } int max = Integer.MIN_VALUE; for ( int i = 1; i < arr.length; i++ ) { for ( int j = 1; j < arr.length; j++ ) { for ( int k = i; k < arr.length; k++ ) { for ( int l = j; l < arr.length; l++ ) { dp[ k ][ l ] = dp[ k - 1 ][ l ] + dp[ k ][ l - 1 ] - dp[ k - 1 ][ l - 1 ] + arr[ k ][ l ]; if ( max < dp[ k ][ l ] ) { max = dp[ k ][ l ]; } } } } } System.out.println( max ); }
8
private void getData(ProtobufDecodeMeta consumerMeta, boolean copyStepname) { if (copyStepname) { wStepname.setText(stepname); } wInputField.setText(Const.NVL(consumerMeta.getInputField(), "")); StringBuilder cpBuf = new StringBuilder(); String[] classpath = consumerMeta.getClasspath(); if (classpath != null) { for (int i = 0; i < classpath.length; ++i) { if (i > 0) { cpBuf.append(File.pathSeparatorChar); } cpBuf.append(classpath[i]); } } wClasspath.setText(cpBuf.toString()); wRootClass.setText(Const.NVL(consumerMeta.getRootClass(), "")); FieldDefinition[] fields = meta.getFields(); if (fields != null) { for (FieldDefinition field : fields) { TableItem item = new TableItem(wFields.table, SWT.NONE); int colnr = 1; item.setText(colnr++, Const.NVL(field.name, "")); item.setText(colnr++, Const.NVL(field.path, "")); item.setText(colnr++, ValueMeta.getTypeDesc(field.type)); } } wFields.removeEmptyRows(); wFields.setRowNums(); wFields.optWidth(true); wStepname.selectAll(); }
6
public static Tag<Map<String, Tag>> newCompound(Map<String, ?> data) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, NoSuchFieldException, NoSuchMethodException, NBTLibDisabledException, UnknownTagException { Map<String, Tag> map; try { for(Object o : data.values().toArray()) { Tag.class.cast(o); } map = (Map<String, Tag>)data; } catch(ClassCastException e) { map = new HashMap<String, Tag>(); for(Map.Entry<String, ?> entry : data.entrySet()) { map.put(entry.getKey(), parse(entry.getValue())); } } return new Tag<Map<String, Tag>>(NBT.COMPOUND, map); }
5
public void accapt(Visitor visitor) { // 关键实现 visitor.visit(this); }
0
public void toggleVisible() { if(frame == null) buildGUI(); frame.setVisible(!frame.isVisible()); }
1
private void creerActions(){ actions = new HashMap<String, Action>(); for(int i = 0 ; i < 9 ; i++ ){ for(int j = 0 ; j < 9 ; j++ ){ for(int k = 1 ; k <= 9 ; k++){ actions.put(i+""+j+""+k, new DynamicAction(i+""+j+""+k)); } } } }
3
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); session.removeAttribute("error"); session.removeAttribute("sucesso"); Usuario user = (Usuario) session.getAttribute("user"); //String idSecaoS = request.getParameter("id_secao"); String titulo = request.getParameter("titulo"); String descricao = request.getParameter("descricao"); Secao secao = (Secao)session.getAttribute("secao"); session.removeAttribute("secao"); try { if(user != null && user instanceof Editor){ Editor editor = (Editor) user; SecaoDAO dao = new SecaoDAO(); if(titulo == null || descricao == null || titulo.trim().equals("") || descricao.trim().equals("")){ session.setAttribute("error", "Preencha todos os campos."); response.sendRedirect(request.getContextPath() + "/editorAdicionarSecao.jsp"); } // Se nao houver secao na sessao. Cria um novo. Se houver edita. else if(secao == null){ secao = new Secao(); secao.setTitulo(titulo); secao.setDescricao(descricao); dao.inserir(secao); editor.getSecoes().add(secao); session.setAttribute("sucesso", "Secao adicionada com sucesso."); response.sendRedirect(request.getContextPath() + "/editorAdicionarSecao.jsp"); }else{ secao.setTitulo(titulo); secao.setDescricao(descricao); dao.atualizar(secao); session.setAttribute("sucesso", "Secao atualizada com sucesso."); response.sendRedirect(request.getContextPath() + "/editorAdicionarSecao.jsp"); } }else{ session.setAttribute("error", "Voce nao tem permissao para acessar essa area."); response.sendRedirect(request.getContextPath() + "/index.jsp"); } } catch(SQLException ex){ ex.printStackTrace(); session.invalidate(); response.sendRedirect(request.getContextPath() + "/index.jsp"); }catch (Exception ex){ ex.printStackTrace(); session.invalidate(); response.sendRedirect(request.getContextPath() + "/index.jsp"); } }
9
public static MultiAnswerQuestion getMultiAnswerQuestionByXMLElem(XMLElement root, Quiz quiz, int pos) { int quizID = quiz.quizID; int position = pos; Object question = null; Object answer = null; double score = 10; int answerNumber = 0; boolean isOrdered = false; if (root.attributeMap.containsKey("isordered") && root.attributeMap.get("isordered").equals("true")) isOrdered = true; for (int i = 0; i < root.childList.size(); i++) { XMLElement elem = root.childList.get(i); if (elem.name.equals("query")) { question = (String) elem.content; } else if (elem.name.equals("answer-list")) { answer = Question.getAnswerListByXMLElem(elem); } else if (elem.name.equals("score")) { score = Double.parseDouble(elem.content); } else if (elem.name.equals("answer-number")){ answerNumber = Integer.parseInt(elem.content); } else { System.out.println("Unexpected field in response question : " + elem.name); } } return new MultiAnswerQuestion(quizID, position, question, answer, score, answerNumber, isOrdered); }
7
IRCDDBExtApp.UpdateResult processUpdate ( int tableID, Scanner s, String ircUser, String msg ) { if (s.hasNext(datePattern)) { String d = s.next(datePattern); if (s.hasNext(timePattern)) { String t = s.next(timePattern); Date dbDate = null; try { dbDate = parseDateFormat.parse(d + " " + t); } catch (java.text.ParseException e) { dbDate = null; } if ((dbDate != null) && s.hasNext(keyPattern[tableID])) { String key = s.next(keyPattern[tableID]); if (s.hasNext(valuePattern[tableID])) { String value = s.next(valuePattern[tableID]); if (extApp != null) { return extApp.dbUpdate( tableID, dbDate, key, value, ircUser, msg ); } } } } } return null; }
7
public JSONArray optJSONArray(String key) { Object o = opt(key); return o instanceof JSONArray ? (JSONArray)o : null; }
1
String[] countWords(String sentence, int returnWordCount) { // check input parameter if (sentence == null || sentence.isEmpty()) { System.out.println("Sentence not defined"); return null; } // check input parameter if (returnWordCount <= 0) { System.out.println("Return Words must be greater than zero"); return null; } // store count for each word discovered, indexed by word HashMap<String, Integer> wordFreq = new HashMap<>(); // remove all characters that are not spaces, letters, or digits final String regex = "[^a-zA-Z\\d\\ ]"; sentence = sentence.replaceAll(regex, ""); // parse string by space StringTokenizer token = new StringTokenizer(sentence); // count the word frequency in the sentence. This operation is O(n) while (token.hasMoreElements()) { String word = (String) token.nextElement(); if (wordFreq.containsKey(word)) { // existing word found. Increment word count wordFreq.put(word, wordFreq.get(word) + 1); } else { // new word found, initial count is 1 wordFreq.put(word, 1); } } // convert map to a list ArrayList<Map.Entry<String, Integer>> wordFreqList = new ArrayList<>(wordFreq.entrySet()); // sort the list and reverse it so that the greatest counts are in the front MapComparator myComparator = new MapComparator(); Collections.sort(wordFreqList, myComparator); Collections.reverse(wordFreqList); // adjust return size so that our return list is no bigger than the number of words if (returnWordCount > wordFreqList.size()) { returnWordCount = wordFreqList.size(); } // copy results into return list int index = 0; String [] returnList = new String[returnWordCount]; for (Map.Entry<String, Integer> x : wordFreqList) { returnList[index++] = x.getKey(); // break if we reach end of list if (index >= returnWordCount) { break; } } return returnList; }
8
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; final Pair pair = (Pair) o; if (first != null ? !first.equals(pair.first) : pair.first != null) return false; if (second != null ? !second.equals(pair.second) : pair.second != null) return false; return true; }
6