text
stringlengths
14
410k
label
int32
0
9
static int checkDup(String[]input, int n){ int i =0; char[] cArray=new char[n]; int[] indexArray=new int[n]; int c=0; while(i<input.length){ if(input[i]==null){ i++; continue; } cArray[c] =input[i].charAt(0); indexArray[c]=i; c++; i++; if(c==n){ break; } } if(c<n){ return 0; } for(int j=1;j<n;j++){ if(cArray[j]!=cArray[0]){ return 0; } } for(int j=0;j<n;j++){ input[indexArray[j]]=null; } return 1; }
7
private void drawNodes(Graphics gs) { //bg.setColor(Color.white); //bg.fillRect(0, 0, gs.get, 5000); for (int i = 0; i < timeout.length; i++) { timeout[i]++; } if (nodes == null) { return; } int id = 0; for (Point p : nodes) { int i = 0; for (byte d : nodeRSSI[id]) { if (timeout[id] > 20) { bg.setColor(Color.DARK_GRAY); } else { bg.setColor(Color.green); } if (nodes[i].equals(p)) { continue; } bg.drawLine(p.x, p.y, nodes[i].x, nodes[i].y); Point mid = getMid(p, nodes[i]); bg.setColor(Color.black); bg.drawString("Rssi " + d, mid.x, mid.y); i++; } if (timeout[id] > 20) { bg.setColor(Color.red); } else { bg.setColor(Color.green); } bg.fillOval(p.x - 4, p.y - 4, 8, 8); bg.setColor(Color.black); bg.drawString("node " + (id + 1), p.x, p.y); id++; } //gs.clearRect(0, 0, 5000, 5000); gs.drawImage(buf, 0, 25, null); }
7
private void group(CommandSender sender, String[] args) { if (!sender.hasPermission("graveyard.command.group")) { noPermission(sender); return; } else if (!(sender instanceof Player)) { noConsole(sender); return; } Player player = (Player) sender; if (args.length > 1) { Spawn closest = SpawnPoint.getClosestAllowed(player); closest.setGroup(args[1]); player.sendMessage(ChatColor.GRAY + closest.getName() + ChatColor.WHITE + " group set to " + ChatColor.GREEN + args[1]); player.sendMessage(ChatColor.WHITE + "Permission is now " + ChatColor.GREEN + "'graveyard.spawn." + args[1] + "'"); SpawnPoint.save(closest); return; } else { commandLine(sender); sender.sendMessage(ChatColor.GRAY + "/graveyard" + ChatColor.WHITE + " message " + ChatColor.RED + "Spawn Message"); sender.sendMessage(ChatColor.WHITE + "Changes the group of the closest spawn point."); commandLine(sender); return; } }
3
public boolean checkNumber(String text){ String ValidNum = "0123456789"; if (text.length()==0){ return true; } if ((ValidNum.indexOf(text.charAt(0))) == -1){ return false; } if ((ValidNum.indexOf(text.charAt(text.length()-1))) == -1){ return false; } for (int i = 0; i<text.length() ;i++) { if (ValidNum.indexOf(text.charAt(i)) == -1){ return false; } } return true; }
5
private void createMenu() { JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); JMenuItem menuItem = new JMenuItem("New connection"); fileMenu.add(menuItem); menuItem.addActionListener(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { NewConnectionDialog connectionDialog = new NewConnectionDialog(MainFrame.this); connectionDialog.setVisible(true); String server = connectionDialog.getServerAddress(); int serverPort = connectionDialog.getServerPort(); try { serverManager.connect(server, serverPort); boolean acceptedUserCredentials = false; while (!acceptedUserCredentials) { UserNameDialog userNameDialog = new UserNameDialog(MainFrame.this); userNameDialog.setVisible(true); String userName = userNameDialog.getUserName(); EnterResult enterResult = serverManager.tryEnter(userName); if (enterResult.isSucceed()) { acceptedUserCredentials = true; setTitle(getTitle() + " - " + userName); } else { JOptionPane.showMessageDialog(MainFrame.this, "Cant enter", "Inane error", JOptionPane.ERROR_MESSAGE); } } serverManager.getResponseReceiver().addErrorHandler(errorHandler); serverManager.requestUserList(); UserListAnswer userListAnswer = (UserListAnswer) serverManager.getReadedAnswer(); List<UserInfo> userList = userListAnswer.getUsers(); userListPanel.setUsers(userList); enabledSendControls(true); } catch (IOException e1) { JOptionPane.showMessageDialog(MainFrame.this, "Error connect to server", "Inane error", JOptionPane.ERROR_MESSAGE); try { serverManager.close(); } catch (IOException e2) { } } } }); JMenuItem exitItem = new JMenuItem("Exit"); fileMenu.add(exitItem); exitItem.addActionListener(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { try { serverManager.getResponseReceiver().removeHandler(errorHandler); serverManager.logout(); } catch (IOException e1) { } finally { System.exit(0); } } }); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { try { serverManager.getResponseReceiver().removeHandler(errorHandler); serverManager.logout(); } catch (IOException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } finally { System.exit(0); } } }); this.setJMenuBar(menuBar); }
6
protected void printParameter(String parentParameterFile, String childParameterFile, ArrayList<_Doc> docList) { System.out.println("printing parameter"); try { System.out.println(parentParameterFile); System.out.println(childParameterFile); PrintWriter parentParaOut = new PrintWriter(new File( parentParameterFile)); PrintWriter childParaOut = new PrintWriter(new File( childParameterFile)); for (_Doc d : docList) { if (d instanceof _ParentDoc) { parentParaOut.print(d.getName() + "\t"); parentParaOut.print("topicProportion\t"); for (int k = 0; k < number_of_topics; k++) { parentParaOut.print(d.m_topics[k] + "\t"); } parentParaOut.println(); for (_ChildDoc cDoc : ((_ParentDoc) d).m_childDocs) { childParaOut.print(cDoc.getName() + "\t"); childParaOut.print("topicProportion\t"); for (int k = 0; k < number_of_topics; k++) { childParaOut.print(cDoc.m_topics[k] + "\t"); } childParaOut.println(); } } } parentParaOut.flush(); parentParaOut.close(); childParaOut.flush(); childParaOut.close(); } catch (Exception e) { e.printStackTrace(); } }
6
public void run() { Graphics g = getGraphics(); g.setClip(new Rectangle(width, height)); // BufferedImage img = new BufferedImage(width, height, // BufferedImage.TYPE_3BYTE_BGR); system = new Simulation(); Body ball1 = new Body(new CollisionCircle(20, new Vector(100, 100)), 10); ball1.setVelocity(new Vector(6, -10)); ball1.setAngularVelocity(.5); // system.addBody(ball1); /* * Vector[] pseudoBallVs = new Vector[1000]; for(int i = 0; i < * pseudoBallVs.length; ++i) { pseudoBallVs[i] = Vector.fromAngle( * Math.PI 2 i / pseudoBallVs.length, 20).add(new Vector(200, 200)); } * Body pseudoBall = new Body(new CollisionPolygon(pseudoBallVs), 10); * system.addBody(pseudoBall); double ball1mi = ball1.momentOfInertia(); * double pseudomi = pseudoBall.momentOfInertia(); */ final Body ball2 = new Body( new CollisionCircle(40, new Vector(150, 50)), 40); ball2.setVelocity(new Vector(0, 0)); ball2.setAngularVelocity(.1); system.addBody(ball2); Body square = new Body(new CollisionPolygon(new Vector[] { new Vector(150, 150), new Vector(200, 150), new Vector(225, 175), new Vector(200, 200), new Vector(150, 200) }), 20); square.setVelocity(new Vector(0, 0)); square.setAngularVelocity(0); system.addBody(square); system.addSpring(new Spring(1, ball2, square, ball2.getShape().center() .add(new Vector(30, 0)), square.getShape().center().add( new Vector(30, 0)))); system.addSpring(new Spring(1, ball2, square, ball2.getShape().center() .add(new Vector(-30, 0)), square.getShape().center().add( new Vector(-20, 0)))); this.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent evt) { if (evt.getKeyChar() == ' ') { // ball2.addImpulse(new Vector(0, -1000)); ball2.setAngularVelocity(ball2.angularVelocity() + .1); } } public void keyTyped(KeyEvent evt) { } public void keyReleased(KeyEvent evt) { } }); Body rect = new Body(new CollisionPolygon(new Vector[] { new Vector(100, 100), new Vector(200, 100), new Vector(200, 200), new Vector(100, 200) }), 10); rect.setVelocity(new Vector(0, 0)); // rect.setAngularVelocity(-10); // system.addBody(rect); int wallSize = 20; Body box = new Body(new CollisionPolygon( new Vector[] { new Vector(0, 0), new Vector(width, 0), new Vector(width, height), new Vector(0, height), new Vector(0, wallSize), new Vector(wallSize, wallSize), new Vector(wallSize, height - wallSize), new Vector(width - wallSize, height - wallSize), new Vector(width - wallSize, wallSize), new Vector(0, wallSize) }), 100000000); // box.setVelocity(new Vector(-.5, -.5)); box.setFixed(true); system.addBody(box); for (;;) { /* * for(int y = 0; y < height; ++y) { for(int x = 0; x < width; ++x) * { Color color; Body colliding = system.bodyAt(new Vector(x, y)); * if(colliding != null) { color = Color.blue; } else { color = * Color.yellow; } img.setRGB(x, y, color.getRGB()); } } */ // g.drawImage(img, 0, 0, this); int numb = system.numBodies(); g.setColor(Color.black); g.fillRect(0, 0, width, height); for (int i = 0; i < numb; ++i) { Body b = system.getBody(i); g.setColor(Color.blue); b.getShape().fill(g); } /* * for(int i = 0; i < numb; ++i) { Body b = system.getBody(i); * CollisionResult res = b.prevRes(); Vector orig = * res.contactPoint(); g.setColor(Color.yellow); g.drawOval( (int) * (orig.x()-5), (int) (orig.y()-5), 10, 10); Vector trans = * orig.add(res.translation().withMagnitude(20)); g.drawLine( (int) * orig.x(), (int) orig.y(), (int) trans.x(), (int) trans.y()); } */ double ek = 0; for (int i = 0; i < numb; ++i) { Body body = system.getBody(i); if (!body.fixed()) { ek += .5 * Math.pow(body.velocity().magnitude(), 2) * body.mass(); ek += .5 * Math.pow(body.angularVelocity(), 2) * body.momentOfInertia(); } } for (Spring s : system.getSprings()) { g.setColor(Color.magenta); s.draw(g); } g.setColor(Color.white); g.drawString("" + ek, 30, 30); for (int i = 0; i < 5000; ++i) { system.step(.0001); // try{Thread.sleep(100);}catch(Exception ex){} } } }
7
@Override public void run() { //get the socket's output stream for writing try { writer = new PrintStream(socket.getOutputStream()); } catch(IOException e) { System.err.println("Error getting writer: " + e); } //get the socket's input stream for reading try { reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch(IOException e) { System.err.println("Error getting reader: " + e); } //get the game data shared singleton to ensure that the game data tree is constructed before beginning and set currentNode to the root of the tree currentNode = GameData.getInstance().getRoot(); //ask for the user's username try { write(script.get("name")); username = read(); } catch(SocketTimeoutException e) { System.err.println("Socket timeout: " + e); } //gameplay loop while(true) { //check for a quit signal try { if(makeAMove() == Response.QUIT) { break; } } catch(SocketTimeoutException e) { System.err.println("Socket timeout: " + e); } } //close the reader and writer try{ reader.close(); writer.close(); } catch(IOException e) { System.err.println("Error closing reader or writer: " + e); } }
7
public String addBlogDetails() { FacesMessage doneMessage = null; String outcome = null; Blog blog = new Blog(); blog.setBlogContent(this.blogContent); blog.setBlogContentLable(this.blogLabel); blog.setCreatedDate(new Date()); if (blogDelegate.saveBlog(blog) != null) { doneMessage = new FacesMessage("Successfully added new user"); outcome = "success"; } else { doneMessage = new FacesMessage("Failure to added new user"); outcome = "failure"; } FacesContext.getCurrentInstance().addMessage(null, doneMessage); return outcome; }
1
public static Car createCar(String carType){ if (carType.equals("AutomobileI")){ return new TruckI("black", (int) (Math.random() * 5) ); } else return null; }
1
@Override public void spawnEnemy(String enemyData) { if(!free()) { return; } int r = Application.get().getRNG().nextInt(7) ; GameActor a = Application.get().getLogic().createActor(enemyData); PhysicsComponent pc = (PhysicsComponent)a.getComponent("PhysicsComponent"); pc.setLocation(x + 50 + r * 100, y + Display.getHeight() + 50); pc.setAngleRad(MathUtil.getOppositeAngleRad(upAngle)); pc.setTargetAngle(pc.getAngleRad()); AIComponent aic = (AIComponent)a.getComponent("AIComponent"); BaseAI ai = aic.getAI(); if(ai instanceof EnemyBasicAI) { EnemyBasicAI ebai = (EnemyBasicAI)ai; ebai.setSector(ID); } }
2
@Override public IMatrix sub(IMatrix other) { //ako nisu jednake dimenzije, vrati iznimku if (this.getColsCount() != other.getColsCount() || this.getRowsCount() != other.getRowsCount()) { throw new IncompatibleOperandException( "Matrices have not same dimensions."); } for (int row = 0; row < this.getRowsCount(); row++) { for (int col = 0; col < this.getColsCount(); col++) { this.set(row, col, this.get(row, col)-other.get(row, col)); } } return this; }
4
private void downSafety(final ExprInfo exprInfo) { final Iterator blocks = cfg.nodes().iterator(); while (blocks.hasNext()) { final Block block = (Block) blocks.next(); final Phi phi = exprInfo.exprPhiAtBlock(block); if (phi == null) { continue; } if (StackPRE.DEBUG) { System.out.println(" down safety for " + phi + " in " + block); } if (phi.downSafe()) { if (StackPRE.DEBUG) { System.out.println(" already down safe"); } continue; } // The phi is not down safe. Make all its operands not // down safe. final Iterator e = phi.operands().iterator(); while (e.hasNext()) { final Def def = (Def) e.next(); if (def != null) { resetDownSafe(def); } } } }
7
public int[] addInstance(BallNode node, Instance inst) throws Exception { double leftDist, rightDist; if (node.m_Left!=null && node.m_Right!=null) { //if node is not a leaf // go further down the tree to look for the leaf the instance should be in leftDist = m_DistanceFunction.distance(inst, node.m_Left.getPivot(), Double.POSITIVE_INFINITY); //instance.value(m_SplitDim); rightDist = m_DistanceFunction.distance(inst, node.m_Right.getPivot(), Double.POSITIVE_INFINITY); if (leftDist < rightDist) { addInstance(node.m_Left, inst); // go into right branch to correct instance list boundaries processNodesAfterAddInstance(node.m_Right); } else { addInstance(node.m_Right, inst); } // correct end index of instance list of this node node.m_End++; } else if(node.m_Left!=null || node.m_Right!=null) { throw new Exception("Error: Only one leaf of the built ball tree is " + "assigned. Please check code."); } else { // found the leaf to insert instance int index = m_Instances.numInstances() - 1; int instList[] = new int[m_Instances.numInstances()]; System.arraycopy(m_InstList, 0, instList, 0, node.m_End+1); if(node.m_End < m_InstList.length-1) System.arraycopy(m_InstList, node.m_End+2, instList, node.m_End+2, m_InstList.length-node.m_End-1); instList[node.m_End+1] = index; node.m_End++; node.m_NumInstances++; m_InstList = instList; m_Splitter.setInstanceList(m_InstList); if(node.m_NumInstances > m_MaxInstancesInLeaf) { m_Splitter.splitNode(node, m_NumNodes); m_NumNodes += 2; } } return m_InstList; }
7
public void codageRZ() { for (int i = 0; i < informationRecue.nbElements(); i++) { for (int j = 0; j < nbEchantillon; j++) { if (informationRecue.iemeElement(i)) { if (j < nbEchantillon / 2) informationEmise.add(max); else if (j >= nbEchantillon / 2) informationEmise.add(0f); } else { if (j < nbEchantillon / 2) informationEmise.add(min); else if (j >= nbEchantillon / 2) informationEmise.add(0f); } } } }
7
public static Image add(Image img1, Image img2) { if (img1 == null || img2 == null) { return null; } Image img = img1.shallowClone(); double min = 0, max = 255; for (int x = 0; x < img1.getWidth(); x++) { for (int y = 0; y < img1.getHeight(); y++) { double red = img1.getPixel(x, y, RED) + img2.getPixel(x, y, RED); double green = img1.getPixel(x, y, GREEN) + img2.getPixel(x, y, GREEN); double blue = img1.getPixel(x, y, BLUE) + img2.getPixel(x, y, BLUE); min = min(red, green, blue, min); max = max(red, green, blue, max); img.setPixel(x, y, RED, red); img.setPixel(x, y, GREEN, green); img.setPixel(x, y, BLUE, blue); } } normalize(img, min, max); return img; }
4
@FXML private void ConnectButtomAction(ActionEvent event) { this.host = Hostinput.getText(); this.port = Portinput.getText(); this.username = Usernameinput.getText(); this.password = Passwordinput.getText(); this.sid = SIDInput.getText(); int port1 = 0; try { port1 = Integer.parseInt(port); } catch (NumberFormatException e) { this.ErrorDialog("Port","El puerto no es un entero"); return; } DataBase db = DataBase.getInstance(); if ("".equals(host)) { this.ErrorDialog("Hostname","El hostname esta vacio"); } else if ("".equals(port)) { this.ErrorDialog("Port","El Port esta vacio"); } else if ("".equals(username)) { this.ErrorDialog("Username","El Username esta vacio"); } else if ("".equals(password)) { this.ErrorDialog("Password","El Password esta vacio"); } else if ("".equals(sid)) { this.ErrorDialog("SID","El SID esta vacio"); } else { try{db.setConnection(host, port1, sid, username, password); if(db.isConnected()) myController.setScreen(Proyecto_Bases.screen2ID); else{ throw new SQLException(); } } catch(SQLException ex){ this.ExceptionDialog(ex); } } }
8
private void setupMicrophone(String name) { Mixer.Info[] mixerInfos = AudioSystem.getMixerInfo(); for (Mixer.Info info : mixerInfos) { if (!info.getName().equals(name)) { continue; } Mixer mixer = AudioSystem.getMixer(info); int maxLines = mixer.getMaxLines(Port.Info.MICROPHONE); Port lineIn = null; if (maxLines > 0) { try { lineIn = (Port) mixer.getLine(Port.Info.MICROPHONE); lineIn.open(); CompoundControl cc = (CompoundControl) lineIn.getControls()[0]; Control[] controls = cc.getMemberControls(); for (Control c : controls) { if (c.getType() == BooleanControl.Type.MUTE) { this.muteControl = (BooleanControl) c; } } } catch (Exception e) { e.printStackTrace(); } } } if (this.muteControl == null) { JOptionPane.showMessageDialog(null, "Couldn't find the mute control for the microphone!", "Error", JOptionPane.ERROR_MESSAGE); System.exit(1); } }
7
@Override public void actionPerformed(ActionEvent e) { //Handle open button action if (e.getSource() == openButton) { openButtonAction(); } else if ((e.getSource() == pathText)) { if (currentState != State.PROCESSING) pathTextEnterPressed(); } else if (e.getSource() == processButton) { processButtonAction(); } else if (e.getSource() == stopButton) { stopButtonAction(); } else if (e.getSource() == cutButton) { cutButtonAction(); } }
6
public boolean draw(int numToDraw) { for (int i = 0; i < numToDraw; i++) { if (deck.size() <= 0) { this.hasLost = true; return this.hasLost; } this.hand.add(this.deck.remove(0)); } return this.hasLost; }
2
private <T> T find(Class<T> itemClass) { for (Item item : items) if (item != null && item.getClass().equals(itemClass)) return itemClass.cast(item); return null; }
3
void f() throws VeryImportantException { throw new VeryImportantException(); }
0
public void exchangeLeveledLists() { String ID; SPProgressBarPlug.setStatus("Exchange LeveledItems in LeveledList"); for (int i = 1; i < RBS_Main.amountBodyTypes; i++) { ID = RBS_Randomize.createID(i); for (LVLI leveledItem : SkyProcStarter.patch.getLeveledItems()) { List<LeveledEntry> asdf = leveledItem.getEntries(); for (int list = 0; list < asdf.size(); list++) { if (asdf.get(list).getForm() != null) { MajorRecord MJ = SkyProcStarter.merger.getLeveledItems().get(asdf.get(list).getForm()); if (MJ != null) { String itemName = MJ.getEDID() + "RBS" + ID; MajorRecord MJNew = SkyProcStarter.patch.getLeveledItems().get(itemName); if (MJNew != null) { leveledItem.addEntry(MJNew.getForm(), asdf.get(list).getLevel(), asdf.get(list).getCount()); leveledItem.removeAllEntries(asdf.get(list).getForm()); } } } } } } }
6
public void setPanels(ArrayList<Rectangle> panels) { this.panels = panels; }
0
public static Image createSquareImage(int height, int width) { Image binaryImage = new RgbImage(width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { // Analyzes if the point is in the black or white square boolean fitsInSquareByWidth = (x > width / 4 && x < 3 * (width / 4)); boolean fitsInSquareByHeight = (y > height / 4 && y < 3 * (height / 4)); Color colorToApply = (fitsInSquareByWidth && fitsInSquareByHeight) ? Color.WHITE : Color.BLACK; binaryImage.setPixel(x, y, colorToApply.getRGB()); } } return binaryImage; }
6
private static BigDecimal applyTheDayOfWeekMarketDiscountsAndGetProductPrice( Product product, String day) { // TODO Auto-generated method stub BigDecimal price = product.getPrice(); switch (day) { case "Tuesday": return (!product.isFruit()) ? price : price .multiply(new BigDecimal("0.80")); case "Wednesday": return (product.isFruit()) ? price : price.multiply(new BigDecimal( "0.90")); case "Thursday": return (!product.getName().equals("banana")) ? price : price .multiply(new BigDecimal("0.70")); case "Friday": return price.multiply(new BigDecimal("0.90")); case "Sunday": return price.multiply(new BigDecimal("0.95")); default: return price; } }
8
public static List<CDCRelation> readValidMatrices(){ // load a file containing the matrix description of network String fileName = "ValidM.csv"; //int[][] aWCTList = null; InputStream MatrixStream = CDCComposition.class.getResourceAsStream(fileName);; List<CDCRelation> aMatrixList = new ArrayList<CDCRelation>(); BufferedReader br = null; String line = ""; String cvsSplitBy = ","; //Reader reader = new InputStreamReader(WCTStream); try { br = new BufferedReader(new InputStreamReader(MatrixStream, "UTF-8")); //int lineNumber = 0; CDCRelation tempRelation; while ((line = br.readLine()) != null) { //line = line.replaceAll("\\s", ""); // remove all whitespaces // use comma as separator int[][] aMatrix = new int[3][3]; for(int l=0;l<3;l++){ String[] MatrixLine = line.split(cvsSplitBy); //int[] tempListLine = new int[3]; for (int i=0;i<3;i++){ aMatrix[l][i] = Integer.parseInt(MatrixLine[i])-1; } line=br.readLine(); } tempRelation = new CDCRelation(0); tempRelation.r = aMatrix; aMatrixList.add(tempRelation); //br.readLine(); } } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println(fileName + "file not found. \n"); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("Done read " + fileName + ".\n"); return aMatrixList; }
7
private String makeDeckMove(CardGame game) { if (topRow) { return game.moveCardOntoTopRowFromDeck(boardIndexTo); } else { return game.moveCardOntoCardFromDeck(boardIndexTo); } }
1
public List<DetallePunto> ObtenerDetallePunto(String consulta){ List<DetallePunto> lista=new ArrayList<DetallePunto>(); if (!consulta.equals("")) { lista=cx.getObjects(consulta); }else { lista=null; } return lista; }
1
public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, boolean focused, int row, int column) { super.getTableCellRendererComponent(table, value, selected, focused, row, column); if (column == 0 || column == 6) { // Week-end setBackground(new Color(255, 220, 220)); } else { // Week setBackground(new Color(255, 255, 255)); } if (value != null) { if (Integer.parseInt(value.toString()) == realDay && currentMonth == realMonth && currentYear == realYear) { // Today setBackground(new Color(220, 220, 255)); } } setBorder(null); setForeground(Color.black); return this; }
6
public void act() { if(life <= 0){ CreatureSimulator cs = (CreatureSimulator)this.getEnvironment(); cs.removeCreature(this); } else { // iterate over all nearby plants Iterable<ICreature> creatures = plantsAround(this); int count = 0; for (ICreature c : creatures) { if (this.distanceFromAPoint(c.getPosition()) <= this.visionDistance){ count++; } } switch (count) { case 2: //No action break; case 3: //Change position setPosition(position.getX()+Math.random()-0.5, position.getY()+Math.random()-0.5); break; default: //decrease life decreaseLife(LIFE_DEGEN_SPEED); break; } } }
5
public static List<ABObject> getAllSupporter (List<ABObject> objs,List<ABObject> ob) { List<ABObject> result = new LinkedList<ABObject>(); try { for (int i = 0; i < objs.size(); i++) { List<ABObject> temp = getSupporters (objs.get(i), ob, objs.get(i).depth + 1); if (!result.containsAll(temp)) result.addAll(temp); System.out.println("Call supporter of " + objs.get(i).id); List<ABObject> recursive = getAllSupporter (temp, ob); if (!result.containsAll(recursive)) result.addAll(recursive); } //System.out.println(result.size()); return result; } catch (StackOverflowError e) { return result; } }
4
public static void startAlgorithm(Vertex start) { algorithm.initialize(start); }
0
@Override protected void addPlayerOnGrid(Player p) { if (p == null) throw new IllegalArgumentException("The given arguments are invalid!"); super.addPlayerOnGrid(p); if(p instanceof PlayerCTF){ PlayerFlag playerFlag = new PlayerFlag(grid, p); ((PlayerCTF)p).setPlayerFlag(playerFlag); grid.addElementToPosition(playerFlag, p.beginPosition); } }
2
public int[] nextInts(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; ++i) { res[i] = nextInt(); } return res; }
1
public static boolean containsOnlyNotNull(Object... values){ for(Object o : values){ if(o== null){ return false; } } return true; }
2
public boolean playVideo(Integer key, boolean fromUser) { if(videos.containsKey(key)){ if(!stoppedVideoKeys.contains(key)){ videos.get(key).pause();; stoppedVideoKeys.add(key); return true; } else { videos.get(key).loop(); stoppedVideoKeys.remove(key); return true; } } //Returns false if no video was found return false; }
2
public ArrayList<Piste> getPisteet() { ArrayList<Piste> pisteet = new ArrayList(); pisteet.add(vasenYlakulma); pisteet.add(oikeaAlakulma); return pisteet; }
0
public void setMaxSpeed(int maxSpeed) throws CarriageException { if (maxSpeed >= 0) { this.maxSpeed = maxSpeed; } else { throw new CarriageException("Maximum speed is under zero"); } }
1
private void filling(){ //获取棋子 HashMap<ChessMan,Integer> map=getAllChessMan(); Random random = new Random(); //横坐标 for(int i=0;i<x;i++){ //纵坐标 for(int j=0;j<y;j++){ int r; if(map.size()==1){ r=0; }else{ r = random.nextInt(map.size()-1); } ChessMan cm = list.get(r); int count = map.get(cm); if(count==1){ map.remove(cm); list.remove(cm); }else{ map.put(cm, count-1); } ChessMan cm1 = new ChessMan(i, j, cm.getValue()); chessboard[i][j]=cm1; } } }
4
EntrySet(int size) { if(size < 0) this.size = 0; // Can't be any bigger than the array: else if(size > DATA.length) this.size = DATA.length; else this.size = size; }
2
public void start(Archive archive, Client client) { String versionNames[] = {"model_version", "anim_version", "midi_version", "map_version"}; for (int i = 0; i < 4; i++) { byte buf[] = archive.get(versionNames[i]); int len = buf.length / 2; Stream buffer = new Stream(buf); files[i] = new int[len]; fileStatus[i] = new byte[len]; for (int l = 0; l < len; l++) { files[i][l] = buffer.getUnsignedShort(); } } String crcNames[] = {"model_crc", "anim_crc", "midi_crc", "map_crc"}; for (int i = 0; i < 4; i++) { byte buf[] = archive.get(crcNames[i]); int len = buf.length / 4; Stream buffer = new Stream(buf); crcs[i] = new int[len]; for (int l = 0; l < len; l++) { crcs[i][l] = buffer.getInt(); } } byte buf[] = archive.get("model_index"); int len = files[0].length; modelIndices = new byte[len]; for (int i = 0; i < len; i++) { if (i < buf.length) { modelIndices[i] = buf[i]; } else { modelIndices[i] = 0; } } buf = archive.get("map_index"); Stream buffer = new Stream(buf); len = buf.length / 7; mapIndices1 = new int[len]; mapIndices2 = new int[len]; mapIndices3 = new int[len]; mapIndices4 = new int[len]; for (int i = 0; i < len; i++) { mapIndices1[i] = buffer.getUnsignedShort(); mapIndices2[i] = buffer.getUnsignedShort(); mapIndices3[i] = buffer.getUnsignedShort(); mapIndices4[i] = buffer.getUnsignedByte(); } buf = archive.get("anim_index"); buffer = new Stream(buf); len = buf.length / 2; animationIndices = new int[len]; for (int i = 0; i < len; i++) { animationIndices[i] = buffer.getUnsignedShort(); } buf = archive.get("midi_index"); buffer = new Stream(buf); len = buf.length; midiIndices = new int[len]; for (int i = 0; i < len; i++) { midiIndices[i] = buffer.getUnsignedByte(); } clientInstance = client; running = true; clientInstance.startRunnable(this, 2); }
9
protected static DateTime entrerDateConsole(){ Scanner sc = new Scanner(System.in); DateTime horaire = null; boolean dateOK = false;//validité de la date au sens chronologique boolean dateFormatOK = false;//validité de la date pour le parsing while(!dateOK){ while(!dateFormatOK){ System.out.print("Entrer la date de départ (jj-mm-aaaa) : "); String date = sc.nextLine(); System.out.print("Entrer l'heure de départ (hh:mm) : "); String heure = sc.nextLine(); String strHoraire = date+" "+heure; try{ horaire = DateTime.parse(strHoraire, inDTF); dateFormatOK = true; } catch(IllegalArgumentException e){ System.out.println("Le couple date et heure entré n'est pas valide, merci de respecter le format."); } } if(horaire.isAfterNow()){ dateOK = true; } else{ System.out.println("Le couple date et heure entré n'est pas valide, merci d'entrer une date postérieure à la date actuelle."); dateFormatOK = false; } } return horaire; }
4
public Texture loadTexture(String filename) { String[] splitArray = filename.split("\\."); String ext = splitArray[splitArray.length - 1]; try { int id = TextureLoader .getTexture( ext, new FileInputStream(new File("./res/textures/" + filename))).getTextureID(); return new Texture(id); } catch (Exception e) { e.printStackTrace(); System.exit(1); } return null; }
1
public boolean isExempt(Player p) { if (p.hasPermission("hunger.effects.exempt")) return true; else return false; }
1
private FunctionCompletion createFunctionCompletion() { FunctionCompletion fc = null; if (funcCompletionType!=null) { try { Class<?> clazz = null; if (completionCL!=null) { clazz = Class.forName(funcCompletionType, true, completionCL); } else { clazz = Class.forName(funcCompletionType); } Constructor<?> c = clazz.getDeclaredConstructor( CompletionProvider.class, String.class, String.class); fc = (FunctionCompletion)c.newInstance(provider, name, returnType); } catch (RuntimeException re) { // FindBugs throw re; } catch (Exception e) { e.printStackTrace(); } } if (fc==null) { // Fallback if completion failed for some reason fc = new FunctionCompletion(provider, name, returnType); } if (desc.length()>0) { fc.setShortDescription(desc.toString()); desc.setLength(0); } fc.setParams(params); fc.setDefinedIn(definedIn); if (returnValDesc.length()>0) { fc.setReturnValueDescription(returnValDesc.toString()); returnValDesc.setLength(0); } return fc; }
9
private static Farbe farbeZuweisen() { if (!Farbe.ROT.isIstFrei() && Farbe.SCHWARZ.isIstFrei()) { return Farbe.SCHWARZ; } else if (!Farbe.BLAU.isIstFrei() && Farbe.GRUEN.isIstFrei()) { return Farbe.GRUEN; } else if (!Farbe.GRUEN.isIstFrei() && Farbe.BLAU.isIstFrei()) { return Farbe.BLAU; } else if (!Farbe.SCHWARZ.isIstFrei() && Farbe.ROT.isIstFrei()) { return Farbe.ROT; } return null; }
8
public static void printHex(byte[] b) { for (int i = 0; i < b.length; ++i) { if (i % 16 == 0) { System.out.print(Integer.toHexString(i & 0xFFFF | 0x10000) .substring(1, 5) + " - "); } System.out.print(Integer.toHexString(b[i] & 0xFF | 0x100) .substring(1, 3) + " "); if (i % 16 == 15 || i == b.length - 1) { int j; for (j = 16 - i % 16; j > 1; --j) { System.out.print(" "); } System.out.print(" - "); int start = i / 16 * 16; int end = b.length < i + 1 ? b.length : i + 1; for (j = start; j < end; ++j) { if (b[j] >= 32 && b[j] <= 126) { System.out.print((char) b[j]); } else { System.out.print("."); } } System.out.println(); } } System.out.println(); }
9
private void passToken() { activity = true; if (silence() < Constants.USAGE_TIMEOUT && eventCount > Constants.MIN_OCTETS) { // SawTokenUser // debug("passToken:SawTokenUser"); if (LOG.isLoggable(Level.FINE)) LOG.fine(thisStation + " passToken:SawTokenUser"); state = MasterNodeState.idle; } else if (silence() >= Constants.USAGE_TIMEOUT && retryCount < Constants.RETRY_TOKEN) { // RetrySendToken // debug("passToken:RetrySendToken to " + nextStation); if (LOG.isLoggable(Level.FINE)) LOG.fine(thisStation + " passToken:RetrySendToken"); retryCount++; sendFrame(FrameType.token, nextStation); eventCount = 0; } else if (silence() >= Constants.USAGE_TIMEOUT && retryCount >= Constants.RETRY_TOKEN) { // FindNewSuccessor // debug("passToken:FindNewSuccessor: trying " + adjacentStation(nextStation)); if (LOG.isLoggable(Level.FINE)) LOG.fine(thisStation + " passToken:FindNewSuccessor"); pollStation = adjacentStation(nextStation); sendFrame(FrameType.pollForMaster, pollStation); nextStation = thisStation; retryCount = 0; tokenCount = 0; eventCount = 0; state = MasterNodeState.pollForMaster; } }
9
@Override protected void setReaction(Message message) { try { String langFrom = getLang(message.text, true); String langTo = getLang(message.text, false); if (isLangAllowed(langFrom) && isLangAllowed(langTo)) { if (langFrom.equals(langTo)) { reaction.add(NO_TRANSLATION); } else { String response = getTranslation(getAddress(message.text.substring(9), langFrom, langTo)); reaction.add(response); } } } catch (Exception e) { setError(e); } }
4
public Items getHead() { return head; }
0
public static void main(String[] args) { Scanner inputScanner = null; try { inputScanner = new Scanner(new File(args[0])); } catch (FileNotFoundException e) { System.err.println("Invalid input file."); } while (inputScanner.hasNextLine()) { String[] outputLine = inputScanner.nextLine().split(" "); for (int x = outputLine.length; x > 0; x--) { System.out.print(outputLine[x-1]); if (x != 0) { System.out.print(" "); } } System.out.print("\n"); } }
4
public int getConstantValue() { if ((accessFlags & AccessFlag.STATIC) == 0) return 0; ConstantAttribute attr = (ConstantAttribute)getAttribute(ConstantAttribute.tag); if (attr == null) return 0; else return attr.getConstantValue(); }
2
@EventHandler public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); final UUID uuid = player.getUniqueId(); final String name = player.getName(); final Database database = plugin.getDatabaseManager().getDatabase(); if (database instanceof YAMLDatabase) { UUID foundUUID = database.getUUID(name); // This player joined with their name for the first time if (!uuid.equals(foundUUID)) { if (foundUUID != null) { // Someone owned this name before database.deleteName(foundUUID, name); } database.insertName(uuid, name); } } else if (database instanceof MySQLDatabase) { new BukkitRunnable() { @Override public void run() { MySQLDatabase sql = (MySQLDatabase) database; if(sql.selectPlayerId(uuid) == null) { sql.insertUUID(uuid); } database.insertName(uuid, name); } }.runTaskAsynchronously(plugin); } else { throw new UnsupportedOperationException("Oh noes, the database implementation isn't supported!"); } }
5
public void drawHead(Graphics graphics, Point position, Point size) { int startAngle = 30; if (getDirection() == Direction.RIGHT) { startAngle = 30; } else if (getDirection() == Direction.LEFT) { startAngle = 210; } else if (getDirection() == Direction.UP) { startAngle = 120; } else if (getDirection() == Direction.DOWN) { startAngle = 300; } graphics.setColor(getHeadColor()); graphics.fillArc(position.x, position.y, size.x, size.y, startAngle, 300); //draw eye graphics.setColor(Color.RED); if ((direction == Direction.LEFT) || (direction == Direction.RIGHT)) { graphics.fillOval(position.x + (size.x / 2), position.y + (size.y / 4), size.x / 6, size.y / 6); } else if (direction == Direction.UP) { graphics.fillOval(position.x + (size.x / 4), position.y + (size.y / 2), size.x / 6, size.y / 6); } else if (direction == Direction.DOWN) { graphics.fillOval(position.x + (size.x * 2 / 3), position.y + (size.y / 2), size.x / 6, size.y / 6); } }
8
public static ArrayList<Sub> getSubs() { ArrayList<String> tempsubs = new ArrayList<String>(); for(int i = 0; i < file.size(); i++) { if( file.get(i).equals("")) { subs.add(new Sub(id, fromTime, toTime, new ArrayList<String>(tempsubs))); tempsubs.clear(); id = 0; fromTime = ""; toTime = ""; } else { if(id <= 0) { id = Integer.parseInt(file.get(i)); } else if(id > 0 && fromTime == "") { fromTime = file.get(i).split("\\s+")[0]; fromTime = fromTime.replace(",", "."); toTime = file.get(i).split("\\s+")[2]; toTime = toTime.replace(",", "."); } else if(id > 0 && fromTime!= "") { tempsubs.add(file.get(i)); } } } return subs; }
7
protected void Calcula_Tamanho() { int quantidadeAtributos = atributosTabela.size(); for (int k = 0; k < quantidadeAtributos; k++) { TipodeDados A = (TipodeDados) atributosTabela.get(k); switch (A.tipoAtributo) { case (TipodeDados.BOOLEAN): { tamanho_tupla = tamanho_tupla + 1; break; } case (TipodeDados.CHAR): { tamanho_tupla = tamanho_tupla + 2; break; } case (TipodeDados.SHORT): { tamanho_tupla = tamanho_tupla + 2; break; } case (TipodeDados.INTEIRO): { tamanho_tupla = tamanho_tupla + 4; break; } case (TipodeDados.LONGINT): { tamanho_tupla = tamanho_tupla + 8; break; } case (TipodeDados.FLOAT): { tamanho_tupla = tamanho_tupla + 4; break; } case (TipodeDados.DOUBLE): { tamanho_tupla = tamanho_tupla + 8; break; } case (TipodeDados.STRING): { tamanho_tupla = tamanho_tupla + 512; break; //Tamanho da string: 255 //cada char possui 2 bytes, e 2 bytes do total estão reservados para armazenar o tamanho } } } }
9
public String getLabel() { if (label == null) label = "while_" + (serialno++) + "_"; return label; }
1
private int neighborCount(int x, int y) { int count = 0; for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { int currentY = y + i; int currentX = x + j; if (currentX != x || currentY != y) { if (currentX >= 0 && currentX < field[0].length && currentY >= 0 && currentY < field.length) { if (field[currentY][currentX]) { count++; } } } } } return count; }
9
@Override public boolean isComplete() { return complete; }
0
public void onTimerEvent() { final List<Customer> customers = customerRepository.getNewCustomers(); final Campaign campaign = new HalfOfCampaign(); final Set<Long> ids = new HashSet<Long>(); if (customers == null) { throw new IllegalArgumentException("No new customers found"); } else { List<Customer> temp = new ArrayList<Customer>(); for (Customer c : customers){ Long id = c.id(); ids.add(id); } for (Long id : ids) { for (Customer c : customers) { if (c.id().equals(id)){ temp.add(c); break; } } } for (Customer c : temp) { if ((c.type() == CustomerType.GOLD || c.type() == CustomerType.VIP) && c.balance().over(1000.00)){ senderRepository.findFastestSenderService().send(campaign.message(), c); } } } }
9
protected void setCurrent(int i) { myCurrent = i; }
0
@Override void update() { x += Math.cos(DIRECTION) * SPEED; y += Math.sin(DIRECTION) * SPEED; AffineTransform tran = new AffineTransform(); tran.translate(x, y); tran.rotate(angle, SIZE / 2, SIZE / 2); painter.drawImage(IMAGE, tran, null); if (x > WIDTH || y > HEIGHT || x < 0 - SIZE || y < 0 - SIZE) remove = true; }
4
public boolean permissible(GuideUserAction currentAction, ParserConfiguration config) throws MaltChainedException { currentAction.getAction(actionContainers); int trans = transActionContainer.getActionCode(); if ((trans == LEFTARC || trans == RIGHTARC) && !isActionContainersLabeled()) { return false; } DependencyNode stackTop = ((NivreConfig)config).getStack().peek(); if (!((NivreConfig)config).isAllowRoot() && stackTop.isRoot() && trans != SHIFT) { return false; } if (trans == LEFTARC && stackTop.isRoot()) { return false; } return true; }
8
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onItemHeldChange(PlayerItemHeldEvent event) { Player player = event.getPlayer(); if (player.isSneaking()) { if ((player.isOp() || player.hasPermission("voxelbar.use")) && plugin.getConfigurationManager().isScrollingEnabledFor(player)) { int scrollDelta = VoxelBarFunctions.getDelta(event.getPreviousSlot(), event.getNewSlot(), 9); if (scrollDelta == 1 || scrollDelta == -1) { VoxelBarFunctions.moveInventory(player, scrollDelta * 9); } } } }
6
private void lengthConversionsMenu() throws InterruptedException { System.out.println(); println("Choose a conversion or enter any integer to go back:"); println("0: Centimeters to meters"); println("1: Meters to centimeters"); println("2: Microns to centimeters"); println("3: Centimeters to microns"); println("4: Nanometers to microns"); println("5: Microns to nanometers"); println("6: Picometers to nanometers"); println("7: Nanometers to picometers"); switch (input.nextInt()) { case 0: // Centimeters to meters amount(); double centimeters = input.nextDouble(); println(Conversions.centimetersToMeters(centimeters) + " m"); break; case 1: // Meters to centimeters amount(); double meters = input.nextDouble(); println(Conversions.metersToCentimeters(meters) + " cm"); break; case 2: // Microns to centimeters amount(); double microns = input.nextDouble(); println(Conversions.micronsToCentimeters(microns) + " cm"); break; case 3: // Centimeters to microns amount(); double centimeters1 = input.nextDouble(); println(Conversions.centimetersToMicrons(centimeters1) + " microns"); break; case 4: // Nanometers to microns amount(); double nanometers = input.nextDouble(); println(Conversions.nanometersToMicrons(nanometers) + " microns"); break; case 5: // Microns to nanometers amount(); double microns1 = input.nextDouble(); println(Conversions.micronsToNanometers(microns1) + " nm"); break; case 6: // Picometers to nanometers amount(); double picometers = input.nextDouble(); println(Conversions.picometersToNanometers(picometers) + " nm"); break; case 7: // Nanometers to picometers amount(); double nanometers1 = input.nextDouble(); println(Conversions.nanometersToPicometers(nanometers1) + " pm"); break; default: // Return to conversions menu conversionsMenu(); } }
8
public String[] getLastMessages() { return previousMessages; }
0
public boolean getTruthValue() { if (!hasTruthValue()) { throw new RuntimeException("Attempt to get the truth value for a result set with non-truth value data."); } return truthValue; }
1
private boolean processSanninCommand(MapleClient c, MessageCallback mc, String[] splitted) { DefinitionSanninCommandPair definitionCommandPair = sannincommands.get(splitted[0]); if (definitionCommandPair != null) { try { definitionCommandPair.getCommand().execute(c, mc, splitted); } catch (IllegalCommandSyntaxException ex) { mc.dropMessage(ex.getMessage()); dropHelpForSanninDefinition(mc, definitionCommandPair.getDefinition()); } catch (NumberFormatException nfe) { mc.dropMessage("[The Elite Ninja Gang] The Syntax to your command appears to be wrong. The correct syntax is given below."); dropHelpForSanninDefinition(mc, definitionCommandPair.getDefinition()); } catch (ArrayIndexOutOfBoundsException ex) { mc.dropMessage("[The Elite Ninja Gang] The Syntax to your command appears to be wrong. The correct syntax is given below."); dropHelpForSanninDefinition(mc, definitionCommandPair.getDefinition()); } catch (NullPointerException exx) { mc.dropMessage("An error occured: " + exx.getClass().getName() + " " + exx.getMessage()); System.err.println("COMMAND ERROR" + exx); } catch (Exception exx) { mc.dropMessage("An error occured: " + exx.getClass().getName() + " " + exx.getMessage()); System.err.println("COMMAND ERROR" + exx); } return true; } else { processGMCommand(c, mc, splitted); } return true; }
6
public void setNametextZoomedFontsize(int fontsize) { if (fontsize <= 0) { this.nametextZoomedFontSize = UIFontInits.NAMEZOOMED.getSize(); } else { this.nametextZoomedFontSize = fontsize; } somethingChanged(); }
1
public String toString() { if (version == null) { StringBuilder result = new StringBuilder(); for (int i = 0; i < orderedVersionNumbers.size(); i++) { Integer curVersionNumber = (Integer) orderedVersionNumbers.get(i); result.append(curVersionNumber.intValue()); if (i < (orderedVersionNumbers.size() - 1)) { result.append("."); } } if (versionPartSuffix != null) { result.append(versionPartSuffix); } if (betaNumber != -1) { result.append("b"); result.append(betaNumber); } else if (releaseCandidateNumber != -1) { result.append("rc"); result.append(releaseCandidateNumber); } if (updateMarker != null) { result.append("_"); result.append(updateMarker); } if (qualifiers.size() > 0) { for (String qualifier : qualifiers) { result.append("-"); result.append(qualifier); } } version = result.toString(); } return version; }
9
public void endLifetime() { if (this.lifetime > 0) this.lifetime = 0; }
1
@Override public void removeUpdate(double delta) { timer += delta; if (timer >= solidityDuration) { getEntity().remove(CollisionComponent.ID); } if (timer >= duration) { getEntity().forceRemove(); } double amt = (duration - timer) / duration; SpriteComponent sc = (SpriteComponent) getEntity().getComponent( SpriteComponent.ID); if (sc != null) { sc.setTransparency(amt); } LightComponent l = (LightComponent) getEntity().getComponent( LightComponent.ID); if (l != null) { l.setIntensity(amt); } }
4
@Override public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { final String command = buildFormatCommand(obj); try { toAppendTo.append(getCycAccess().converseString(command)); } catch (Exception ex) { throw new RuntimeException("Exception formatting " + obj, ex); } return toAppendTo; }
1
public static void htmlExecuteQuery(KeyValueList querydata, org.powerloom.PrintableStringWriter stream) { { String modulename = ((StringWrapper)(querydata.lookup(StringWrapper.wrapString("MODULE")))).wrapperValue; Module module = Logic.getModule(StringWrapper.wrapString(modulename)); StringWrapper nvalueentry = ((StringWrapper)(querydata.lookup(StringWrapper.wrapString("NANSWERS")))); Stella_Object nvalueobject = ((nvalueentry != null) ? Stella.readSExpressionFromString(nvalueentry.wrapperValue) : ((Stella_Object)(null))); int nvalues = (Stella_Object.integerP(nvalueobject) ? ((IntegerWrapper)(nvalueobject)).wrapperValue : Stella.NULL_INTEGER); StringWrapper timeoutentry = ((StringWrapper)(querydata.lookup(StringWrapper.wrapString("TIMEOUT")))); Stella_Object timeoutobject = ((timeoutentry != null) ? Stella.readSExpressionFromString(timeoutentry.wrapperValue) : ((Stella_Object)(null))); double timeout = (Stella_Object.floatP(timeoutobject) ? ((FloatWrapper)(timeoutobject)).wrapperValue : Stella.NULL_FLOAT); Cons query = Stella.NIL; Cons options = Cons.list$(Cons.cons(OntosaurusUtil.KWD_SORT_BY, Cons.cons(OntosaurusUtil.KWD_VALUES, Cons.cons(Stella.NIL, Stella.NIL)))); List variables = List.newList(); if (module != null) { { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, module); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); query = ((Cons)(Stella.readSExpressionFromString(((StringWrapper)(querydata.lookup(StringWrapper.wrapString("QUERYSOURCE")))).wrapperValue))); Logic.collectUndeclaredVariables(query, Stella.NIL, variables); if (timeout != Stella.NULL_FLOAT) { options = options.concatenate(Cons.list$(Cons.cons(OntosaurusUtil.KWD_TIMEOUT, Cons.cons(FloatWrapper.wrapFloat(timeout), Cons.cons(Stella.NIL, Stella.NIL)))), Stella.NIL); } if (variables.emptyP()) { OntosaurusUtil.htmlExecuteAskQuery(query, options, module, stream); } else { OntosaurusUtil.htmlExecuteRetrieveQuery(nvalues, variables.theConsList, query, options, module, stream); } OntosaurusUtil.htmlLineBreak(stream); stream.println("<HR SIZE=2>"); OntosaurusUtil.writePowerloomTrailer(stream); } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } } else { OntosaurusUtil.htmlUnknownModuleResponse(OntosaurusUtil.KWD_QUERY, "", modulename, stream); } } }
7
public Fraction evaluate(String expression) { IEvaluable ev; try { TokenList tl = tokenizer.tokenize(expression); if (debug) System.out.println("\nBuilding syntax tree..."); ev = tl.parse(); } catch (ParseError e) { throw e; } catch (NumberFormatException e) { throw new ParseError("Invalid number format."); } catch (Exception e) { throw new ParseError(e); } if (debug) System.out.println("\nSyntax tree:\n" + ev + "\n"); Fraction out = ev.evaluate(); return out; }
5
private void drawLogoLayer() { ctx.clearRect(0, 0, size, size); if (Clock.Design.BOSCH == getSkinnable().getDesign()) { ctx.setFill(getSkinnable().isNightMode() ? Color.rgb(240, 240, 240) : Color.rgb(10, 10, 10)); ctx.fillRect(size * 0.5 - 1, size * 0.18, 2, size * 0.27); ctx.fillRect(size * 0.5 - 1, size * 0.55, 2, size * 0.27); ctx.fillRect(size * 0.18, size * 0.5 - 1, size * 0.27, 2); ctx.fillRect(size * 0.55, size * 0.5 - 1, size * 0.27, 2); } if (getSkinnable().getText().isEmpty()) return; ctx.setFill(getSkinnable().isNightMode() ? Color.WHITE : Color.BLACK); ctx.setFont(Fonts.opensansSemiBold(size * 0.05)); ctx.setTextBaseline(VPos.CENTER); ctx.setTextAlign(TextAlignment.CENTER); ctx.fillText(getSkinnable().getText(), size * 0.5, size * 0.675, size * 0.8); }
4
public int getGladiolos() { return gladiolos; }
0
public HashMap hashResult(String query) throws SQLException { Connection connection = null; Statement statement = null; ResultSet result = null; String key = ""; String val = ""; HashMap hashedList = new HashMap(); try { Class.forName(driver); connection = DriverManager.getConnection(url, username, passwd); statement = connection.createStatement(); result = statement.executeQuery(query); while (result.next()) { key = String.valueOf(result.getInt(1)); val = result.getString(2); hashedList.put(key, val); } result.close(); result = null; statement.close(); statement = null; } catch (Exception e) { System.out.println(e); } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { System.out.println(e); } statement = null; } if (connection != null) { try { connection.close(); } catch (SQLException e) { System.out.println(e); } connection = null; } } return hashedList; }
6
public static ArrayList<Clientes> sqlSelectTodos() { ArrayList<Clientes> cat = new ArrayList(); if(!BD.getInstance().sqlSelect("SELECT * FROM clientes ORDER BY idclientes DESC")){ return cat; } while(BD.getInstance().sqlFetch()){ cat.add(new Clientes(BD.getInstance().getInt("rut") ,BD.getInstance().getString("dv").charAt(0) ,BD.getInstance().getString("nombre") ,BD.getInstance().getString("ape_paterno") ,BD.getInstance().getString("ape_materno") ,BD.getInstance().getString("email") ,BD.getInstance().getString("fecha_nac") ,BD.getInstance().getString("telefono") ,BD.getInstance().getString("sexo").charAt(0) ,BD.getInstance().getString("direccion") )); } return cat; }
2
public void refuel(int amount) { if((amount > 0) && ((amount + fuelLevel) <= fuelCapacity) && !infinite) { fuelLevel += amount; } }
3
@Override public void ParseIn(Connection Main, Server Environment) { if(Main.Data.Trade != null) { return; } Room Room = Environment.RoomManager.GetRoom(Main.Data.CurrentRoom); if (Room == null) { return; } int User = Room.GetRoomUserByVirtualId(Main.DecodeInt()); if (User != -1) { if (Room.UserList[User].Client.Data.Trade != null) { return; } Main.Data.RoomUser.SetStatus("trd", ""); Room.UserList[User].SetStatus("trd", ""); Trade trade = new Trade(Environment, Main.Data, Room.UserList[User].Client.Data); trade.SetTrade(); } }
4
@Override public String remove(String hashKey) { if (manager.remove(hashKey) == null) { return "Error: No match to object!"; } else { if (hashKey.startsWith("A")) { aisleCount--; } else if (hashKey.startsWith("R")) { rackCount--; } return "Remove: OK"; } }
3
public synchronized void drop_tables() { Connection c = null; try { c = connectionPool.getConnection(); clearSoftState(); Statement stmt = c.createStatement(); for( String t : TABLES ) { try { stmt.executeUpdate("DROP TABLE IF EXISTS " + t); } catch( Exception e ) { logger.warning(e.toString()); } } stmt.close(); } catch( Exception e ) {} finally { try { c.close(); } catch( SQLException e ) {} } }
4
public Object getPrice(MaterialData data){ if(data==null) return null; if(prices.containsKey(data)) return prices.get(data); return defaultPrice; }
2
public void setTotalPrice(float totalPrice) { this.totalPrice = totalPrice; }
0
public Request getNextBlock(){ if(complete){return null;} Iterator<SubPiece> itor = data.iterator(); SubPiece last=null; int max = idealSize; if(max > finalPiece.length){ max = finalPiece.length; } //TODO: reduces i think? while(itor.hasNext()){ if(last==null){ last=itor.next(); }else{ SubPiece curr =itor.next(); if(curr.begin>last.begin+last.data.length){//plzz dont be off by one kay thx //Our next piece falls between two pieces int m=curr.begin-(last.begin+last.data.length);//delta aka between blocks m=m>max?m:max; return new Request(pieceIndex,last.begin+last.data.length,m); } last = curr; } } if(last==null){//First request for this piece ^.^ return new Request(pieceIndex,0,max); }else{//At the end? Maybe? int m = finalPiece.length-(last.begin+last.data.length)>max?max:finalPiece.length-last.begin+last.data.length; if(m!=0){//if not complete. return new Request(pieceIndex,last.begin+last.data.length,max); } } return null;//its actually complete. }
9
public int getInt(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } }
2
public static void addInventoryInfo(MaplePacketLittleEndianWriter mplew, MapleCharacter chr) { mplew.writeInt(chr.getMeso()); // mesos mplew.write(chr.getInventory(MapleInventoryType.EQUIP).getSlotLimit()); // equip slots mplew.write(chr.getInventory(MapleInventoryType.USE).getSlotLimit()); // use slots mplew.write(chr.getInventory(MapleInventoryType.SETUP).getSlotLimit()); // set-up slots mplew.write(chr.getInventory(MapleInventoryType.ETC).getSlotLimit()); // etc slots mplew.write(chr.getInventory(MapleInventoryType.CASH).getSlotLimit()); // cash slots mplew.write(unk1); MapleInventory iv = chr.getInventory(MapleInventoryType.EQUIPPED); Collection<IItem> equippedC = iv.list(); List<Item> equipped = new ArrayList<Item>(equippedC.size()); List<Item> equippedCash = new ArrayList<Item>(equippedC.size()); for (IItem item : equippedC) { if (item.getPosition() <= -100) { equippedCash.add((Item) item); } else { equipped.add((Item) item); } } Collections.sort(equipped); for (Item item : equipped) { addItemInfo(mplew, item, false, false); } mplew.write(0); // start of equip cash for (Item item : equippedCash) { addItemInfo(mplew, item, false, false); } mplew.write(0); // start of equip inventory iv = chr.getInventory(MapleInventoryType.EQUIP); for (IItem item : iv.list()) { addItemInfo(mplew, item, false, false); } mplew.write(0); // start of use inventory iv = chr.getInventory(MapleInventoryType.USE); for (IItem item : iv.list()) { addItemInfo(mplew, item, false, false); } mplew.write(0); // start of set-up inventory iv = chr.getInventory(MapleInventoryType.SETUP); for (IItem item : iv.list()) { addItemInfo(mplew, item, false, false); } mplew.write(0); // start of etc inventory iv = chr.getInventory(MapleInventoryType.ETC); for (IItem item : iv.list()) { addItemInfo(mplew, item, false, false); } mplew.write(0); // start of cash inventory iv = chr.getInventory(MapleInventoryType.CASH); for (IItem item : iv.list()) { addItemInfo(mplew, item, false, false); } mplew.write(0); }
9
public void setClobField(Clob clobField) { this.clobField = clobField; BufferedReader reader = null; try { reader = new BufferedReader(clobField.getCharacterStream()); setClobData(reader.readLine()); } catch (SQLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) reader.close(); } catch (IOException e) { e.printStackTrace(); } } }
4
public void addNpe(String className, NpeData data) { String name = className; if(data == null) { data = new NpeData(this); } // Register the MBean ObjectName oName; try { oName = new ObjectName("org.dkhenry.minejmx:type=NpeData,name=" + name); if( mbs.isRegistered(oName) ) { mbs.unregisterMBean(oName) ; } mbs.registerMBean(data, oName) ; } catch (InstanceAlreadyExistsException e) { //e.printStackTrace(); } catch (MBeanRegistrationException e) { //e.printStackTrace(); } catch (NotCompliantMBeanException e) { //e.printStackTrace(); } catch (MalformedObjectNameException e) { //e.printStackTrace(); } catch (NullPointerException e) { //e.printStackTrace(); } catch (InstanceNotFoundException e) { //e.printStackTrace(); } this.npeData.put(name, data) ; }
8
@Override public void testIgnored(Description description) { testStarted(description); final Xpp3Dom testCase = getCurrentTestCase(); testCase.addChild(createResult(TestState.blocked)); final String message = description.getAnnotation(Ignore.class).value(); testCase.addChild(createNotes(String.format("'%s' BLOCKED because '%s'.", description.getDisplayName(), message))); }
0
@Override public void addUnsearchQueue(WebPage unsearchQueue) { // TODO Auto-generated method stub }
0
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 NewMemberGui() { System.out.println("DEBUG: starting NewMemberGui..."); try { mM = MemberManager.getInstance(); System.out.println("DEBUG: mM-instance: " + MemberManager.getInstance()); } catch (FileNotFoundException ex) { Logger.getLogger(MemberGui.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MemberGui.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLServerException ex) { Logger.getLogger(MemberGui.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(MemberGui.class.getName()).log(Level.SEVERE, null, ex); } initComponents(); }
4
public IterableGroup(TKey key, Iterable<TElement> source) { this._key = key; this._source = source; }
0
private String extractParameterValue(String str, String parameterName) { int paraIdx = str.indexOf("\""+parameterName+"\""); if (paraIdx < 0) return ""; int startIdx = str.indexOf(":", paraIdx)+1; if (startIdx <= -1) return ""; String value; int endIdx = str.indexOf("\"", startIdx+1); if (endIdx <= -1) value = str.substring(startIdx); else value = str.substring(startIdx, endIdx); value = value.replaceAll("\"", ""); return value; }
3
public double[] rawPersonMaxima(){ if(!this.dataPreprocessed)this.preprocessData(); if(!this.variancesCalculated)this.meansAndVariances(); return this.rawPersonMaxima; }
2
private static void fillPersonFields(Person p, String[] tokens) { int i = 1; //Start in token 1 as token 0 is the field label (MANAGER, PLAYER, etc.) String flag = null, value = null; do { //Get current flag flag = tokens[i]; value = tokens[i+1]; switch(flag) { case "-name": { p.setName(value); break; } case "-fname": { p.setFirstName(value); break; } case "-id": { p.setId(value); break; } case "-pnum": { p.setPhoneNumber(value); break; } case "-dbirt": { int day = Integer.parseInt(value); p.getBirthDate().set(Calendar.DAY_OF_MONTH, day); break; } case "-mbirt": { int month = Integer.parseInt(value); p.getBirthDate().set(Calendar.MONTH, month); break; } case "-ybirt": { int year = Integer.parseInt(value); p.getBirthDate().set(Calendar.YEAR, year); break; } default: { break; } } //Get next group of tokens i += 2; } while(i < tokens.length); }
8
public Worker () { //initial settings isInputActive = true; this.keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println(MSG_WELCOME); //start this.lifeCycle(); }
0