text
stringlengths
14
410k
label
int32
0
9
public void mouseDrag(int x, int y){ if(movingInputTime){ node.setPosition(x); } }
1
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpSession session = ((HttpServletRequest)request).getSession(true); Locale locale = (Locale) session.getAttribute(JSP_LOCALE); if (locale == null) { if (defLocale != null) { session.setAttribute(JSP_LOCALE, defLocale); } else { Locale loc = response.getLocale(); session.setAttribute(JSP_LOCALE, response.getLocale()); } } chain.doFilter(request, response); }
2
protected void addNewAciton() { // Action type Object typeValueItem = typeNAJcbx.getSelectedItem(); String typeValue = null; if (typeValueItem != null ) { typeValue = typeValueItem.toString(); } // Claims", "Counter Claims", "Evidene", "Counter Evidence", // "Bi-polar Questions", "Response to Bi-polar", "Challenge"}; switch (typeValue) { case "Claims": addNewClaim(); break; case "Sub Claims": addNewSubClaim(); break; case "Evidence": addEvidence(); break; case "Counter Claims": oppositeClaimResultList = claim.getClaimList(publicFileName); addNewCounterClaims(); break; case "Counter Evidence": addNewCounterEvidence(); break; case "Bi-polar Questions": addNewBipolarQuestion(); break; case "Response to Bi-polar": addNewResponse(); break; case "Challenge": addNewChallenge(); break; } // Action title, description String titleValue = titleNAJtxt.getText() , descriptionValue = descriptionNAJtxa.getText(); System.out.println("typeValue : " + typeValue + " titleValue:" +titleValue + " descriptionValue: " + descriptionValue); }
9
@Override public void onFirstUpdate(){ if (sound.Manager.enabled) { sound.Event effect = new sound.Event(getPosition(), getVelocity(),sound.Library.findByName(SHOOT_EFFECT)); effect.gain = EFFECT_VOLUME; sound.Manager.addEvent(effect); } if(ParticleSystem.isEnabled()){ particleGenerator = new graphics.particles.generators.Exhaust<Plasma>(Plasma.class,this); ParticleSystem.addGenerator(particleGenerator); } }
2
protected void attachToHost() { if (host == null) return; if (host instanceof Particle || host instanceof RectangularObstacle) { switch (getAttachmentPosition()) { case CENTER: setLocation(host.getRx(), host.getRy()); break; case ENDPOINT1: float length = (float) getLength(); float invLength = 1.0f / length; float cos = (getX1() - getX2()) * invLength; float sin = (getY1() - getY2()) * invLength; setLocation(host.getRx() - length * cos * 0.5f, host.getRy() - length * sin * 0.5f); break; case ENDPOINT2: length = (float) getLength(); invLength = 1.0f / length; cos = (getX2() - getX1()) * invLength; sin = (getY2() - getY1()) * invLength; setLocation(host.getRx() - length * cos * 0.5f, host.getRy() - length * sin * 0.5f); break; } } else if (host instanceof RadialBond) { RadialBond bond = (RadialBond) host; double length = bond.getLength(-1); double invLength = 0.5 / length; double cos = (bond.atom2.rx - bond.atom1.rx) * invLength; double sin = (bond.atom2.ry - bond.atom1.ry) * invLength; setX1((float) (bond.atom1.rx - bond.atom1.sigma * cos)); setY1((float) (bond.atom1.ry - bond.atom1.sigma * sin)); setX2((float) (bond.atom2.rx + bond.atom2.sigma * cos)); setY2((float) (bond.atom2.ry + bond.atom2.sigma * sin)); } }
7
public static void load(){ BufferedReader reader = null; try{ if(USER_DATA_FILE.exists() == false){ //System.out.println("USER DATA DOES NOT EXIST"); USER_DATA_FILE.createNewFile(); makeAllDefault(); return; } reader = new BufferedReader(new FileReader(USER_DATA_FILE)); //get all data ArrayList<StringPair> stringPairs = new ArrayList<StringPair>(); StringPair readPair = null; while((readPair = readLine(reader)) != null){ stringPairs.add(readPair); } //determine whose data is whose for(StringPair pair : stringPairs){ for(Datum<String> datum : Data.values()){ if(datum.description.equals(pair.description)){ //descriptions match; data belongs to this datum datum.setData(pair.data, false); } } } //set values for each datum /*for(Datum<String> datum : Data.values()){ datum.setData(readLine(reader),true); }*/ } catch(IOException io){ Utils.debug(io, "Error reading user data"); //set default values for all makeAllDefault(); } finally{ if(reader != null){ try{ reader.close(); } catch(IOException io){ Utils.debug(io, "Error closing input stream in file reader"); } } save(); } }
8
public static String sendPost(String url, String contents,HashMap<String, String> propertyMap){ InputStreamReader inr = null; try{ System.out.println("post>>>"+url); URL serverUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection(); conn.setRequestMethod("POST");//"POST" ,"GET" if(propertyMap != null){ Set<String> keys = propertyMap.keySet(); Iterator<String> iterator = keys.iterator(); while (iterator.hasNext()) { String key = iterator.next(); conn.addRequestProperty(key, propertyMap.get(key)); } } conn.addRequestProperty("Cookie", getCookie()); conn.addRequestProperty("Accept-Charset", "UTF-8;");//GB2312, conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36"); conn.setDoInput(true); conn.setDoOutput(true); conn.connect(); if (contents!=null) { conn.getOutputStream().write(contents.getBytes()); } if(conn.getHeaderFields().get("Set-Cookie") != null){ for(String s:conn.getHeaderFields().get("Set-Cookie")){ addCookie(new BotCookie(s)); } } InputStream ins = conn.getInputStream(); inr = new InputStreamReader(ins, "UTF-8"); BufferedReader bfr = new BufferedReader(inr); String line = ""; StringBuffer res = new StringBuffer(); do{ res.append(line); line = bfr.readLine(); //System.out.println(line); }while(line != null); // System.out.println(">>>==="+res); return res.toString(); }catch(Exception e){ e.printStackTrace(); return null; } finally{ if(inr!=null){ try { inr.close(); } catch (IOException e) { e.printStackTrace(); }finally{ inr =null; } } } }
9
public void render() { clear(); Graphics g = graphics(); if (isPushed)// modified by Kerrigan { if (a) g.drawImage(up, 0, 0, null); else if (isHovered) g.drawImage(hover, 0, 0, null); else g.drawImage(down, 0, 0, null); } else { if (a) g.drawImage(down, 0, 0, null); else if (isHovered) g.drawImage(hover, 0, 0, null); else g.drawImage(up, 0, 0, null); } update(); }
5
public static byte[] handshake(byte[] info_hash, byte[] peer_id){ byte[] hand_shake = new byte[68]; //<19><BitTorrent protocol><00000000> //copy the handshake_header into the handshake message for(int i = 0; i<handshake_header.length; i++) hand_shake[i] = handshake_header[i]; //fill 28 - 47 with the SHA1 hash from info_hash for(int i=0; i<20;i++) hand_shake[28+i] = info_hash[i]; //fill 48 - 67 with the peer_id for(int i=0; i<20;i++) hand_shake[48+i] = peer_id[i]; //out handshake is completed, return it to the peer return hand_shake; }
3
public boolean isSymmetricItr(TreeNode root){ ArrayDeque<TreeNode> queue1 = new ArrayDeque<TreeNode>(); ArrayDeque<TreeNode> queue2 = new ArrayDeque<TreeNode>(); queue1.offerLast(root); queue2.offerLast(root); while(!queue1.isEmpty() && !queue2.isEmpty()){ TreeNode n1 = queue1.pollFirst(); TreeNode n2 = queue2.pollFirst(); if(n1 == null && n2 == null) continue; if(n1 == null || n2 == null) return false; if(n1.val != n2.val) return false; queue1.offerLast(n1.left); queue1.offerLast(n1.right); queue2.offerLast(n2.right); queue2.offerLast(n2.left); } return queue1.isEmpty() && queue2.isEmpty(); }
8
public String searchTagAttributeValue(Document doc, String rootNodeName, String tag, String attributeName, boolean strict) throws TagNotFoundException, AttributeNotFoundException { NodeList nodes = doc.getElementsByTagName(rootNodeName); try { DOMWalker walker = DOMWalkerFactory.getWalker(WALKER).configure(nodes.item(0), DOMWalker.ELEMENT_NODES); while (walker.hasNext()) { Node node = walker.nextNode(); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equalsIgnoreCase(tag)) { NamedNodeMap attributes = node.getAttributes(); if (attributes == null) { if (strict) { throw new AttributeNotFoundException("The tag \"" + tag + "\" does not contain attributes."); } else { return ""; } } else { Node attribute = attributes.getNamedItem(attributeName); if (attribute == null) { if (strict) { throw new AttributeNotFoundException("The attribute \"" + attribute + "\" does not exists."); } else { return ""; } } else { return attribute.getNodeValue(); } } } } } } catch (Exception e) { LOG.error("Error parsing DOM tree. Error: " + e.toString(), e); } if (strict) { throw new TagNotFoundException("The tag \"" + tag + "\" was not found in the XML."); } else { return ""; } }
9
public boolean choqueObstaculo(int posicionX, int posicionY){ for (int i = 0; i < listaObjetos.size(); i++){ //Si es de tipo Roca y la posicion esta dentro de su perimetro no permite el movimiento if( (listaObjetos.get(i).getTipoObjeto().getClass() == (new ObjetoRoca().getClass())) && ( (listaObjetos.get(i).getPosX() >= posicionX) && (listaObjetos.get(i).getPosX() <= (posicionX + Ventana.getDiametroImagen())) ) && ( (listaObjetos.get(i).getPosY() >= posicionY) && (listaObjetos.get(i).getPosY() <= (posicionY + Ventana.getDiametroImagen())) ) ) return true; } return false; }
6
public void updateList(String remoteMachineID, MemberList incomingMemberList) { int localIndex=-1,otherIndex=0; String currentIP; int localMemberListsize = this.memList.size(); int incomingMemberListsize = incomingMemberList.memList.size(); for ( otherIndex = 0; otherIndex < incomingMemberListsize; otherIndex++ ) { currentIP = incomingMemberList.memList.get(otherIndex).getMachineID(); for (int i = 0; i < localMemberListsize; i++ ) { // if localIndex == -1, entry not found in the local gossip table if (this.memList.get(i).getMachineID().equals(currentIP)){ localIndex = i; break; } } if (localIndex >= 0 && incomingMemberList.memList.get(otherIndex).getHeartBeat() > this.memList.get(localIndex).getHeartBeat() && incomingMemberList.memList.get(otherIndex).getDeletionStatus() == false) { if(this.memList.get(localIndex).getDeletionStatus() == true) { this.memList.get(localIndex).setDeletionStatus(false); FaultRateCalculator.falseDetections++; //System.out.println("falseDetections" + Integer.valueOf(FaultRateCalculator.falseDetections)); } this.memList.get(localIndex).updateHeartBeat(incomingMemberList.memList.get(otherIndex).getHeartBeat()); this.memList.get(localIndex).setlocalTimeStamp(); } else if(localIndex < 0 && incomingMemberList.memList.get(otherIndex).getDeletionStatus() == false) { this.memList.add(new MemberListEntry(currentIP)); int currentSize = this.memList.size()-1; this.memList.get(currentSize).setMachineID(currentIP); this.memList.get(currentSize).setHeartBeat(incomingMemberList.memList.get(otherIndex).getHeartBeat()); this.memList.get(currentSize).setlocalTimeStamp(); // To be confirmed. this.memList.get(currentSize).setDeletionStatus(false); } } }
9
@Override public void update(Observable o, Object arg) { if (!this.gm.getBoard().getWinner().equals(GameResult.GameRunning)){ endGame(); } if (this.gm.canDraw() && (!isDrawVisable)) { isDrawVisable = true; int wantsDraw = JOptionPane.showConfirmDialog( myCheckmate, "It is possible to declare this game as a tie. Would you like to end this game in a draw?", "End game in a draw?", JOptionPane.YES_NO_OPTION ); if (wantsDraw == JOptionPane.YES_OPTION) { this.gm.getBoard().setWinner(GameResult.DrawGame); drawGame(); isDrawVisable = false; } } this.paintComponent(this.getGraphics()); if (this.gm.mustDraw()) { drawGame(); } if (this.gm.isCheckMate()) { JPanel panel = new JPanel(new GridLayout(2, 1)); JLabel label; if(myCheckmate.getGameModel().getBoard().isWhiteTurn()) { label = new JLabel("Black Wins!!"); this.gm.getBoard().setWinner(GameResult.BlackWon); } else { label = new JLabel("White Wins!!"); this.gm.getBoard().setWinner(GameResult.WhiteWon); } panel.add(label); endGame(); } }
7
public void run() { long current = 0, size = totalSize(); for (Pair<File,File> pair : pairs) { File src = pair.get1(); File dst = pair.get2(); if (src.exists() && src.isFile()) { if (!dst.exists() || dst.isFile()) { try { if (dst.exists()) dst.delete(); dst.createNewFile(); progressStr = src.getAbsolutePath()+"\n"+dst.getAbsolutePath(); FileInputStream fis = new FileInputStream(src); BufferedInputStream bis = new BufferedInputStream(fis); FileOutputStream fos = new FileOutputStream(dst); BufferedOutputStream bos = new BufferedOutputStream(fos); int value; while ((value = bis.read()) != -1) { progress = ((float)current)/((float)size); bos.write(value); current++; } bos.flush(); bos.close(); fos.close(); bis.close(); fis.close(); } catch (Exception e) {e.printStackTrace();} } } } progress = 1f; super.run(); }
8
private void handleUpdate() { if (pref instanceof PreferenceString) { ((PreferenceString) pref).setTmp((String) box.getSelectedItem()); } else if (pref instanceof PreferenceLineEnding) { ((PreferenceLineEnding) pref).setTmp((String) box.getSelectedItem()); } }
2
public List<Produto> listarTodos() throws ErroValidacaoException, Exception{ List<Produto> produtos = new LinkedList<>(); try{ PreparedStatement comando = bd.getConexao() .prepareStatement("SELECT p.id,nome,descricao,valor_uni_Venda, " + "valor_Uni_Compra,quantidade " + "FROM produtos p INNER JOIN estoques e on e.id = p.id WHERE p.ativo = 1"); ResultSet consulta = comando.executeQuery(); while(consulta.next()){ Produto novo = new Produto(); Estoque novoE = new Estoque(); novo.setDescricao(consulta.getString("descricao")); novo.setId(consulta.getInt("id")); novo.setNome(consulta.getString("nome")); novo.setValorUnidadeCompra(consulta.getDouble("valor_uni_Compra")); novo.setValorUnidadeVenda(consulta.getDouble("valor_uni_Venda")); novoE.setId(consulta.getInt("id")); novoE.setQuantidade(consulta.getInt("quantidade")); novo.setEstoque(novoE); produtos.add(novo); } return produtos; }catch(SQLException ex){ ex.printStackTrace(); return null; } }
2
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person1 = (Person) o; if (age != person1.age) return false; if (firstName != null ? !firstName.equals(person1.firstName) : person1.firstName != null) return false; if (lastName != null ? !lastName.equals(person1.lastName) : person1.lastName != null) return false; return true; }
8
public static void splitLabel(Transition transition, Automaton automaton){ FSATransition trans = (FSATransition) transition; State from = transition.getFromState(), f = from, to = transition .getToState(); automaton.removeTransition(trans); String label = trans.getLabel(); for(int i=label.charAt(label.indexOf("[")+1); i<=label.charAt(label.indexOf("[")+3); i++){ Transition newTrans = new FSATransition(from, to, Character.toString((char)i)); automaton.addTransition(newTrans); } }
1
@Override public void sort(int[] array) { for( int i = array.length-1; i > 0; --i ) { for( int j = 0; j < i; ++j ) { if( array[j] > array[j+1] ) { int swap = array[j+1]; array[j+1] = array[j]; array[j] = swap; } } } }
3
protected void constBranchEliminate(Block root) { Queue<Entry<Block, HashMap<Integer, SSAorConst>>> queue = new LinkedList<Entry<Block, HashMap<Integer, SSAorConst>>>(); HashMap<Integer, SSAorConst> propagator = new HashMap<Integer, SSAorConst>(); queue.add(new AbstractMap.SimpleEntry<Block, HashMap<Integer, SSAorConst>>(root, propagator)); HashSet<Block> removedBlocks = new HashSet<Block>(); while (!queue.isEmpty()) { Entry<Block, HashMap<Integer, SSAorConst>> entry = queue.remove(); Block blk = entry.getKey(); propagator = entry.getValue(); if (blk == null) {// || visited.contains(blk)) { continue; } if (removedBlocks.contains(blk)) { // propagate removed message continueRemove(blk.getNextBlock(), queue, removedBlocks); continueRemove(blk.getNegBranchBlock(), queue, removedBlocks); continue; } // beggining propagator.putAll(blk.fixConstPhi(removedBlocks)); // middle propagator = blk.copyPropagate(propagator); // end Block removed = blk.checkAndRemoveConstBranch(); if (removed != null) { removedBlocks.add(removed); queue.add(new AbstractMap.SimpleEntry<Block, HashMap<Integer, SSAorConst>>(removed, null)); } if (blk.getNextBlock() != null) { if (blk.getNextBlock().isBackEdgeFrom(blk)) { // back to front, update, but not propagate HashMap<Integer, SSAorConst> nextPropagator = new HashMap<Integer, SSAorConst>( propagator); // nextPropagator.putAll(blk.getNextBlock().fixConstPhi(removedBlocks)); nextPropagator = blk.getNextBlock().copyPropagate(nextPropagator); } else { queue.add(new AbstractMap.SimpleEntry<Block, HashMap<Integer, SSAorConst>>(blk .getNextBlock(), propagator)); } } if (blk.getNegBranchBlock() != null) { if (blk.getNegBranchBlock().isBackEdgeFrom(blk)) { // back to front, update, but not propagate HashMap<Integer, SSAorConst> nextPropagator = new HashMap<Integer, SSAorConst>( propagator); // nextPropagator.putAll(blk.getNegBranchBlock().fixConstPhi(removedBlocks)); nextPropagator = blk.getNegBranchBlock().copyPropagate(nextPropagator); } else { queue.add(new AbstractMap.SimpleEntry<Block, HashMap<Integer, SSAorConst>>(blk .getNegBranchBlock(), propagator)); } } } }
8
public static Window getWindowForComponent(Component comp) { while (true) { if (comp == null) { return JOptionPane.getRootFrame(); } if (comp instanceof Frame || comp instanceof Dialog) { return (Window) comp; } comp = comp.getParent(); } }
4
public Server() { // Show server view serverView = new ServerView(this); serverView.getFrame().setVisible(true); // Start server and listen from port 1099 Rmi rmiService = null; try { rmiService = new RmiImpl(); Registry registry = LocateRegistry.createRegistry(1099); registry.rebind("pcs", rmiService); // Object will be used as a // service by clients } catch (RemoteException e) { // Problem with starting the server JOptionPane.showMessageDialog(null, "Server can't start service. Please restart server."); e.printStackTrace(); } // Start server updater thread serverUpdater = new ServerUpdater(); serverUpdater.start(); // Start code runner thread codeRunnerThread = new CodeRunnerThread(); codeRunnerThread.start(); }
1
public void mouseClicked(MouseEvent pEvent) { mLastMouseClickedPosition = pEvent.getPoint(); Point p = pEvent.getComponent().getLocationOnScreen(); mLastMouseClickedPosition.x += p.getX(); mLastMouseClickedPosition.y += p.getY(); TableViewAdapter adapter = (TableViewAdapter) getModel(); mCurrentCollumn = adapter.getColumn(getColumnModel().getColumn(columnAtPoint(pEvent.getPoint())).getModelIndex()); if (pEvent.getComponent().getCursor().getType() == Cursor.E_RESIZE_CURSOR) { if (pEvent.getClickCount() == 2) { TableColumnModel model = getColumnModel(); JTableHeader header = getTableHeader(); int columnIndex = -1; int length = Integer.MAX_VALUE; for (int i = 0; i < model.getColumnCount(); i++) { Rectangle rect = header.getHeaderRect(i); int newLength = Math.abs(rect.x + rect.width - pEvent.getX()); if (newLength < length) { columnIndex = i; length = newLength; } } autoSizeColumn(columnIndex); } } else if (pEvent.isMetaDown()) { mMenuItemSearch.setEnabled(mCurrentCollumn.isSearchable()); mPopupMenu.pack(); mPopupMenu.setLocation(mLastMouseClickedPosition); mPopupMenu.setVisible(true); } else if (pEvent.isControlDown() && mCurrentCollumn.isSearchable()) { menuItemSearchActionPerformed(null); } else if (mCurrentCollumn != null && mCurrentCollumn.isSortable()) { List selection = getSelectedRowObjects(); adapter.sort(mCurrentCollumn); getTableHeader().repaint(); addRowSelection(selection); } }
9
public void actionPerformed(ActionEvent e) { if (e.getSource() == buttonPlay) { wait = !wait; } else if (e.getSource() == buttonPrev) { wait = true; view.controller().prev(); view.flush(); repaint(); } else if (e.getSource() == buttonNext) { wait = true; view.controller().next(); view.flush(); repaint(); } else if (e.getSource() == buttonReset) { wait = true; while(view.controller().hasPrev()) { view.controller().prev(); } view.flush(); repaint(); } else if (e.getSource() == buttonKey) { panel.toggleKey(); } }
6
public TileMap() { for (int x = 0; x < 16; x++) { for (int y = 0; y < 10; y++) { putTile(Tile.GRASS_1, x, y); } } }
2
protected static Instances getMiningSchemaAsInstances(Element model, Instances dataDictionary) throws Exception { FastVector attInfo = new FastVector(); NodeList fieldList = model.getElementsByTagName("MiningField"); int classIndex = -1; int addedCount = 0; for (int i = 0; i < fieldList.getLength(); i++) { Node miningField = fieldList.item(i); if (miningField.getNodeType() == Node.ELEMENT_NODE) { Element miningFieldEl = (Element)miningField; String name = miningFieldEl.getAttribute("name"); String usage = miningFieldEl.getAttribute("usageType"); // TO-DO: also missing value replacement etc. // find this attribute in the dataDictionary Attribute miningAtt = dataDictionary.attribute(name); if (miningAtt != null) { if (usage.length() == 0 || usage.equals("active") || usage.equals("predicted")) { attInfo.addElement(miningAtt); addedCount++; } if (usage.equals("predicted")) { classIndex = addedCount - 1; } } else { throw new Exception("Can't find mining field: " + name + " in the data dictionary."); } } } Instances insts = new Instances("miningSchema", attInfo, 0); // System.out.println(insts); if (classIndex != -1) { insts.setClassIndex(classIndex); } return insts; }
8
private boolean jj_2_61(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_61(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(60, xla); } }
1
public boolean saveSmfUser(String user) throws ClassNotFoundException, SQLException { // SMF activation sqlClass(); sqlCon(); if (!customField.isEmpty()) { query = "SELECT id_member FROM " + tablePref + "themes WHERE variable='" + smfFieldValue() + "' AND value='" + user + "'"; ResultSet rs = SELECT(query); if (rs.next()) { query = "UPDATE " + tablePref + "members SET is_activated='1' WHERE id_member='" + rs.getInt("id_member") + "'"; UPDATE(query); query = "SELECT * FROM " + tablePref + "members WHERE id_member=" + rs.getInt("id_member") + " AND is_activated='1'"; rs = SELECT(query); if (rs.next()) { plugin.sendInfo(ForumAA.server.getPlayer(user), "Your account has been activated."); closeCon(); return true; } else { plugin.sendError(ForumAA.server.getPlayer(user), "Your account has not been activated"); closeCon(); return false; } } else { plugin.sendError(ForumAA.server.getPlayer(user), "Couldn't find your username"); closeCon(); return false; } } else { query = "UPDATE " + tablePref + "members SET is_activated='1' WHERE member_name='" + user + "'"; UPDATE(query); query = "SELECT * FROM " + tablePref + "members WHERE member_name='" + user + "' AND is_activated='1'"; ResultSet rs = SELECT(query); if (rs.next()) { plugin.sendInfo(ForumAA.server.getPlayer(user), "Your account has been activated."); closeCon(); return true; } else { plugin.sendError(ForumAA.server.getPlayer(user), "Your account has not been activated"); closeCon(); return false; } } }
4
@Override public Void call() { final String timestamp = this.writer.timestamp.format(new Date()); this.markers.clear(); for (final World world : this.writer.plugin.getServer().getWorlds()) { for (final Wolf wolf : world.getEntitiesByClass(Wolf.class)) { if (!wolf.isTamed() || !(wolf.getOwner() instanceof OfflinePlayer)) continue; final OfflinePlayer owner = (OfflinePlayer) wolf.getOwner(); final Map<String, Object> marker = new HashMap<String, Object>(); marker.put("id", this.getType().id); marker.put("msg", owner.getName()); marker.put("world", wolf.getLocation().getWorld().getName()); marker.put("x", wolf.getLocation().getX()); marker.put("y", wolf.getLocation().getY()); marker.put("z", wolf.getLocation().getZ()); marker.put("timestamp", timestamp); this.markers.add(marker); } } return null; }
4
public static Object getObjectFromRequestParameter(String requestParameterName, Converter converter, UIComponent component) { String theId = JsfUtil.getRequestParameter(requestParameterName); return converter.getAsObject(FacesContext.getCurrentInstance(), component, theId); }
0
private void checkMagicChar(char expected, String position) throws IOException { int magic = this.in.read(); if (magic != expected) { throw new IOException("Stream is not BZip2 formatted: expected '" + expected + "' as " + position + " byte but got '" + (char) magic + "'"); } }
1
protected void createReaderWriter() throws JoeException { // try to create an appropriate reader-writer ourReaderWriter = new PdbReaderWriter() ; // if we fail ... if (ourReaderWriter == null) { throw new JoeException(UNABLE_TO_CREATE_OBJECT) ; } // end if } // end protected method PdbReaderWriter
1
private static boolean isInteger(String lexeme) { try { return Integer.signum(Integer.parseInt(lexeme)) != -1; } catch (NumberFormatException e) { return false; } }
1
public final void setDistance(double distance) { this.distance = distance; parametersToNumbers.put("distance", new Double(distance)); }
0
public BMPImage copyPart(int x, int y, int width, int height) { BMPImage image = new BMPImage(this); image.imageHeader.biHeight = height; image.imageHeader.biWidth = width; image.fileHeader.bfSize = FILE_HEADER_SIZE + IMAGE_HEADER_SIZE + height * width; BMPColor[][] bitmap = new BMPColor[width + 2][height + 2]; if(height > pixelData.bitmap.length) { height = pixelData.bitmap.length; } if(width > pixelData.bitmap[0].length) { width = pixelData.bitmap[0].length; } for(int j = 0; j <= height + 1; j++) { for(int i = 0; i <= width + 1; i++) { bitmap[j][i] = pixelData.bitmap[y + j][x + i]; } } for(int i = 1; i <= width; i++) { bitmap[0][i] = new BMPColor(bitmap[1][i]); bitmap[height + 1][i] = new BMPColor(bitmap[height][i]); } for(int i = 1; i <= height; i++) { bitmap[i][0] = new BMPColor(bitmap[i][1]); bitmap[i][width+1] = new BMPColor(bitmap[i][width]); } bitmap[0][0] = new BMPColor(); bitmap[height+1][0] = new BMPColor(); bitmap[0][width+1] = new BMPColor(); bitmap[height+1][width+1] = new BMPColor(); bitmap[0][0].blue = (bitmap[1][0].blue + bitmap[0][1].blue)/2; bitmap[height+1][0].blue = (bitmap[height][0].blue + bitmap[height+1][1].blue)/2; bitmap[0][width+1].blue = (bitmap[0][width].blue + bitmap[1][width+1].blue)/2; bitmap[height+1][width+1].blue = (bitmap[height+1][width].blue + bitmap[height][width+1].blue)/2; bitmap[0][0].green = (bitmap[1][0].green + bitmap[0][1].green)/2; bitmap[height+1][0].green = (bitmap[height][0].green + bitmap[height+1][1].green)/2; bitmap[0][width+1].green = (bitmap[0][width].green + bitmap[1][width+1].green)/2; bitmap[height+1][width+1].green = (bitmap[height+1][width].green + bitmap[height][width+1].green)/2; bitmap[0][0].red = (bitmap[1][0].red + bitmap[0][1].red)/2; bitmap[height+1][0].red = (bitmap[height][0].red + bitmap[height+1][1].red)/2; bitmap[0][width+1].red = (bitmap[0][width].red + bitmap[1][width+1].red)/2; bitmap[height+1][width+1].red = (bitmap[height+1][width].red + bitmap[height][width+1].red)/2; image.pixelData.bitmap = bitmap; return image; }
6
public void setTelefon2(String telefon2) { this.telefon2 = telefon2; }
0
@EventHandler(priority=EventPriority.NORMAL) public void exploded(EntityExplodeEvent event) { Iterator<Block> i = event.blockList().iterator(); List<Block> blockToHandleList= new LinkedList<Block> (); while(i.hasNext()) { Block block = (Block)i.next(); CustomBlock cblock = this.plugin.getCustomBlock(block); if (cblock != null) { blockToHandleList.add(block); } } Iterator<Block> iter = blockToHandleList.iterator(); while(iter.hasNext()) { Block block = (Block)iter.next(); CustomBlock cblock = this.plugin.getCustomBlock(block); if (cblock != null) { cblock.handleExplode(event, block); } } }
4
private void createReferenceFile(final ObjectStreamClass osc) { final File referenceDir = context.getReferenceBaseDir(); final File referenceFile = new File(new File(referenceDir, osc.getName()), Long .toString(osc.getSerialVersionUID()) + ".ser"); if (!referenceFile.isFile()) { if (!referenceDir.isDirectory()) { throw new AssertionFailedError("Missing serialization reference directory: " + referenceDir.getAbsolutePath()); } if (!referenceFile.getParentFile().isDirectory()) { referenceFile.getParentFile().mkdir(); } try { try { final FileOutputStream out = new FileOutputStream(referenceFile); try { out.write(baos.toByteArray()); } catch (final IOException e) { throw new AssertionFailedError("Cannot write missing reference file " + referenceFile.getAbsolutePath() + ". " + e.getMessage()); } finally { out.close(); } } catch (final FileNotFoundException e) { throw new AssertionFailedError("Cannot create missing reference file " + referenceFile.getAbsolutePath() + ". " + e.getMessage()); } catch (final IOException e) { throw new AssertionFailedError("Cannot close missing reference file " + referenceFile.getAbsolutePath() + ". " + e.getMessage()); } } catch (final AssertionFailedError e) { if (referenceFile.exists()) { referenceFile.delete(); } throw e; } throw new AssertionFailedError("Missing reference file " + referenceFile.getAbsolutePath() + " created."); } }
8
public void print(List<String> IdsToStrings,String pad) { Iterator<T> biIter=BigramCounts.keySet().iterator(); T myValue; UnigramCountsModel<K> model; int getVal; if (pad==null) { pad=""; } while (biIter.hasNext()) { myValue=biIter.next(); model=BigramCounts.get(myValue); if ((IdsToStrings!=null) && (myValue instanceof Integer)) { getVal=((Integer)myValue).intValue(); System.out.println(pad+"Bigram<"+myValue.getClass().getName()+">:"+IdsToStrings.get(getVal)+"|+|"); } else if (myValue instanceof BigramModel) { System.out.println(pad+"Bigram<"+myValue.getClass().getName()+">:"+((BigramModel)myValue).toString(IdsToStrings)+"|+|"); } else { System.out.println(pad+"Bigram<"+myValue.getClass().getName()+">:"+myValue+"|+|"); } model.print(IdsToStrings,pad+pad); } }
5
public void removeTray(Tray tray) { if (this.trays.contains(tray)) { this.trays.remove(tray); tray.setStorageUnit(null); } }
1
private Object[] readIndexTenor(XMLStreamReader2 streamReader) throws XMLStreamException { Integer periodMultiplier = null; PeriodEnum period = null; int startingDepth = streamReader.getDepth(); while(streamReader.hasNext()) { switch(streamReader.next()) { case XMLEvent.START_ELEMENT: if(streamReader.getDepth() == startingDepth + 1) { String localName = streamReader.getLocalName(); if("periodMultiplier".equals(localName)) { periodMultiplier = Integer.parseInt(FpmlParser.readText(streamReader)); } else if("period".equals(localName)) { period = PeriodEnum.valueOf(FpmlParser.readText(streamReader)); } } break; case XMLEvent.END_ELEMENT: if(streamReader.getDepth() == startingDepth) { return new Object[]{periodMultiplier, period}; } } } throw new PricerException("No more events before element finished"); }
7
void decorate(AbstractAxisChart chart) { chart.setTitle(title); chart.setSize(plotSizeX, plotSizeY); int gridx = (maxX - minX) / 10; int gridy = (maxY - minY) / 10; if( (gridx > 0) && (gridy > 0) ) chart.setGrid((maxX - minX) / 10, (maxY - minY) / 10, 3, 2); // Adding axis info to chart. chart.addXAxisLabels(AxisLabelsFactory.newAxisLabels(labelList)); chart.addXAxisLabels(AxisLabelsFactory.newAxisLabels(xAxisLabel, 50.0)); chart.addYAxisLabels(AxisLabelsFactory.newNumericRangeAxisLabels(minY, maxY)); chart.addYAxisLabels(AxisLabelsFactory.newAxisLabels(yAxisLabel, 50.0)); }
2
public long getDaysOlder(String personA, String personB) throws Exception { String[] personDataA = getPersonData(personA); String[] personDataB = getPersonData(personB); long agePersonA = getDaysFromSeconds(getAgeInSeconds(personDataA[DOB_INDEX])); long agePersonB = getDaysFromSeconds(getAgeInSeconds(personDataB[DOB_INDEX])); return agePersonA - agePersonB; }
0
public void showItem(Item item) { //when messing with craft book selector w/o item first loaded if (item == null) { return; } currentItem = item; //CraftIntoPanel treats all Items equally. guiCraftIntoPanel.craftTable.setData(item); //Casting for CraftComponentPanel and ItemInfoPanel. switch(item.getType()) { case MATERIAL: showMaterial((Material) item); break; case CRAFTABLE: showCraftable((Craftable) item); break; case CRAFTBOOK: showCraftBook((CraftBook) item); break; default: try { throw new Exception(); } catch (Exception e) { System.err.println("Unknown item type."); e.printStackTrace(); } break; } }
5
@Override public boolean replicaAll(Hashtable<String, Integer> objects, String server) throws RemoteException { //Interface to access other server to get all objects InterfaceAcesso ia = null; //Was replicaAll a success? boolean success = true; //Looking for the server try { ia = (InterfaceAcesso) Naming.lookup(server); } catch(MalformedURLException e) { System.err.println("Server.replicaAll catch MalformedURLException"); e.printStackTrace(); success = false; } catch(NotBoundException e) { System.err.println("Server.replicaAll catch NotBoundException"); e.printStackTrace(); success = false; } Set<String> objs = objects.keySet(); System.out.println("Coping objects from " + ia); //Get all objects for(String s: objs) { Integer id = objects.get(s); try { Box obj = ia.recupera(id); h.put(id, obj); } catch (ObjetoNaoEncontradoException e) { System.err.println("Server.replicaAll catch ObjetoNaoEncontradoException to ID " + id.toString()); e.printStackTrace(); success = false; } } System.out.println("All objects copied from " + ia); return success; }
4
void updateHitboxes(Element frame) { blue_hitboxes.clear(); red_hitboxes.clear(); boolean empty_red = false; boolean empty_blue = false; for(Node hitbox=frame.getFirstChild();hitbox!=null;hitbox=hitbox.getNextSibling())//Hitbox loop { if(hitbox.getNodeName().equals("Hitboxes")) { if(((Element)hitbox).getAttribute("variable").equals("red")) { empty_red=true; for(Node hitbox_red=hitbox.getFirstChild();hitbox_red!=null;hitbox_red=hitbox_red.getNextSibling())//Red Hitboxes loop { //!!! if(hitbox_red.getNodeName().equals("Hitbox")) { int x1 = Integer.parseInt(((Element)hitbox_red).getAttribute("x1")); int y1 = Integer.parseInt(((Element)hitbox_red).getAttribute("y1")); int x2 = Integer.parseInt(((Element)hitbox_red).getAttribute("x2")); int y2 = Integer.parseInt(((Element)hitbox_red).getAttribute("y2")); red_hitboxes.add(new Hitbox(x1, y1, x2, y2)); empty_red=false; } } } if(((Element)hitbox).getAttribute("variable").equals("blue")) { empty_blue=true; for(Node hitbox_blue=hitbox.getFirstChild();hitbox_blue!=null;hitbox_blue=hitbox_blue.getNextSibling())//Blue Hitboxes loop { if(hitbox_blue.getNodeName().equals("Hitbox")) { int x1 = Integer.parseInt(((Element)hitbox_blue).getAttribute("x1")); int y1 = Integer.parseInt(((Element)hitbox_blue).getAttribute("y1")); int x2 = Integer.parseInt(((Element)hitbox_blue).getAttribute("x2")); int y2 = Integer.parseInt(((Element)hitbox_blue).getAttribute("y2")); blue_hitboxes.add(new Hitbox(x1, y1, x2, y2)); empty_blue=false; } } } } } drawHitboxes(empty_blue, empty_red); saveHitboxes(); }
8
public String bitrate_string() { if (h_vbr == true) { return Integer.toString(bitrate()/1000)+" kb/s"; } else return bitrate_str[h_version][h_layer - 1][h_bitrate_index]; }
1
public static<X> X getMiddle(X[] a) { return a[a.length / 2]; }
0
public static DBQueryUserResult getUser(String username, String password) { preQueryConnect(); Actions.addAction(new Action(ActionType.INFO, "User query requested for input: " + username + ".")); DBQueryUserResult userQueryResult = null; if(username.contains("'") || username.contains("\"") || username.contains(" ")) { return null; } synchronized(dbConnection) { Statement st = null; ResultSet res = null; try { st = dbConnection.createStatement(); res = st.executeQuery( "SELECT * FROM " + DBConstants.USER_TABLE + " WHERE " + DBConstants.USER_USERNAME + "='" + username + "'" + " AND " + DBConstants.USER_PASSWORD + " LIKE BINARY '" + password + "' LIMIT 1"); /* Return null if the user was not found in the database */ if(!res.next()) { Actions.addAction(new Action(ActionType.INFO, "User Query returned 0x00.")); return null; } userQueryResult = new DBQueryUserResult(res); Actions.addAction(new Action(ActionType.INFO, "Query Successful! Returning User: " + userQueryResult.getUsername() + ".")); } catch (SQLException e) { Actions.addAction(new Action(ActionType.ERROR, "User Query had an error. Possibility of MySQL Injection Attempt. " + e.toString())); } finally { postQueryCleanup(dbConnection, st, res); } } return userQueryResult; }
5
public void setCombinacion(int combinacion) { this.combinacion = combinacion; }
0
public boolean isInitial(int c){ return Character.isLetter(c) || c == '*' || c == '/' || c == '>'|| c == '<' || c == '=' || c == '?' || c == '!' || c == '.'; }
8
private static String convertNumber(String number) { if (number.length() > 3) throw new NumberFormatException( "La longitud maxima debe ser 3 digitos"); // Caso especial con el 100 if (number.equals("100")) { return "CIEN"; } StringBuilder output = new StringBuilder(); if (getDigitAt(number, 2) != 0) output.append(CENTENAS[getDigitAt(number, 2) - 1]); int k = Integer.parseInt(String.valueOf(getDigitAt(number, 1)) + String.valueOf(getDigitAt(number, 0))); if (k <= 20) output.append(UNIDADES[k]); else if (k > 30 && getDigitAt(number, 0) != 0) output.append(DECENAS[getDigitAt(number, 1) - 2] + "Y " + UNIDADES[getDigitAt(number, 0)]); else output.append(DECENAS[getDigitAt(number, 1) - 2] + UNIDADES[getDigitAt(number, 0)]); return output.toString(); }
6
@Override public void publish(LogRecord record) { if (painted.get()) { synchronized (lock) { final LogEntry peek = logEntries.peekLast(); if (peek == null || !peek.text.equals(record.getMessage())) { logEntries.offer(new LogEntry(record)); } else if (peek.text.equals(record.getMessage())) { if (logEntries.removeLastOccurrence(peek)) { peek.timeSent = System.currentTimeMillis(); peek.alpha = 1f; logEntries.offer(peek); } else { logEntries.offer(new LogEntry(record)); } } } } }
5
@Override public void setValues(Component target, int tweenType, float[] newValues) { switch (tweenType) { case X: target.setLocation(Math.round(newValues[0]), target.getY()); break; case Y: target.setLocation(target.getX(), Math.round(newValues[0])); break; case XY: target.setLocation(Math.round(newValues[0]), Math.round(newValues[1])); break; case W: target.setSize(Math.round(newValues[0]), target.getHeight()); target.validate(); break; case H: target.setSize(target.getWidth(), Math.round(newValues[0])); target.validate(); break; case WH: target.setSize(Math.round(newValues[0]), Math.round(newValues[1])); target.validate(); break; case XYWH: target.setBounds(Math.round(newValues[0]), Math.round(newValues[1]), Math.round(newValues[2]), Math.round(newValues[3])); target.validate(); break; } }
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LadoSe other = (LadoSe) obj; if (cabecalho == null) { if (other.cabecalho != null) return false; } else if (!cabecalho.equals(other.cabecalho)) return false; if (evidencia == null) { if (other.evidencia != null) return false; } else if (!evidencia.equals(other.evidencia)) return false; return true; }
9
private void processMoveFromBoard(MouseEvent e) { int col = findCol(e.getX()); List<Card> possibleCards = game.getBoard().get(col); int index = findCardIndex(possibleCards, e.getY(), col == 0); if (index == -1) { //Indicates none found. return; } if (possibleCards.get(index) != null) { if (game.isValidNewMove(col, index)) { activeMove = new CardMove(index, col, game); } else { storeError("Cannot move that card, cards beneath it are not the same suit or correctly ordered"); } } }
3
public void mainAction() { ship s = getShipToPerformAction(); if(getTurnDecay() == 0) { s.addHardpoints(h); } else { modifyTurnDecay(-1); } }
1
public BufMgr( int numbufs, String replacerArg ) { numBuffers = numbufs; frmeTable = new FrameDesc[numBuffers]; bufPool = new byte[numBuffers][MAX_SPACE]; frmeTable = new FrameDesc[numBuffers]; // Initialize the Buffer Table with empty frame descriptions for (int i = 0; i < numBuffers; i++) frmeTable[i] = new FrameDesc(); replacer = new Clock(this); // You must setBufferManager or the state array is not initialized // NOTE: This seems redundant and should be part of the replacer constructor replacer.setBufferManager( this ); } // end constructor
1
@Override public void run() { setStopped(false); try { while ((!Thread.currentThread().isInterrupted()) && (!isStopped())) { Thread.sleep(IDLE_TIMEOUT / 2); try { if (!isStopped()) { send(ISession.KEEPALIVE_MESSAGE, null); } } catch (Exception ex) { catchException(this, ex); } } } catch (InterruptedException ex) { //..break in sleep } finally { //..free resources } }
5
private long readLong_slow (boolean optimizePositive) { // The buffer is guaranteed to have at least 1 byte. int b = buffer[position++]; long result = b & 0x7F; if ((b & 0x80) != 0) { require(1); byte[] buffer = this.buffer; b = buffer[position++]; result |= (b & 0x7F) << 7; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (b & 0x7F) << 14; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (b & 0x7F) << 21; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (long)(b & 0x7F) << 28; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (long)(b & 0x7F) << 35; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (long)(b & 0x7F) << 42; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (long)(b & 0x7F) << 49; if ((b & 0x80) != 0) { require(1); b = buffer[position++]; result |= (long)b << 56; } } } } } } } } if (!optimizePositive) result = (result >>> 1) ^ -(result & 1); return result; }
9
@RequestMapping(value = "/list", method = RequestMethod.GET) public String start(ModelMap modelMap, HttpSession session) { List<Content> restrictedContentList = new ArrayList<>(); Integer numberOfElementsToDisplay = (contentService.getAll().size() >= 5) ? 5 : contentService.getAll().size(); if (session.getAttribute("number") != null && ((Integer)session.getAttribute("number")) >= 5) { numberOfElementsToDisplay = (Integer) session.getAttribute("number"); } if (numberOfElementsToDisplay > 0) { for (int i = 0; i < numberOfElementsToDisplay; i++) { restrictedContentList.add(contentService.getAll().get(i)); } } modelMap.addAttribute("contentList", restrictedContentList); modelMap.addAttribute("contentForm", new ContentForm()); return "list"; }
5
public boolean add(T t) { boolean result = false; if(array.length <= index) { T[] newArray = (T[])Array.newInstance(type, array.length * 2); for(int i = 0; i < array.length; i++){ newArray[i] = array[i]; } array = newArray; } array[index] = t; index++; result = true; return result; }
2
public boolean equalsXMLElement(IXMLElement elt) { if (! this.name.equals(elt.getName())) { return false; } if (this.attributes.size() != elt.getAttributeCount()) { return false; } Enumeration en = this.attributes.elements(); while (en.hasMoreElements()) { XMLAttribute attr = (XMLAttribute) en.nextElement(); if (! elt.hasAttribute(attr.getName(), attr.getNamespace())) { return false; } String value = elt.getAttribute(attr.getName(), attr.getNamespace(), null); if (! attr.getValue().equals(value)) { return false; } String type = elt.getAttributeType(attr.getName(), attr.getNamespace()); if (! attr.getType().equals(type)) { return false; } } if (this.children.size() != elt.getChildrenCount()) { return false; } for (int i = 0; i < this.children.size(); i++) { IXMLElement child1 = this.getChildAtIndex(i); IXMLElement child2 = elt.getChildAtIndex(i); if (! child1.equalsXMLElement(child2)) { return false; } } return true; }
9
public CallType getCallType() { return callType; }
0
public static SeqDist getClosestInFile(int[] u, File file) throws IOException { /* * ///!!!\\\ all the sequences in the file must have the same size */ DnaFileReader reader = new DnaFileReader(file); int nSeq = reader.totalNumberofSeq(); int[] bestSeq = null, curSeq = null; int bestDist = Integer.MAX_VALUE; int[] t = reader.readSequence(); // Enable exceptions and omit all subsequent error checks JCudaDriver.setExceptionsEnabled(true); // Create the PTX file by calling the NVCC String ptxFileName = preparePtxFile("edition_distance/DnaDistanceKernel.cu"); // Initialize the driver and create a context for the first device. cuInit(0); CUdevice device = new CUdevice(); cuDeviceGet(device, 0); CUcontext context = new CUcontext(); cuCtxCreate(context, 0, device); // Load the ptx file. CUmodule module = new CUmodule(); cuModuleLoad(module, ptxFileName); // Obtain a function pointer to the "add" function. CUfunction function = new CUfunction(); cuModuleGetFunction(function, module, "distance"); // ensures u.length >= t.length if (u.length < t.length){ int[] tmp = u; u = t; t = tmp; } int kmax = u.length + t.length ; int diagSize = t.length + 1; // prepare host diags to copy int[] hostDiag1 = {0}; int[] hostDiag2 = {1, 1}; // Allocate the device inputs CUdeviceptr deviceInputU = new CUdeviceptr(); cuMemAlloc(deviceInputU, u.length * Sizeof.INT); CUdeviceptr deviceInputT = new CUdeviceptr(); cuMemAlloc(deviceInputT, t.length * Sizeof.INT); // Allocate the device diags CUdeviceptr deviceDiag0 = new CUdeviceptr(); cuMemAlloc(deviceDiag0, diagSize * Sizeof.INT); CUdeviceptr deviceDiag1 = new CUdeviceptr(); cuMemAlloc(deviceDiag1, diagSize * Sizeof.INT); CUdeviceptr deviceDiag2 = new CUdeviceptr(); cuMemAlloc(deviceDiag2, diagSize * Sizeof.INT); int blockSizeX = 672; int[] res = new int[1]; int finalDiag = (kmax+1) % 3; for(int i = 0 ; i < nSeq ; i++){ if (i != 0){ t = reader.readSequence(); // ensures u.length >= t.length if (u.length < t.length){ int[] tmp = u; u = t; t = tmp; } } cuMemcpyHtoD(deviceInputU, Pointer.to(u), u.length * Sizeof.INT); cuMemcpyHtoD(deviceInputT, Pointer.to(t), t.length * Sizeof.INT); cuMemcpyHtoD(deviceDiag1, Pointer.to(hostDiag1), Sizeof.INT); cuMemcpyHtoD(deviceDiag2, Pointer.to(hostDiag2), 2 * Sizeof.INT); // Set up the kernel parameters: A pointer to an array // of pointers which point to the actual values. Pointer kernelParameters = Pointer.to( Pointer.to(new int[]{u.length}), Pointer.to(new int[]{t.length}), Pointer.to(new int[]{kmax}), Pointer.to(deviceInputU), Pointer.to(deviceInputT), Pointer.to(deviceDiag0), Pointer.to(deviceDiag1), Pointer.to(deviceDiag2) ); // Call the kernel function. cuLaunchKernel(function, 1, 1, 1, // Grid dimension blockSizeX, 1, 1, // Block dimension 0, null, // Shared memory size and stream kernelParameters, null // Kernel- and extra parameters ); cuCtxSynchronize(); // Allocate host output memory and copy the device diag2 to the host switch(finalDiag){ case 0: cuMemcpyDtoH(Pointer.to(res), deviceDiag0.withByteOffset(t.length * Sizeof.INT), Sizeof.INT); break; case 1: cuMemcpyDtoH(Pointer.to(res), deviceDiag1.withByteOffset(t.length * Sizeof.INT), Sizeof.INT); break; case 2: cuMemcpyDtoH(Pointer.to(res), deviceDiag2.withByteOffset(t.length * Sizeof.INT), Sizeof.INT); break; } System.err.println("Processed distance #" + i +": "+res[0]); if (res[0] < bestDist){ bestSeq = curSeq; bestDist = res[0]; } } // Clean up. cuMemFree(deviceInputU); cuMemFree(deviceInputT); cuMemFree(deviceDiag0); cuMemFree(deviceDiag1); cuMemFree(deviceDiag2); return new SeqDist(bestSeq, bestDist); }
8
private String getNameforNum(int n) { //SWAP 1 TEAM 5. /* * QUALITY CHANGES * Looked things up and found an easier way to do days of the week; a lot easier to understand * while compressing 20 lines of useless duplicate code. */ if(n == 1) { return "Sunday"; } else if (n > 1 && n <= 7){ return new DateFormatSymbols().getWeekdays()[n-1]; } //1 is monday, 2 is tuesday return null; }
3
private void calculateGreatMargin(Double fieldA, Double factor) { if((ourProportion.compareTo(fieldA) <= 0) && ((purchaseCost.compareTo(0.0) != 0) ? minMarginOnPosition.compareTo((minCostOnAll - 0.02) / purchaseCost * 100.0 - 100.0) < 0 : minMarginOnPosition.compareTo(0.0) < 0)) { if(settlementCost.compareTo(0.0) != 0) paymentAdjustmentFactor = ((minCostOnAll - 0.02) / settlementCost * 100.0 - 100.0) * ((100.0 + factor) / 100.0); } else if((purchaseCost.compareTo(0.0) != 0) ? minMarginOnPosition.compareTo((avarageCostOnAll - 0.02) / purchaseCost * 100.0 - 100.0) < 0 : minMarginOnPosition.compareTo(0.0) < 0) { if(settlementCost.compareTo(0.0) != 0) paymentAdjustmentFactor = ((avarageCostOnAll - 0.02) / settlementCost * 100.0 - 100.0) * ((100.0 + factor) / 100.0); } else { if(settlementCost.compareTo(0.0) != 0) paymentAdjustmentFactor = saleCost / settlementCost * 100.0 - 100.0; } }
8
private void notifyListeners(AccessToken token) { for (TokenRetrievedListener listener : mListeners) if (listener != null) listener.notify(token); }
2
@Deprecated public static final Object getMethodValue(OgnlContext context, Object target, String propertyName) throws OgnlException, IllegalAccessException, NoSuchMethodException, IntrospectionException { return getMethodValue(context, target, propertyName, false); }
9
public double rawAllResponsesStandardDeviation(){ if(!this.dataPreprocessed)this.preprocessData(); if(!this.variancesCalculated)this.meansAndVariances(); return this.rawAllResponsesStandardDeviation; }
2
public static void saveAs(ArrayList<String> lines) throws IOException { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Save file as? "); int result = chooser.showSaveDialog(null); if (result == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); if (file != null) { fileName = file.getCanonicalPath(); writeTo(fileName, lines); } } }
2
private final void calcGaps(ComponentWrapper before, CC befCC, ComponentWrapper after, CC aftCC, String tag, boolean flowX, boolean isLTR) { ContainerWrapper par = comp.getParent(); int parW = par.getWidth(); int parH = par.getHeight(); BoundSize befGap = before != null ? (flowX ? befCC.getHorizontal() : befCC.getVertical()).getGapAfter() : null; BoundSize aftGap = after != null ? (flowX ? aftCC.getHorizontal() : aftCC.getVertical()).getGapBefore() : null; mergeGapSizes(cc.getVertical().getComponentGaps(par, comp, befGap, (flowX ? null : before), tag, parH, 0, isLTR), false, true); mergeGapSizes(cc.getHorizontal().getComponentGaps(par, comp, befGap, (flowX ? before : null), tag, parW, 1, isLTR), true, true); mergeGapSizes(cc.getVertical().getComponentGaps(par, comp, aftGap, (flowX ? null : after), tag, parH, 2, isLTR), false, false); mergeGapSizes(cc.getHorizontal().getComponentGaps(par, comp, aftGap, (flowX ? after : null), tag, parW, 3, isLTR), true, false); }
8
public void setModel(Model model) { setSimulation(false); if (this.model != null) { this.model.unregisterListener(this); } this.model = model; final boolean isModelPresent = model != null; fileSave.setEnabled(isModelPresent && model.hasBackingFile()); fileSaveAs.setEnabled(isModelPresent); actionClear.setEnabled(isModelPresent); actionLaunchSimulation.setEnabled(isModelPresent && !model.getAccessPoints().isEmpty()); actionStopSimulation.setEnabled(false); toolAp.setEnabled(isModelPresent); toolRepeater.setEnabled(false); toolWall.setEnabled(isModelPresent); toolRoom.setEnabled(isModelPresent); toolDoor.setEnabled(false); if (!isModelPresent) { return; } final List<AccessPoint> aps = model.getAccessPoints(); comboBoxAp.setAlignmentX(Component.LEFT_ALIGNMENT); comboBoxAp.setModel(new DefaultComboBoxModel<>(aps.toArray(new AccessPoint[aps.size()]))); model.registerListener(this); }
4
private char escapedStringChar(J_PositionTrackingPushbackReader var1) throws IOException, J_InvalidSyntaxException { char var3 = (char)var1.read(); char var2; switch(var3) { case 34: var2 = 34; break; case 47: var2 = 47; break; case 92: var2 = 92; break; case 98: var2 = 8; break; case 102: var2 = 12; break; case 110: var2 = 10; break; case 114: var2 = 13; break; case 116: var2 = 9; break; case 117: var2 = (char)this.hexadecimalNumber(var1); break; default: throw new J_InvalidSyntaxException("Unrecognised escape character [" + var3 + "].", var1); } return var2; }
9
private void loginSuccess() { if (user != null) { System.out.println("username: " + user.getUsername()); this.setVisible(false); if (user.getRole().equals("Tutor")) { TutorGUI tutorGUI = new TutorGUI(user); tutorGUI.setSize(880, 500); tutorGUI.setLocation(250, 100); tutorGUI.setTitle("Debate"); tutorGUI.setVisible(true); } else if(!user.getRole().equals("Tutor") && user.getRole() != null) { DebateListGUI debateListGUI = new DebateListGUI(user); debateListGUI.setLocation(250, 100); debateListGUI.setTitle("Debates"); debateListGUI.setVisible(true); } } else { System.out.println("user is null"); } }
4
@Test public void testGetInstruction() throws IOException { System.out.println("getInstruction"); String antBrainFile = "cleverbrain1.brain"; AntBrain instance = new AntBrain(antBrainFile); int currState = 0; Sense expResult = new Sense(Sense.dirFromString("here"),32, 1,Sense.condFromString("home")); Sense result = (Sense)instance.getInstruction(0); assertEquals(expResult.getCondVal(), result.getCondVal()); assertEquals(expResult.getS1(), result.getS1()); assertEquals(expResult.getS2(), result.getS2()); assertEquals(expResult.getSenseDirVal(), result.getSenseDirVal()); }
0
static private DamageCause getType(String str) { // Renamed if (str.equalsIgnoreCase("burning")) { return DamageCause.FIRE_TICK; } // By Name DamageCause[] types = getTypes(); for (int i = 0; i < types.length; i++) { if (types[i].name().equalsIgnoreCase(str)) return types[i]; } for (int i = 0; i < types.length; i++) { if (types[i].name().replace("_", "").equalsIgnoreCase(str)) return types[i]; } for (int i = 0; i < types.length; i++) { if (types[i].name().replace("_", " ").equalsIgnoreCase(str)) return types[i]; } throw new RuntimeException("Unknown damage cause: " + str); }
7
public static InformationStatusEnum fromString(String v) { if (v != null) { for (InformationStatusEnum c : InformationStatusEnum.values()) { if (v.equalsIgnoreCase(c.toString())) { return c; } } } throw new IllegalArgumentException(v); }
3
public FloodWorld(Player.PlayerType playerType) { super(80, 80, 10); backgroundMusic.playLoop(); setPaintOrder(MuteButton.class, Overlay.class, Counter.class, Coins.class, MenuBar.class, Player.class, Bag.class, Coin.class, Water.class, Floodbank.class); for(int i=0; i<=80; i++) { for(int j=0; j<=30; j++) { addObject(new Water(), i, j); } } for(int i = 0; i <= 80; i++) { for(int j = 50; j <= 70; j++) { addObject(new Meadow(), i, j); } } addObject(new MenuBar2(), 39, 75); for(int i = 0; i <= 80; i++) { for(int j = 30; j <= 50; j++) { addObject(new Floodbank(), i, j); } } addObject(player = Player.createPlayer(playerType), 40, 67); scoreCounter = new Score("Score: "); addObject(scoreCounter, 6, 74); coinCounter = new Coins("Coins: "); addObject(coinCounter, 6, 76); addObject(muteButton = new MuteButton(), 75, 75); muteButton.registerSound(backgroundMusic); }
6
public Element parseElement(Scanner in) throws IOException { in.read(); if (in.isSymbol("%")) { return parseReference(in, new IntegerElement()); } else if (in.isSymbol("$")) { return parseReference(in, new StringElement()); } else if (in.isSymbol("*")) { return parseReference(in, new StarElement()); } else if (in.isSymbol("[")) { List<String> ls = new ArrayList<String>(); for (; ; ) { in.read(); if (in.isName()) { ls.add(in.getToken()); } else if (in.isSymbol("]")) { break; } else if (!in.isSymbol("|")) { in.error("Expected | or ] instead of `" + in.getToken() + "'"); } } String[] values = ls.toArray(new String[ls.size()]); return parseReference(in, new OptionsElement(values)); // } else if (in.isSymbol("{")) { // parseReference(in); // } else if (in.isSymbol("(")) { // parseReference(in); } return null; }
8
@Override public String toString() { return describeNode(); }
0
public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); switch(key) { case KeyEvent.VK_F2 : if(!this.live) { this.live = true; this.life = 100; } break; case KeyEvent.VK_LEFT : bL = true; break; case KeyEvent.VK_UP : bU = true; break; case KeyEvent.VK_RIGHT : bR = true; break; case KeyEvent.VK_DOWN : bD = true; break; } locateDirection(); }
6
private int[] maxOneTimeShortProfit(int[] prices, int start, int end) { int bestBuy = -1, bestSell = -1, bestProfit = 0; int currentHigh = start; for (int i = start; i < end; i++) { int price = prices[i]; if (i < end - 1 && price > prices[i + 1]) { if (price >= prices[currentHigh]) { currentHigh = i; } } if (i == end - 1 || price < prices[i + 1]) { int profit = prices[currentHigh] - price; if (profit > bestProfit) { bestBuy = i; bestSell = currentHigh; bestProfit = profit; } } } return new int[] {bestBuy, bestSell, bestProfit}; }
7
private static void unmarshal() throws JAXBException, FileNotFoundException { JAXBContext context = JAXBContext.newInstance(AtomicValidator.class, UnaryLogicalNotOperator.class, BinaryLogicalAndOperator.class, BinaryLogicalOrOperator.class, BinaryEqualsOperator.class, BinaryValidator.class); System.out.println("Output from our XML File: "); Unmarshaller um = context.createUnmarshaller(); Validator binValidator = (Validator) um.unmarshal(new FileReader("validator.xml")); Employee_ToBeRemoved emp = new Employee_ToBeRemoved(); emp.setId(3); emp.setName("gaurav"); //emp.setDateOfJoining(new Date()); System.out.println(binValidator.validate(emp)); }
0
public void setId(int id) { this.id = id; }
0
@Override protected void processMouseMotionEvent(MouseEvent event) { mInAutoscroll = getAutoscrolls() && event.getID() == MouseEvent.MOUSE_DRAGGED; super.processMouseMotionEvent(event); mInAutoscroll = false; }
1
private void playNight() { doVoice(false); if (firstNight) { firstNight = false; bot.sendMessage(gameChan, getFromFile("FIRSTNIGHT", NARRATION)); } else { bot.sendMessage(gameChan, Colors.DARK_BLUE + getFromFile("NIGHTTIME", NARRATION)); } if (players2.numWolves() == 1) { bot.sendMessage(gameChan, getFromFile("WOLF-INSTRUCTIONS", nightTime, GAME)); } else { bot.sendMessage(gameChan, getFromFile("WOLVES-INSTRUCTIONS", nightTime, GAME)); } if (!players2.isSeerDead()) { bot.sendMessage(gameChan, getFromFile("SEER-INSTRUCTIONS", nightTime, GAME)); } waitForOutgoingQueueSizeIsZero(); gameTimer.schedule(new WereTask(), nightTime * 1000); }
3
public void processMouseMotionEvent(MouseEvent event) { transformMouseEvent(event); super.processMouseMotionEvent(event); }
0
public int removeDuplicates(int[] A) { if (A == null || A.length == 0) return 0; int current = A[0]; int step = 0; for (int i = 1; i < A.length; i++) { if(A[i] == current) step ++ ; else{ A[i -step] = A[i]; current = A[i]; } } return A.length - step; }
4
public int getStrength(){ int value = 0; for (Armor armor : armorList) { if(armor != null) value += armor.getStats().getStrength(); } return value; }
2
@Override public void onCollision(Player player) { if(canPickUp()){ pickup(); player.energy += amount; player.points += 5; player.energy = Math.min(player.energy, Constants.MAX_ENERGY); } }
1
public static int getScaledX(int xPosition, float tileX) { float dist = Math.abs(xPosition - tileX); float pos = dist - TILE_SCALE_FACTOR * dist * (dist - 1) / 2f; if (dist > SCALE_LIMIT_DIST) if (xPosition < tileX) return scaledXDistRight + ((int) dist - SCALE_LIMIT_DIST); else return scaledXDistLeft - ((int) dist - SCALE_LIMIT_DIST); if (xPosition < tileX) return CENTER_TILE_X + (int) (pos * Constants.TILE_WIDTH); else return CENTER_TILE_X - (int) (pos * Constants.TILE_WIDTH); }
3
public static void main(String[] args) { //配置一些用到的东西 ByteBuffer byteBuffer = ByteBuffer.allocate(1024); ByteBuffer buffer = ByteBuffer.wrap("hello world chiand".getBytes()); ByteBuffer randomBuffer; CharsetDecoder charsetDecoder = Charset.defaultCharset().newDecoder(); //打开通道 try(AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open()) { //是否打开 if (socketChannel.isOpen()) { //options Set<SocketOption<?>> socketOptions = socketChannel.supportedOptions(); System.out.println(socketOptions); //配置 socketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024); socketChannel.setOption(StandardSocketOptions.SO_SNDBUF, 4 * 1024); socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true); System.out.println(socketChannel.getLocalAddress()); //进行连接 Future<Void> connect = socketChannel.connect(new InetSocketAddress("127.0.0.1", 5555)); /*while (!connect.isDone()) { System.out.println("is connecting newwork...."); }*/ if (connect.get() == null) { //开始写消息 Future<Integer> write = socketChannel.write(buffer); /*if (!write.isDone()) { System.out.println("not write yet....."); }*/ /* if (write.isDone()) {*/ System.out.println("write count :"+write.get()); //读取 while (socketChannel.read(byteBuffer).get() != -1) { byteBuffer.flip(); System.out.println(charsetDecoder.decode(byteBuffer)); if (byteBuffer.hasRemaining()) { byteBuffer.compact(); }else{ byteBuffer.clear(); } int i = new Random().nextInt(100); if (i == 60) { System.out.println("find number 60"); break; }else{ randomBuffer = ByteBuffer.wrap(("number is " + i).getBytes()); socketChannel.write(randomBuffer); } } /*}*//**/ } }else{ System.out.println("channel is not open......."); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }
9
@Override public void processNPC() { super.processNPC(); List<WorldObject> objects = World.getRegion(getRegionId()).getSpawnedObjects(); if (objects != null) { final HunterNPC info = HunterNPC.forId(getId()); int objectId = info.getEquipment().getObjectId(); for (final WorldObject object : objects) { if (object.getId() == objectId) { if (OwnedObjectManager.convertIntoObject(object, new WorldObject(info.getSuccessfulTransformObjectId(), 10, 0, this.getX(), this.getY(), this.getPlane()), new ConvertEvent() { @Override public boolean canConvert(Player player) { if (player == null || player.getLockDelay() > Utils.currentTimeMillis()) return false; if (Hunter.isSuccessful(player, info.getLevel(), new DynamicFormula() { @Override public int getExtraProbablity(Player player) { //bait here return 1; } })) { failedAttempt(object, info); return false; } else { setNextAnimation(info.getSuccessCatchAnim()); return true; } } })) { setRespawnTask(); // auto finishes } } } } }
7
public TableauState (Tableau t) { dungeon = new Card[t.dungeon.length - 1]; for (int i=0; i < dungeon.length; i++) { dungeon[i] = t.dungeon[i].top(); } dungeonDeck = t.dungeon[t.dungeon.length - 1].size(); for (CardPile p : t.heroes) { if (p == null) continue; if (p.size() == 0) continue; TreeMap<Integer, Integer> hero = new TreeMap<Integer, Integer>(); for (Card c : p) { if (hero.containsKey(c.getLevel())) hero.put(c.getLevel(), 1 + hero.get(c.getLevel())); else hero.put(c.getLevel(), 1); } heroes.put(p.top(), hero); } for (CardPile p : t.village) if (p != null && p.size() > 0) village.put(p.top(), p.size()); trash = t.trash.size(); }
9
private String Complement(String binaryString) { StringBuilder complementBuilder = new StringBuilder(binaryString); for(int i = 0; i < binaryString.length(); ++i) { char flip = binaryString.charAt(i) == '0' ? '1' : '0'; complementBuilder.setCharAt(i, flip); } return complementBuilder.toString(); }
2
private void getColor() { color = new int[] { 0xFF111111, 0xFF000000, 0xFFC2FEFF }; switch (random.nextInt(8)) { case 0: { // red color color[1] = 0xFFFF0000; break; } case 1: { // gold color color[1] = 0xFFCFB53B; break; } case 2: { // blue color color[1] = 0xFF005AFF; break; } case 3: { // silver color color[1] = 0xFFCCCCCC; break; } case 4: { // black color color[1] = 0xFF111111; break; } case 5: { // green color color[1] = 0xFF066518; break; } case 6: { // purple color color[1] = 0xFF580271; break; } default: { // White color[1] = 0xFFFFFFFF; break; } } }
7
public void rightMultiplyBy(Matrix that) { double[][] values = new double[3][3]; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) values[i][j] = this.m[i][0] * that.m[0][j] + this.m[i][1] * that.m[1][j] + this.m[i][2] * that.m[2][j]; setComponents(values); }
2
public MonsterAttributes() { // TODO Auto-generated constructor stub }
0