text
stringlengths
14
410k
label
int32
0
9
public String toString() { String ret = new String(""); for(int y=tabuleiro[0].length-1; y>=0; y--) { if( y == tabuleiro[0].length-1 ) { for(int x=0; x<tabuleiro.length; x++) ret += " "+x; ret += Util.EOL; } for(int x=0; x<tabuleiro.length; x++) ret += "|"+tabuleiro[x][y]; ret += "|"+Util.EOL; for(int x=0; x<tabuleiro.length; x++) ret += "+-"; ret += "+"+Util.EOL; } return ret; }
5
@Override public String toString() { String txt = ""; if (label != null && !label.equals("")) { txt += label + ": \n"; } if (vertices != null && vertices.size() > 0) { txt = txt + "V: {"; for (Vertex v : vertices) { txt = txt + v.getLabel() + ", "; } txt = txt.substring(0, txt.length() - 2) + "}"; } if (edges != null && edges.size() > 0) { txt += "\nE: {"; for (Edge e : edges) { txt = txt + e + ", "; } txt = txt.substring(0, txt.length() - 2) + "}"; } return txt; }
8
@Override public boolean equals(Object obj) { if (!(obj instanceof TargetTransition)) return false; TargetTransition tt = (TargetTransition) obj; return this.action.equals(tt.action) && this.invoke.equals(tt.invoke); }
2
public static void linejnyj(int[] a, int key) { double time = -System.currentTimeMillis(); boolean flag = false; for (int i = 0; i < a.length; i++) { if (a[i] == key) { System.out.println("pozicija " + (i + 1)); flag = true; } } if (!flag) { System.out.println("Rezultat ne najden"); } time += System.currentTimeMillis(); System.out.println("vremja " + time); }
3
public ArrayList<Term> getOverlappingTerms(String query, ArrayList<Integer> selectedChapters){ if(index.hasTerm(query)){ if(selectedChapters.size() == 0){ return index.getOverlappingTerms(query, 0, 0); } else { ArrayList<Term> overlappingTerms = new ArrayList<>(); for(int i = 0;i < selectedChapters.size();i++){ ArrayList<Term> allPotentialCandidatesFromCurrentChapter = index.getOverlappingTerms(query, toc.getChapters().get(selectedChapters.get(i)).getStart(), toc.getChapters().get(selectedChapters.get(i)).getEnd()); for(Term maybe : allPotentialCandidatesFromCurrentChapter){ if(!overlappingTerms.contains(maybe)){ overlappingTerms.add(maybe); } } } return overlappingTerms; } } else { return null; } }
5
@Override public List<Position> getAll() throws SQLException { List<Position> results = new ArrayList<Position>(); Connection dbConnection = null; java.sql.Statement statement = null; String selectCourses = "SELECT id_position, name, sallary FROM position"; try { dbConnection = PSQL.getConnection(); statement = dbConnection.createStatement(); ResultSet rs = statement.executeQuery(selectCourses); while (rs.next()) { Position position = new Position(); int id = rs.getInt("id_position"); String name = rs.getString("name"); int sallary = rs.getInt("sallary"); position.setId(id); position.setName(name); position.setSallary(sallary); results.add(position); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { if (statement != null) { statement.close(); } if (dbConnection != null) { dbConnection.close(); } } return results; }
4
public static void main(String[] args) { long pathCount = 0; long[][] grid = new long[xDim][yDim]; for(int i = 0; i < yDim; i++) { for(int j = 0; j < xDim; j++) { if(j == 0 && i == 0) grid[j][i] = 1 + 1; else if(j == 0) grid[j][i] = 1 + grid[j][i-1]; else if(i == 0) grid[j][i] = 1 + grid[j-1][i]; else grid[j][i] = grid[j-1][i] + grid[j][i-1]; loopCounter++; } } for(int i = 0; i < yDim; i++) { for(int j = 0; j < xDim; j++) { System.out.print(" ".substring(0,14 - ("" + grid[j][i]).toString().length()) + grid[j][i]); } System.out.println(); } System.out.println("Number of paths: " + grid[xDim-1][yDim-1]); System.out.println("Loop count: " + loopCounter); }
8
public String toString() { return String.format("%2d : %s", getSuppliercode(), getName()); }
0
@Override public void execute(MapleClient c, MessageCallback mc, String[] splitted) throws Exception { String cmd = splitted[0]; MapleCharacter pl = c.getPlayer(); if (cmd.equalsIgnoreCase("donated")) { if (splitted.length != 4) { pl.dropMessage("syntax : !donated <ign> <amount> <paypal e-mail>"); } short damount = 0; try { damount = Short.parseShort(splitted[2]); } catch (NumberFormatException nfe) { pl.dropMessage(nfe.toString()); return; } DonationProcessor.doDonation(c, splitted[1], damount, cmd); } else if (cmd.equalsIgnoreCase("setdamount")) { if (splitted.length != 3) { mc.dropMessage("[Anbu]Drunk?? read the commands. Syntax : !setdamount ign amount"); return; } String name = splitted[1]; short amt = 0; try { amt = Short.parseShort(splitted[2]); } catch (NumberFormatException nfe) { pl.dropMessage(nfe.toString()); return; } DonationProcessor.setDAmount(c, name, amt); } else if (cmd.equalsIgnoreCase("setdpoint")) { if (splitted.length != 3) { mc.dropMessage("[Anbu]Drunk?? read the commands. Syntax : !setdpoint ign amount"); return; } String name = splitted[1]; short amt = 0; try { amt = Short.parseShort(splitted[2]); } catch (NumberFormatException nfe) { pl.dropMessage(nfe.toString()); return; } DonationProcessor.setDPoints(c, name, amt); } }
9
public void setChar(TChar node) { if(this._char_ != null) { this._char_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._char_ = node; }
3
public Editor(final Skin skin) { if (skin == null) { throw new IllegalArgumentException(); } this.skin = skin; setUpStringArrays(); EventQueue.invokeLater(new Runnable() { @Override public void run() { Editor.this.setTitle(GUIConstants.PROGRAM_TITLE + " - " + skin.getName()); Editor.this.setIconImage(GUIConstants.PROGRAM_ICON); Editor.this.setJMenuBar(new EditorMenuBar(skin)); Editor.this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); Editor.this.addWindowListener(Editor.this); Editor.this.setBackground(GUIConstants.DEFAULT_BACKGROUND); Editor.this.setMinimumSize(GUIConstants.MIN_EDITOR_DIM); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int width = (int) ((screenSize.getWidth() * (100 - GUIConstants.EDITOR_SIDEGAP_PERCENT)) / 100f); int height = (int) ((screenSize.getHeight() * (100 - GUIConstants.EDITOR_SIDEGAP_PERCENT)) / 100f); Editor.this.setSize(width, height); Editor.this.setLocationRelativeTo(null); create(); setFocusToLeftMenu(); Editor.this.setVisible(true); } }); }
1
private ItemStack createStack(Objective o, QuestProgress qd) { Material m = Material.getMaterial(o.getItemIconId()); if(m == null || m == Material.AIR)m = Material.getMaterial(o.getType().getItemIcon()); if(m == null || m == Material.AIR)m = Material.WRITTEN_BOOK; ItemStack ostack = new ItemStack(m); ItemMeta im = player.getServer().getItemFactory().getItemMeta(m); boolean complete = qd.isComplete(o.getID()); ArrayList<String>lore = new ArrayList<String>(); String[] desc = o.getDescription(); for(String s:desc)lore.add(s); if(o.isOptional()) { if(desc.length > 0)lore.add(""); lore.add(ChatColor.GOLD + "" + ChatColor.ITALIC + "Optional"); } if(complete) { String ps = o.getType().getProgressString(o.getTarget(), o.getTarget()); im.setDisplayName(ChatColor.GREEN + o.getName() + " " + ps); lore.add(ChatColor.YELLOW + "" + ChatColor.ITALIC + "Completed"); } else { String ps = o.getType().getProgressString(o.getTarget(), qd.getProgress(o.getID())); im.setDisplayName(ChatColor.YELLOW + o.getName() + " " + ps); } im.setLore(lore); ostack.setItemMeta(im); return ostack; }
8
public String getXML() throws KettleException { StringBuilder retval = new StringBuilder(); if (inputField != null) { retval.append(" ").append(XMLHandler.addTagValue("INPUT_FIELD", inputField)); } if (classpath != null) { retval.append(" ").append(XMLHandler.openTag("CLASSPATH")).append(Const.CR); for (String path : classpath) { retval.append(" " + XMLHandler.addTagValue("PATH", path)); } retval.append(" ").append(XMLHandler.closeTag("CLASSPATH")).append(Const.CR); } if (rootClass != null) { retval.append(" ").append(XMLHandler.addTagValue("ROOT_CLASS", rootClass)); } if (fields != null) { retval.append(" ").append(XMLHandler.openTag("FIELDS")).append(Const.CR); for (FieldDefinition field : fields) { retval.append(" ").append(XMLHandler.openTag("FIELD")).append(Const.CR); retval.append(" " + XMLHandler.addTagValue("NAME", field.name)); retval.append(" " + XMLHandler.addTagValue("PATH", field.path)); retval.append(" " + XMLHandler.addTagValue("TYPE", ValueMeta.getTypeDesc(field.type))); retval.append(" ").append(XMLHandler.closeTag("FIELD")).append(Const.CR); } retval.append(" ").append(XMLHandler.closeTag("FIELDS")).append(Const.CR); } return retval.toString(); }
6
public String scriptCreation(String appKey, String userKey, String testName) { try { appKey = URLEncoder.encode(appKey, "UTF-8"); userKey = URLEncoder.encode(userKey, "UTF-8"); testName = URLEncoder.encode(testName, "UTF-8"); } catch (UnsupportedEncodingException e) { BmLog.error(e); } return String.format("%s/api/rest/blazemeter/testCreate/?app_key=%s&user_key=%s&test_name=%s", SERVER_URL, appKey, userKey, testName); }
1
private boolean includes(HashMap<String, String> row, HashMap<String, String> list) { for (String key : list.keySet()) { String correct = list.get(key); String rowData = row.get(key); if (!correct.equals(rowData)) return false; } return true; }
2
public void wakeUp(final Guard guard){ Thread clockTick = new Thread(){ private Bandit prey = null; @Override public void run(){ for(GameMatter itm: area.getItems()){ if(itm instanceof Bandit){ prey = (Bandit) itm; } } try { this.sleep(2500); } catch (InterruptedException e) { e.printStackTrace(); } if (prey.getArea().equals(guard.area) && prey.getArea().getItems().contains(guard)){ prey.kill(); } } }; clockTick.start(); }
5
public Object getObject(String name) { try { return lookupObject(name); } catch (ObjectNotFoundException e) { return null; } }
1
public final synchronized void waitForInit() { if (--this.wait <= 0) { return; } while (this.wait != 0) { try { wait(); } catch (final InterruptedException e) { this.master.interrupt(); } } }
3
@EventHandler public void WitchNightVision(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getWitchConfig().getDouble("Witch.NightVision.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if ( plugin.getWitchConfig().getBoolean("Witch.NightVision.Enabled", true) && damager instanceof Witch && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, plugin.getWitchConfig().getInt("Witch.NightVision.Time"), plugin.getWitchConfig().getInt("Witch.NightVision.Power"))); } }
6
public void showPhoneNumberPopup() { phoneNumber.show(); }
0
public void addLink(int s, int d){ Node S = null; Node P = null; for(Node N : network) { if(N.id == s) { S = N; } if(N.id == d) { P = N; } } if(S != null && P != null) { S.addLink(new Link(P)); P.addLink(new Link(S)); D.getGraphPanel().addLink(S.id, P.id); D.getGraphPanel().repaint(); } else { System.err.println("Cannot find both nodes: " + s + " and " + d); } }
5
public final void forward(String target, String... patterns) { for (String path : patterns) { pages.forward(target, path); } }
1
public boolean equals(Object o) { MethodType mt; return (o instanceof MethodType && signature .equals((mt = (MethodType) o).signature)); }
1
@Override public void run(ListIterator<Instruction> iter) throws Exception { Instruction i = iter.next(); for(Value v : i.getArguments()) { if(v instanceof DefaultValue) { i.replaceArgument(v, new Immediate(0)); } } }
2
public NumberValidator(String str) { String[] parts = str.split(","); if (parts.length > 0) min = Long.parseLong(parts[0]); if (parts.length > 1) max = Long.parseLong(parts[1]); }
2
public BigDecimal getValue(int row, int clums, int sheetat) { BigDecimal value = new BigDecimal(0); String s = null; try { hSheet = hWorkbook.getSheetAt(sheetat); hRow = hSheet.getRow(row - 1); hCell = hRow.getCell(clums - 1); hCell.setCellType(Cell.CELL_TYPE_STRING); s = hCell.getStringCellValue(); value = new BigDecimal(s).setScale(2, BigDecimal.ROUND_HALF_UP); } catch (Exception e) { value = new BigDecimal(0); } return value; }
1
public void click(int x, int y) { if(x<9*drawSize && y<9*drawSize) { Cell clickedCell = grid[y/drawSize][x/drawSize]; if(clickedCell==selectedCell) { selectedCell.deselect(); selectedCell = null; } else { if(selectedCell!=null) { selectedCell.deselect(); } selectedCell = clickedCell; selectedCell.select(); } } }
4
public static void addComponentsToPane(Container pane) { if (!(pane.getLayout() instanceof BorderLayout)) { pane.add(new JLabel("Container doesn't use BorderLayout!")); return; } JPanel p = new JPanel(); caption = new JLabel(""); caption.setFont(caption.getFont().deriveFont(Font.BOLD, 16)); p.add(caption); pane.add(p, BorderLayout.PAGE_START); da = new DrawArea(null); pane.add(da, BorderLayout.CENTER); p = new JPanel(); p.setLayout(new BorderLayout()); logArea = new JTextArea("Atlikti veiksmai:\n"); logArea.setFont(logArea.getFont().deriveFont(Font.PLAIN, 12)); logArea.setEditable(false); JScrollPane scrollPane = new JScrollPane(logArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); scrollPane.setPreferredSize(new Dimension(300, 0)); p.add(scrollPane, BorderLayout.CENTER); logAreaCheck = new JCheckBox("Registruoti atliktus veiksmus.", true); p.add(logAreaCheck, BorderLayout.PAGE_END); pane.add(p, BorderLayout.WEST); p = new JPanel(); // this is needed because combo box selections are not displayed over the draw area sometimes p.setBorder(BorderFactory.createEmptyBorder(25, 0, 0, 0)); step = new JButton("Vienas žingsnis"); step.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { doStep = true; } }); p.add(step); final JTextField interval = new JTextField("2", 3); cont = new JButton("Tęsti"); cont.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (!doContinue) { try { float inter = Float.parseFloat(interval.getText()); SLEEP_BETWEEN_STEPS = (int)(inter*1000); if (SLEEP_BETWEEN_STEPS < 0) { throw new Exception("Step interval too small."); } doContinue = !doContinue; ((JButton)ae.getSource()).setText("Stabdyti"); interval.setEnabled(false); step.setEnabled(false); } catch (Exception ex) { JOptionPane.showMessageDialog(frame, "Žingsnio intervalas turi būti didesnis arba lygus nuliui.", "Netinkamas žingsnio intervalas", JOptionPane.ERROR_MESSAGE); } } else { ((JButton)ae.getSource()).setText("Tęsti"); interval.setEnabled(true); step.setEnabled(true); doContinue = !doContinue; } } }); p.add(cont); p.add(new JLabel("Žingsnis kas:")); p.add(interval); p.add(new JLabel("s.")); final JTextField diskNumber = new JTextField("3", 3); String[] algoTypes = { "Rekursyviai", "Iteraityviai"}; final JComboBox algoList = new JComboBox(algoTypes); JButton reset = new JButton("Iš naujo"); reset.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { try { diskCount = Integer.parseInt(diskNumber.getText()); if (diskCount < 0 || diskCount > 100) { throw new Exception("Disk number too small."); } doReset = true; currentSolutionType = algoList.getSelectedIndex(); doContinue = false; cont.setText("Tęsti"); step.setEnabled(true); cont.setEnabled(true); interval.setEnabled(true); done.setVisible(false); logArea.setText("Atlikti veiksmai:\n"); } catch (Exception ex) { JOptionPane.showMessageDialog(frame, "Diskų skaičius turi būti tarp 0 ir 100.", "Netinkamas diskų skaičius", JOptionPane.ERROR_MESSAGE); } } }); p.add(reset); p.add(algoList); p.add(new JLabel("Pradinis diskų skaičius:")); p.add(diskNumber); done = new JLabel("Išspręsta"); done.setOpaque(true); done.setBackground(new Color(0,255,0)); done.setVisible(false); done.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); p.add(done); pane.add(p, BorderLayout.PAGE_END); }
7
private void firePieceCompleted(Piece piece) { for (PeerActivityListener listener : this.listeners) { listener.handlePieceCompleted(this, piece); } }
1
@Override public void actionPerformed(ActionEvent arg0) { Object event = arg0.getSource(); int row = 0; int col = 0; int bombP = 0; if(event == confirm){ try{ row = Integer.parseInt(textRow.getText()); }catch(NumberFormatException e){ JOptionPane.showMessageDialog(this, "All Fields need to be filled with integers!"); this.textRow.setText("10"); } try{ col = Integer.parseInt(textCol.getText()); }catch(NumberFormatException e){ JOptionPane.showMessageDialog(this, "All Fields need to be filled with integers!"); this.textCol.setText("10"); } try{ bombP = Integer.parseInt(textBombs.getText()); }catch(NumberFormatException e){ JOptionPane.showMessageDialog(this, "All Fields need to be filled with integers!"); this.textBombs.setText("10"); } String errMessage = null; if(row > 0 && col > 0 && bombP > 0 && bombP < 101){ con.field.initialize(row, col); con.segregateBombs(bombP, errMessage); synchronized (this){ this.notify(); } } } }
8
public boolean remove(K k) { Node<K> parent = head; Node<K> n = head.getRight(); /* * Sucht Knoten mit zu löschendem Schlüssel. * Schleife erfasst auch Elternknoten des Knotens. */ while (n != nullNode) { int compare = k.compareTo(n.getKey()); if (compare == 0) { break; } parent = n; n = (compare > 0 ? n.getRight() : n.getLeft()); } /* * Falls Knoten mit gesuchtem Schlüssel nicht exisitet * gebe false zurück. */ if (n == nullNode) { return false; } System.out.println("Anzahl Kinder " + getChildCount(n) ); /* * Abhängig von der Kindanzahl wird die entsprechende Aktion * bzw. Methode ausgeführt. */ switch (getChildCount(n)) { case 0: if(parent.getLeft() == n) parent.setLeft(nullNode); else parent.setRight(nullNode); break; case 1: this.replace_with_child(parent, n); break; case 2: this.replace_with_Inorderpredecessor(parent, n); break; default: break; } return true; }
8
private void applyInvisibleLinkType(Annotation annotation) { // clear border thickness if (linkType == Annotation.INVISIBLE_RECTANGLE) { Object border = annotation.getObject(Annotation.BORDER_KEY); if (border != null && border instanceof Vector) { Vector borderProps = (Vector) border; if (borderProps.size() >= 3) { borderProps.set(2, 0); } } // check for a border style if (annotation.getBorderStyle() != null) { BorderStyle borderStyle = annotation.getBorderStyle(); borderStyle.setStrokeWidth(0); } } }
5
public static void main( String[] args ) { try{ (new Core(args)).run(); } catch(FileNotFoundException e) { System.out.println(Message.getSSLError("FileNotFound")); System.out.println("[CRITICAL]: Closing server."); } catch(java.net.ConnectException e) { System.out.println(Message.getSSLError("NoConnection")); System.out.println("[CRITICAL]: Closing server."); } catch(IOException e) { System.out.println(Message.getSSLError("WrongKey")); System.out.println("[CRITICAL]: Closing server."); } catch (UnrecoverableKeyException e) { System.out.println(Message.getSSLError("UnrecoverableKeyException")); System.out.println("[CRITICAL]: Closing server."); } catch (KeyManagementException e) { System.out.println(Message.getSSLError("KeyManagementException")); System.out.println("[CRITICAL]: Closing server."); } catch (KeyStoreException e) { System.out.println(Message.getSSLError("KeyStoreException")); System.out.println("[CRITICAL]: Closing server."); } catch (NoSuchAlgorithmException e) { System.out.println(Message.getSSLError("NoSuchAlgorithmException")); System.out.println("[CRITICAL]: Closing server."); } catch (CertificateException e) { System.out.println(Message.getSSLError("WrongCertificate")); System.out.println("[CRITICAL]: Closing server."); } }
8
public void run() { long currentTime = System.currentTimeMillis(); long lastTime; long deltaMs; options.save(); fpsCounter = 0; elapsed = 0; //resManager.getAudioManager().play(); while(!quitting && !Display.isCloseRequested()) { lastTime = currentTime; currentTime = System.currentTimeMillis(); deltaMs = currentTime - lastTime; lifetime += deltaMs; elapsed += deltaMs; fpsCounter++; if(elapsed >= 1000) { //System.out.println(fpsCounter); fps = fpsCounter; fpsCounter = 0; elapsed = 0; } // If the window was resized, we need to update our projection if (Display.wasResized()) { resize(); } logic.update(deltaMs); humanView.update(deltaMs); eventManager.update(); Display.update(); } resManager.destroy(); Display.destroy(); }
4
public RollupTaskXmlDriver(String xmlStr) throws DocumentException, XmlTypeErrorException { super(); if (!isRollupTaskXml(xmlStr)) { throw new XmlTypeErrorException("not a valid rollupTask Xml"); } document = DocumentHelper.parseText(xmlStr); timestamp = document.selectSingleNode("//properties/timestamp") .getText(); fromCubeIdentifier = document.selectSingleNode( "//properties/operation/from").getText(); Element root = this.document.getRootElement(); List<?> list = root .selectNodes("//properties/operation/conditions/condition"); String dimensionName; String levelName; final String start = ""; final String end = ""; ConditionBean conditionBean; for (Iterator<?> iter = list.iterator(); iter.hasNext(); ) { Node node = (Node) iter.next(); dimensionName = node.selectSingleNode("dimensionName").getText(); levelName = node.selectSingleNode("levelName").getText(); conditionBean = new ConditionBean(dimensionName, levelName, start, end); conditionBeans.add(conditionBean); } }
4
public MainViewPanel() { super(); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setBackground(Color.WHITE); for (int i = 0; i < paintings.length; i++) paintings[i] = new Painting(); for(int i = 0; i< graphics.length; i++) graphics[i] = paintings[i].createGraphics(); for (int i = 0; i < sliders.length; i++) { sliders[i] = new JSlider(JSlider.HORIZONTAL, 0, 10, 5); sliders[i].setBackground(Color.WHITE); sliders[i].setMajorTickSpacing(1); sliders[i].setPaintTicks(true); sliders[i].setPaintLabels(true); } add(Box.createRigidArea(new Dimension(x, y))); JPanel pan2 = new JPanel(new FlowLayout(FlowLayout.CENTER, 60, 0)); pan2.setBackground(Color.WHITE); for (int i = 0; i < 4; i++) pan2.add(sliders[i]); add(pan2); add(Box.createRigidArea(new Dimension(x, y))); JPanel pan4 = new JPanel(new FlowLayout(FlowLayout.CENTER, 60, 0)); pan4.setBackground(Color.WHITE); for (int i = 4; i < sliders.length; i++) pan4.add(sliders[i]); add(pan4); }
5
@Override public void put( ByteBuffer out, Class<?> v ) { if ( v == null ) { out.put( Compress.NULL ); } else { String name = v.getCanonicalName(); Compress.putIntUnsignedNullable( out, name.length() ); out.put( name.getBytes() ); } }
2
public GenericDAO<Employee> getEmployeesDAO() { if (_employeesDAO == null) { _employeesDAO = new GenericDAO(Employee.class); } return _employeesDAO; }
1
public void paintObjects() { removeAll(); Button btop = new Button("top"); objectsName = new Label[objects.size()]; objectsSize = new Label[objects.size()]; objectsSelect = new Button[objects.size()]; lobjs.setFont(new Font(Font.SERIF, Font.PLAIN, 25)); add(lobjs); add(btop); lobjs.setBounds(20,40, 100, 20); btop.setBounds(210, 40, 200, 30); btop.addActionListener(this); int count = 1; int max; if(objects.size() > items * page) { max = items * page; } else { max = objects.size(); } int j = 0; for(Map.Entry<String, Object> e : objects.entrySet()) { if(j >= (page -1) * items && j < max){ Object[] value = (Object[])e.getValue(); int size = value.length; objectsName[count - 1] = new Label(e.getKey()); objectsSize[count - 1] = new Label(String.valueOf(size)); objectsSelect[count - 1] = new Button("select"); add(objectsName[count - 1]); add(objectsSize[count - 1]); add(objectsSelect[count - 1]); objectsName[count - 1].setBounds(20,40 + 90 * count,200,30); objectsSize[count - 1].setBounds(objectsName[count - 1].getX() + objectsName[count - 1].getWidth() + 20,40 + 90 * count,30,30); objectsSelect[count - 1].setBounds(objectsSize[count - 1].getX() + objectsSize[count - 1].getWidth() + 20 , 40 + 90 * count, 100, 30); objectsSelect[count - 1].setActionCommand("select" + e.getKey()); objectsSelect[count - 1].addActionListener(this); count++; } j++; } if(objects.size() > page * items){ Button bn = new Button("next"); bn.setActionCommand("nextObjects"); add(bn); bn.setBounds(100, 590, 50, 30); bn.addActionListener(this); } if(page > 1){ Button bp = new Button("prev"); bp.setActionCommand("nextObjects"); add(bp); bp.setBounds(20, 590, 50, 30); bp.addActionListener(this); } Label p = new Label(page + "/" + ((objects.size() - 1) / items + 1)); add(p); p.setBounds(180, 590, 50, 30); }
6
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String act = request.getParameter("act"); String message = null; if (act == null) { act = ""; } else { act = act.trim(); } TimeLogger tl = new TimeLogger(); try { if (act.equals("insert")) { int entries = Integer.parseInt(request.getParameter("num")); boneService.addDummyBones(entries); message = String.format("Inserting %d entries in H2 takes time: %d.", entries, tl.getTimeDiff()); } else if (act.equals("count")) { message = boneService.getTotalNumberOfBones() + ""; } else if (act.equals("queryAll")) { List<Bone> bones = boneService.getAllBones(); message = JSONArray.fromObject(bones).toString(); } else if (act.equals("init")) { int i = boneService.createBoneTable(); message = "Create table returns " + i; } else if (act.equals("clear")) { int i = boneService.clearBones(null); message = "Clear bones returns " + i; } else if (act.equalsIgnoreCase("rejectedLog")) { message = testRejectedLog(); } else { message = "Unknown action" + act + ", accepts: init, count, insert, queryAll, clear. \nExamples:\n" + "http://localhost:8080/BoneSpringBatis/InfoDbTest" + "http://localhost:8080/BoneSpringBatis/InfoDbTest?act=insert&num=10" + "http://localhost:8080/BoneSpringBatis/InfoDbTest?act=query"; } } catch (Exception e) { message = "An error occurred, did you forget to init your tables?"; logger.error(e); } PrintWriter writer = response.getWriter(); JSONObject jobj = JSONObject.fromObject(new Result(message)); writer.append(jobj.toString()); writer.close(); new XmlWebApplicationContext().close(); }
8
public Board chooseMove() throws Exception{ int ties = 1; double bestValue = Double.NEGATIVE_INFINITY, currentValue; Board bestMove = null, currentMove; double[] results = new double[TaTeTi.MAX_CELLS*TaTeTi.MAX_CELLS]; LinkedList<Board> availableMoves = eg.getAvailableMovesForPlayer(cellValue, currentBoard); Iterator it = availableMoves.iterator(); Random rand = new Random(); while (it.hasNext()){ currentMove = (Board)it.next(); currentValue = vEstimate(currentMove, false); if(currentValue >= bestValue){ if(currentValue == bestValue){ bestMove = (Math.random()>=(0.5/ties)) ? bestMove : currentMove; ties++; } else{ bestMove = currentMove; } bestValue = currentValue; } } for(int i=0; i<availableMoves.size();i++) results[i] = vEstimate(availableMoves.get(i),false); if(TaTeTi.print){ for(int i=0; i<availableMoves.size();i++){ if(results[i]==bestValue){ System.out.println("Movida con puntaje maximo: "); vEstimate(availableMoves.get(i),true); availableMoves.get(i).print(); System.out.println("puntaje: " + results[i]); } } if(bestMove!=null){ System.out.println("Movida elegida: "); bestMove.print(); System.out.println("value for best move: " + bestValue); vEstimate(bestMove, true); } } return bestMove; }
9
private static void setSpawnLocation() { int rand = random.nextInt(8); switch (rand) { case 0: spawnLocation.setVector(110, 425); break; case 1: spawnLocation.setVector(345, 185); break; case 2: spawnLocation.setVector(755, 85); break; case 3: spawnLocation.setVector(1150, 140); break; case 4: spawnLocation.setVector(1465, 425); break; case 5: spawnLocation.setVector(1306, 650); break; case 6: spawnLocation.setVector(800, 800); break; case 7: spawnLocation.setVector(395, 720); break; } }
8
private ArrayList<Operation> getAllOperation(String Declaration) { ArrayList<Operation> ArrayOperation = new ArrayList(); Declaration = Declaration.trim(); if(Declaration.equals("")){ return ArrayOperation; } else { boolean nextop = true; int i = 0; while(nextop){ String id =""; while(Declaration.charAt(i) != '('){ id += Declaration.charAt(i); i++; } i++; String arg =""; while(Declaration.charAt(i) != ')'){ arg += Declaration.charAt(i); i++; } ArrayList<Argument> arrayarg = getArguments(arg); while(Declaration.charAt(i) != ':')i++; i++; String nomtype =""; while(Declaration.charAt(i) != ',' && i < Declaration.length()-1){ nomtype += Declaration.charAt(i); i++; } if(Declaration.charAt(i) != ','){ nomtype += Declaration.charAt(i); nextop = false; } else { i++; } Operation op = new Operation(id.trim(), new Type(nomtype.trim()), arrayarg); ArrayOperation.add(op); } } return ArrayOperation; }
8
void reprodukcja() { // tworzę tablicę skumulowanych wartości przystosowania: double fittness_skum[] = new double[liczba_rozw]; fittness_skum[0] = fittness[0]; for (int i=1;i<liczba_rozw;i++) fittness_skum[i] = fittness_skum[i-1] + fittness[i]; Rozw nowa_popul_rozw[] = new Rozw[liczba_rozw]; for (int i=0;i<liczba_rozw;i++) nowa_popul_rozw[i] = new Rozw(); for (int i=0;i<liczba_rozw;i++) { double los = loteria.nextFloat()*fittness_skum[liczba_rozw-1]; int indeks = -1; //System.out.printf("los = %f, fit_min = %f, fit_max = %f\n",los,fittness_skum[0],fittness_skum[liczba_rozw-1]); if (los <= fittness_skum[0]) indeks = 0; else { int k,l = 0, p = liczba_rozw-1; // wyszukiwanie binarne miejsca na ruletce: while (indeks == -1) { k = (l+p)/2; if (los > fittness_skum[k]) l = k+1; else p = k-1; //System.out.printf("l = %d, p = %d, k = %d, \n",l,p,k); if ((los <= fittness_skum[k])&&(los > fittness_skum[k-1])) indeks = k; } } // utworzenie nowej kopii rozwiązania i umieszczenie jej w nowej populacji: nowa_popul_rozw[i].kopiuj_obiekt(popul_rozw[indeks]); } // for po rozwiązaniach popul_rozw = nowa_popul_rozw; // nowa populacja zastępuje starą }
8
private int YUV_to_BGR(int Y, int u, int v) { if (Y < 0) { Y = 0; } int tempB, tempG, tempR; tempB = Y + ((116130 * u) >> 16); if (tempB < 0) { tempB = 0; } else if (tempB > 255) { tempB = 255; } tempG = Y - ((22554 * u + 46802 * v) >> 16); if (tempG < 0) { tempG = 0; } else if (tempG > 255) { tempG = 255; } tempR = Y + ((91881 * v) >> 16); if (tempR < 0) { tempR = 0; } else if (tempR > 255) { tempR = 255; } return 0xff000000 | ((tempR << 16) + (tempG << 8) + tempB); }
7
public void reachableClass(String clazzName) { ClassIdentifier ident = getClassIdentifier(clazzName); if (ident != null) ident.setReachable(); }
1
public static void main(String args[]){ String objectListPath = "/u/ml/mindseye/nlg_lm/LM/lesk_syns_purdue.txt"; int no_objects = readObjectList(objectListPath); String outputMatrixPath = "/u/ml/mindseye/nlg_lm/LM/object_count.txt"; int[] object_counts = new int[no_objects]; String ldcCorpusPath = "/scratch/cluster/niveda/extracted_original"; File input_folder = new File(ldcCorpusPath); Stack<File> stack = new Stack<File>(); stack.push(input_folder); int x=1; try{ while (!stack.isEmpty()) { File child = stack.pop(); if (child.isDirectory()) { for (File f : child.listFiles()) stack.push(f); } else if (child.isFile()) { System.out .println("Processing: " + child.getAbsolutePath()); FileReader fr = new FileReader(child.getAbsolutePath()); BufferedReader br = new BufferedReader(fr); String readLine = ""; while ((readLine = br.readLine()) != null) { String words[] = readLine.split("\\s+"); for(int i=0;i<words.length;i++){ if(object_words.containsKey(words[i])) object_counts[object_words.get(words[i])]+=1; } } br.close(); fr.close(); } } FileWriter fw = new FileWriter(outputMatrixPath); fw.write("[OBJECT_COUNTS]\n"); for (int i = 0; i < no_objects; i++) { fw.write(object_counts[i]+"\t"); } fw.close(); } catch(Exception e){ System.out.println("Exception caught:"+e); e.printStackTrace(); } }
9
public static Vector<PhyloTreeEdge> getCommonEdges(PhyloTree t1, PhyloTree t2) { Vector<PhyloTreeEdge> commonEdges = new Vector<PhyloTreeEdge>(); // if the two trees do not have the same leaf2NumMap if (!(t1.getLeaf2NumMap().equals(t2.getLeaf2NumMap()))) { System.out.println("Error: the two trees do not have the same leaves!"); System.out.println("First tree's leaves are " + t1.getLeaf2NumMap()); System.out.println("Second tree's leaves are " + t2.getLeaf2NumMap()); throw new RuntimeException(); } for (PhyloTreeEdge e1 : t1.edges) { // check that the split is not 0 (has no leaves and can be thought of as a null split; ignore such edges) if (!e1.isZero()) { if (t2.getSplits().contains(e1.asSplit())) { // then we have found the same split in each tree EdgeAttribute commonAttrib = EdgeAttribute.difference(e1.getAttribute(), t2.getAttribOfSplit(e1.asSplit())); commonEdges.add(new PhyloTreeEdge(e1.asSplit(), commonAttrib, e1.getOriginalID())); } // otherwise check if the split is compatible with all splits in t2 else if (e1.isCompatibleWith(t2.getSplits())) { EdgeAttribute commonAttrib = EdgeAttribute.difference(e1.getAttribute(), null); commonEdges.add(new PhyloTreeEdge(e1.asSplit(), commonAttrib, e1.getOriginalID())); } } } // check for splits in t2 that are compatible with all splits in t1 for (PhyloTreeEdge e2 : t2.getEdges()) { if (!e2.isZero()) { if (e2.isCompatibleWith(t1.getSplits()) && !(t1.getSplits().contains(e2.asSplit()))) { EdgeAttribute commonAttrib = EdgeAttribute.difference(null, e2.getAttribute()); commonEdges.add(new PhyloTreeEdge(e2.asSplit(), commonAttrib, e2.getOriginalID())); } } } return commonEdges; }
9
public static boolean create(String[] args, CommandSender s){ // Various checks to prevent the guild creation from going through if it shouldn't happen if(Util.isBannedFromGuilds(s) == true){ //Checking if they are banned from the guilds system s.sendMessage(ChatColor.RED + "You are currently banned from interacting with the Guilds system. Talk to your server admin if you believe this is in error."); return false; } if(!s.hasPermission("zguilds.player.create")){ //Checking if they have the permission node to proceed s.sendMessage(ChatColor.RED + "You lack sufficient permissions to create a guild. Talk to your server admin if you believe this is in error."); return false; } if(Util.isInGuild(s) == true){ //Checking if they're already in a guild s.sendMessage(ChatColor.RED + "You're already in a guild! You can't create a new one until you leave your current guild."); return false; } if(args.length > 2 || args.length == 1){ //Checking if the create command has proper args s.sendMessage(ChatColor.RED + "Incorrectly formatted guild name! Proper syntax is: \"/guild create GuildNameHere\""); return false; } if(args[1].length() > 10 || args[1].length() < 4){ //Checking if the chosen guild name is between 4-10 characters s.sendMessage(ChatColor.RED + "Your chosen guild name must be between 4 and 10 characters."); return false; } if(!args[1].matches("^[0-9a-zA-Z]+$")){ //Checking if the chosen guild name matches the appropriate regex (no special characters, only letters and numbers, capitals allowed), REGEX: ^[0-9a-zA-Z]+$ s.sendMessage(ChatColor.RED + "Your chosen guild name doesn't match the requirements. Only letters (caps and lowercase) and numbers."); return false; } guildNameInternal = args[1].toLowerCase(); if(Main.guilds.getConfigurationSection("Guilds." + guildNameInternal) != null){ //Checking if that guild already exists s.sendMessage(ChatColor.RED + "Your chosen guild name already exists. Choose a different name."); return false; } //Variable initialization if the guild creation passed all of the necessary checks playerName = s.getName().toLowerCase(); now = new Date(); dateCreated = now.toString(); guildNameInternal = args[1].toLowerCase(); guildNameDisplayed = args[1]; //Guild creation (assuming it got through all the above checks)! Main.guilds.set("Guilds." + guildNameInternal + ".Created", Var.GuildDefaults_Created); //created: true or false (out of charter phase) Main.guilds.set("Guilds." + guildNameInternal + ".Level", Var.GuildDefaults_Level); //level Main.guilds.set("Guilds." + guildNameInternal + ".Chat_Prefix", guildNameDisplayed); //chat prefix Main.guilds.set("Guilds." + guildNameInternal + ".Type", Var.GuildDefaults_Type); //type Main.guilds.set("Guilds." + guildNameInternal + ".Creation_Date", dateCreated); //creation date Main.guilds.set("Guilds." + guildNameInternal + ".Max_Members", Var.GuildDefaults_MaxMembers); //max members Main.guilds.set("Guilds." + guildNameInternal + ".Roster_Size", 1); //number of members Main.guilds.set("Guilds." + guildNameInternal + ".New_Member_Starting_Rank", Var.GuildDefaults_DefaultRank); //new member starting rank Main.guilds.set("Guilds." + guildNameInternal + ".Home_Location.X_Coordinate", Var.GuildDefaults_HomeX); Main.guilds.set("Guilds." + guildNameInternal + ".Home_Location.Y_Coordinate", Var.GuildDefaults_HomeY); Main.guilds.set("Guilds." + guildNameInternal + ".Home_Location.Z_Coordinate", Var.GuildDefaults_HomeZ); Main.guilds.set("Guilds." + guildNameInternal + ".Home_Location.World", Var.GuildDefaults_HomeWorld); Main.guilds.set("Guilds." + guildNameInternal + ".Ranks.10", Var.GuildDefaults_Rank10); // default rank 10 Main.guilds.set("Guilds." + guildNameInternal + ".Ranks.9", Var.GuildDefaults_Rank9); // default rank 9 Main.guilds.set("Guilds." + guildNameInternal + ".Ranks.8", Var.GuildDefaults_Rank8); // default rank 8 Main.guilds.set("Guilds." + guildNameInternal + ".Ranks.7", Var.GuildDefaults_Rank7); // default rank 7 Main.guilds.set("Guilds." + guildNameInternal + ".Ranks.6", Var.GuildDefaults_Rank6); // default rank 6 Main.guilds.set("Guilds." + guildNameInternal + ".Ranks.5", Var.GuildDefaults_Rank5); // default rank 5 Main.guilds.set("Guilds." + guildNameInternal + ".Ranks.4", Var.GuildDefaults_Rank4); // default rank 4 Main.guilds.set("Guilds." + guildNameInternal + ".Ranks.3", Var.GuildDefaults_Rank3); // default rank 3 Main.guilds.set("Guilds." + guildNameInternal + ".Ranks.2", Var.GuildDefaults_Rank2); // default rank 2 Main.guilds.set("Guilds." + guildNameInternal + ".Ranks.1", Var.GuildDefaults_Rank1); // default rank 1 Main.players.set("Players." + playerName + ".Guild_Leader", true); Main.players.set("Players." + playerName + ".Current_Guild", guildNameInternal); Main.players.set("Players." + playerName + ".Current_Rank", 10); Main.players.set("Players." + playerName + ".Guild_Contributions", 0); Main.players.set("Players." + playerName + ".Member_Since", dateCreated); Main.players.set("Players." + playerName + ".Current_Invitation", "N/A"); s.sendMessage(ChatColor.DARK_GREEN + "You created a guild called " + ChatColor.DARK_GRAY + guildNameDisplayed + ChatColor.DARK_GREEN + "!"); Bukkit.broadcastMessage(ChatColor.DARK_GRAY + "The guild [" + ChatColor.DARK_GREEN + guildNameDisplayed + ChatColor.DARK_GRAY + "] has been created."); Main.saveYamls(); return true; }
9
public long getNumericalAddress() { return _address; }
0
public boolean compositeRank() { if(throwback) { for(Song song: library) { double score= (dateAddedWeight*song.getDARank()) + (playCountWeight*song.getPCRank())+ (timeLengthWeight*song.getTLRank()); song.setCompositeScore(score); } Collections.sort(library, ScoreComparator.getScorer()); for(int i=0; i<library.size(); i++) { library.get(i).setCompositeRank(i+1); } } else { for(Song song: library) { double score= (playCountWeight*song.getPCRank())+ (timeLengthWeight*song.getTLRank()); song.setCompositeScore(score); } Collections.sort(library, ScoreComparator.getScorer()); for(int i=0; i<library.size(); i++) { library.get(i).setCompositeRank(i+1); } } return throwback; }
5
public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("sd"); }
0
public void bidSearch( ) { FacesContext fc = FacesContext.getCurrentInstance(); try { Bid_DTO bid = bidService.getBid( idBid ); setIdItem( bid.getIdItem()); setIdUser( bid.getIdUser()); setImporte( bid.getBidPrice() ); } catch (ClassCastException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); fc.addMessage( "bidBid.msjBidBid", new FacesMessage( "<!>", "Error al buscar bid. " + e.getMessage() )); clean(); } catch ( NoHayDatosDBException e ) { fc.addMessage( "bidBid.msjBidBid", new FacesMessage( "<!>", "No fue encontrado bid con # " + idBid )); clean(); } }
3
public void przerysujPlansze() { liczbaPrzerysowaniaPlanszy++; for(int k=0;k<10;k++) for(int l=0;l<10;l++) { if(liczbaPrzerysowaniaPlanszy > 1) { if(widokRozmiesc.uzytkownik.plansza.l_polaPlanszy_GRACZ[l][k].getRodzajPola().equals("1")) { //lb_polaGry[l][k].setBackground(Color.BLUE); lb_polaGry[l][k].setIcon(img_poleStatku); } else if(widokRozmiesc.uzytkownik.plansza.l_polaPlanszy_GRACZ[l][k].getRodzajPola().equals("X")) { //lb_polaGry[l][k].setBackground(Color.RED); lb_polaGry[l][k].setIcon(img_poleZablokowane); } else { //lb_polaGry[l][k].setBackground(new Color(240,240,240)); lb_polaGry[l][k].setIcon(img_zwyklePole); } } else lb_polaGry[l][k].setIcon(img_zwyklePole); } }
5
private Header readNextFrame() throws BitstreamException { if (framesize == -1) { nextFrame(); } return header; }
1
@Override public SyrianEdge getMove(SyrianGraph graph) throws AgentHasNoMoveException, AgentIsDoneException { if (this.getLocation() == this.getTarget() && graph.getVerticesWithChemicals().size() == 0){ throw new AgentIsDoneException(this); } AbstractList<SimpleHeuristicNode> path = this .getPathToTargetWithChemicalsAllowReVisits(graph, this.getLocation()); System.out.println("Path: "); for (SimpleHeuristicNode hn : path) { System.out.println(hn.toString()); } SimpleHeuristicNode move = path.get(path.size() - 1); if (move.hasChemicals() && !this.hasChemicals()) { try { this.takeChemicals(); } catch (AgentAlreadyHasChemicalsException e) { System.out.println("Error in path!"); e.printStackTrace(); } catch (LocationDoesntHaveChemicalsException e) { System.out.println("Error in path!"); e.printStackTrace(); } } System.out.println("MOVE: " + move.toString()); return move.getPath(); }
7
public int getRowInsertionIndex(int y) { List<Row> rows = mModel.getRows(); int pos = getInsets().top; int last = getLastRowToDisplay(); for (int i = getFirstRowToDisplay(); i <= last; i++) { Row row = rows.get(i); if (!mModel.isRowFiltered(row)) { int height = row.getHeight(); int tmp = pos + height / 2; if (y <= tmp) { return i; } pos += height + (mDrawRowDividers ? 1 : 0); } } return last; }
4
private static Color getColor(int counter) { return colors[counter % colors.length]; }
0
public void removeEdge(final GraphNode v, final GraphNode w) { Assert.isTrue(nodes.containsValue(v), "Graph does not contain " + v); Assert.isTrue(nodes.containsValue(w), "Graph does not contain " + w); Assert.isTrue(v.succs().contains(w)); if (removingEdge == 0) { succs(v).remove(w); } else if (removingEdge != 1) { throw new RuntimeException(); } edgeModCount++; }
2
private void createResolutionCombo(PrintRequestAttributeSet set) { PrinterResolution[] resolutions = (PrinterResolution[]) mService.getSupportedAttributeValues(PrinterResolution.class, DocFlavor.SERVICE_FORMATTED.PRINTABLE, null); if (resolutions != null && resolutions.length > 0) { PrinterResolution current = PrintUtilities.getResolution(mService, set, true); WrappedPrinterResolution[] wrappers = new WrappedPrinterResolution[resolutions.length]; int selection = 0; for (int i = 0; i < resolutions.length; i++) { wrappers[i] = new WrappedPrinterResolution(generateResolutionTitle(resolutions[i]), resolutions[i]); if (resolutions[i] == current) { selection = i; } } mResolution = new JComboBox<>(wrappers); mResolution.setSelectedIndex(selection); UIUtilities.setOnlySize(mResolution, mResolution.getPreferredSize()); LinkedLabel label = new LinkedLabel(RESOLUTION, mResolution); add(label, new PrecisionLayoutData().setEndHorizontalAlignment()); add(mResolution); } else { mResolution = null; } }
4
public Label nextBlock(final Label label) { boolean seen = false; final Iterator iter = code.iterator(); while (iter.hasNext()) { final Object obj = iter.next(); if (obj instanceof Label) { if (seen) { final Label l = (Label) obj; if (l.startsBlock()) { return l; } } else if (label.equals(obj)) { seen = true; } } } return null; }
5
public static double[] baseProportions(String s) { int aCount = 0; int tCount = 0; int gCount = 0; int cCount = 0; int count = 0; for (int i = 0; i < s.length(); i++) { switch (s.charAt(i)) { case 'A': aCount++; count++; break; case 'T': tCount++; count++; break; case 'G': gCount++; count++; break; case 'C': cCount++; count++; break; default: break; } } double[] vals = new double[4]; vals[0] = (double) aCount / (double) count; vals[1] = (double) tCount / (double) count; vals[2] = (double) gCount / (double) count; vals[3] = (double) cCount / (double) count; return vals; }
5
public MainFrame() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); setSize(800, 600); setLocationRelativeTo(null); contentPane = new JPanel(); contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.X_AXIS)); JPanel listPanel = new JPanel(); textField = new JTextField(); textField.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent arg0) { } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { SearchList(textField.getText()); } }); listPanel.setLayout(new BoxLayout(listPanel, BoxLayout.Y_AXIS)); listPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); listPanel.add(Box.createHorizontalGlue()); listPanel.add(textField); textField.setColumns(10); textField.setMaximumSize(new Dimension(100000, 60)); listPanel.add(Box.createRigidArea(new Dimension(0, 5))); refreshList(); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane listScroller = new JScrollPane(list); listPanel.add(listScroller); removeItembtn = new JButton("Remove Selected Item"); removeItembtn.setAlignmentX(Component.CENTER_ALIGNMENT); removeItembtn.addActionListener(this); removeItembtn.setMaximumSize(new Dimension(100000, 80)); addToBillbtn = new JButton("Add to Bill"); addToBillbtn.addActionListener(this); addToBillbtn.setMaximumSize(new Dimension(100000, 80)); addNewItembtn = new JButton("Add Item to List"); addNewItembtn.setMaximumSize(new Dimension(100000, 80)); addNewItembtn.addActionListener(this); addNewItembtn.setAlignmentX(Component.CENTER_ALIGNMENT); modifyItembtn = new JButton("Modify Item"); modifyItembtn.setAlignmentX(Component.CENTER_ALIGNMENT); modifyItembtn.addActionListener(this); modifyItembtn.setMaximumSize(new Dimension(100000, 80)); listPanel.add(removeItembtn); listPanel.add(modifyItembtn); listPanel.add(addNewItembtn); quantityPanel = new JPanel(); quantityPanel.setLayout(new BoxLayout(quantityPanel, BoxLayout.X_AXIS)); quantityPanel.setMaximumSize(new Dimension(100000, 80)); quantityLabel = new JLabel("Quantity"); quantityTextField = new JTextField(); quantityTextField.addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { char vChar = e.getKeyChar(); if (!(Character.isDigit(vChar) || (vChar == KeyEvent.VK_BACK_SPACE) || (vChar == KeyEvent.VK_DELETE))) { e.consume(); } } }); quantityPanel.add(quantityLabel); quantityPanel.add(quantityTextField); quantityPanel.add(addToBillbtn); listPanel.add(quantityPanel); table = new JTable(); JPanel billPanel = new JPanel(); billPanel.add(new JScrollPane(table)); billPanel.setLayout(new BoxLayout(billPanel, BoxLayout.Y_AXIS)); billPanel.add(Box.createHorizontalGlue()); billPanel.setPreferredSize(new Dimension(400, 500)); JPanel toolPanel = new JPanel(); toolPanel.setLayout(new BoxLayout(toolPanel, BoxLayout.X_AXIS)); removeFromBill = new JButton("Remove from bill"); removeFromBill.setAlignmentX(Component.CENTER_ALIGNMENT); removeFromBill.addActionListener(this); removeFromBill.setMaximumSize(new Dimension(100000, 60)); toolPanel.add(removeFromBill); saveBill = new JButton("Save Bill"); saveBill.setAlignmentX(Component.CENTER_ALIGNMENT); saveBill.addActionListener(this); saveBill.setMaximumSize(new Dimension(100000, 60)); toolPanel.add(saveBill); loadBill = new JButton("Load Bill"); loadBill.setAlignmentX(Component.CENTER_ALIGNMENT); loadBill.addActionListener(this); loadBill.setMaximumSize(new Dimension(100000, 60)); toolPanel.add(loadBill); sumLabel = new JLabel("SUM:"); sumLabel.setAlignmentX(Component.CENTER_ALIGNMENT); sumLabel.setMaximumSize(new Dimension(100000, 60)); toolPanel.add(sumLabel); sum = new JLabel("" + 0); sum.setAlignmentX(Component.CENTER_ALIGNMENT); toolPanel.add(sum); billPanel.add(toolPanel); splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listPanel, billPanel); contentPane.add(splitPane, BorderLayout.CENTER); splitPane.setResizeWeight(0.3); splitPane.setContinuousLayout(true); setContentPane(contentPane); pack(); }
3
public void BuildMobs() { for (int i = 0; i < MOBS.length; i++) { if (Engine.mfo.pfh.ReadPlayerType == 1) { MOBS[i] = new Sleeper(Engine.mfo.pfh.ReadPlayerX, Engine.mfo.pfh.ReadPlayerY, Engine.mfo.pfh.ReadPlayerName, Engine.mfo.pfh.ReadPlayerLayer); } else if (Engine.mfo.pfh.ReadPlayerType == 2) { MOBS[i] = new Wizard(Engine.mfo.pfh.ReadPlayerX, Engine.mfo.pfh.ReadPlayerY, Engine.mfo.pfh.ReadPlayerName, Engine.mfo.pfh.ReadPlayerLayer); } if (i == 0) { MOBS[i].isControlledByPlayer = true; MOBS[i].map=Engine.mfo.pfh.ReadPlayerMap; for(int h=0;h<MOBS[i].ITEMS.length;h++){ for(int w=0;w<MOBS[i].ITEMS[h].length;w++){ if(Engine.mfo.pfh.ITEMS[h][w]==0){ MOBS[i].ITEMS[h][w]=new NoItem(); }else if(Engine.mfo.pfh.ITEMS[h][w]==1){ MOBS[i].ITEMS[h][w]=new Candle(); } } } } } }
8
public void run(String[] params) { int codeLine = 0; for(String string : codeLines) { codeLine++; try { try { // System.out.println(string); String[] spl = string.split("\\<"); // System.out.println(spl[1]); if (spl[0].equalsIgnoreCase("toss")) { returnValue = getInterpreter().getValue(spl[1]); return; } } catch (Exception e) { // e.printStackTrace(); } interpreter.interpret(string); } catch (Exception e) { System.out.println("Encountered error at line " + codeLine + "!"); e.printStackTrace(); // printStackTrace(interpreter.getStack()); } } }
4
public Loader() throws MessageStackException { copyFile("map.txt"); copyFile("community.txt"); copyFile("events.txt"); if(isSerialized()) { try { //reads serialized data from monopoly.ser to get every map data and player data ObjectInputStream serializedFile = new ObjectInputStream(new FileInputStream("monopoly.ser")); go = (FieldCircularList) serializedFile.readObject(); jail = (FieldCircularList) serializedFile.readObject(); event = (CardStack) serializedFile.readObject(); community = (CardStack) serializedFile.readObject(); playerHashMap = (HashMap<Integer, Player>) serializedFile.readObject(); } catch(IOException e) { new File("monopoly.ser").delete(); throw new LoaderException("The problem occurred while reading the file monopoly.ser.", e); } catch(ClassNotFoundException e) { new File("monopoly.ser").delete(); throw new LoaderException("The problem occurred while reading a class from the file monopoly.ser.", e); } } else { //creates a new MapArrayCreator, gets every map data and creates/connects a new map. //newly created data is serialized and stored in monopoly.ser try { //TODO load files in three threads and check for a.join(), b.join() c.join() MapArrayCreator mac = new MapArrayCreator(); event = new CardStack("events.txt", "Event Karte"); community = new CardStack("community.txt", "Gemeinschafts Karte"); new Connector().connect(mac.getMap(), event, community, playerHashMap); go = mac.getGo(); jail = mac.getJail(); ObjectOutputStream serializedFile = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("monopoly.ser"))); serializedFile.writeObject(go); serializedFile.writeObject(jail); serializedFile.writeObject(event); serializedFile.writeObject(community); serializedFile.writeObject(playerHashMap); serializedFile.close(); } catch(IOException e) { new File("monopoly.ser").delete(); throw new LoaderException("The problem occurred while writing to the monopoly.ser file.", e); } } }
4
private static final boolean isFinisher(final int skillid) { switch (skillid) { case 1111003: case 1111004: case 1111005: case 1111006: case 11111002: case 11111003: return true; } return false; }
6
private boolean isDead(Node node){ if(node.getX() < 0 || node.getX() > Map.WIDTH){ this.isDead = true; return true; } if(node.getY() < 0 || node.getY() > Map.HEIGHT){ this.isDead = true; return true; } for(Node _node : body){ if(node.isEquals(_node)){ this.isDead = true; return true; } } return false; }
6
public List<Claim> getPublicClaimList(String parentClaimId, String claimType) { List<Claim> counterclaimList = new ArrayList<Claim>(); Element claimE; Claim claim; for (Iterator i = root.elementIterator(claimType); i.hasNext();) { claimE = (Element)i.next(); if (claimE.element("isDelete").getText().equals("false") && claimE.element("parentClaimId").getText().equals(parentClaimId)) { String id = claimE.element("id").getText() , title = claimE.element("title").getText() , type = claimE.element("type").getText(); // For public dialog, do not have to find parent claim, so it sets to null claim = new Claim(id, title, type, parentClaimId); if (claimE.attributeValue("teamType").equals("A")) { claim.setTeamType("A"); } else { claim.setTeamType("B"); } counterclaimList.add(claim); } } return counterclaimList; }
4
@Override public int compareTo(Team t) { if(this.points > t.points) { return HIGHER; } if(this.points == t.points) { if(this.goalDifference > t.goalDifference) { return HIGHER; } if(this.goalDifference == t.goalDifference) { if(this.goalsFor > t.goalsFor) { return HIGHER; } if(this.goalsFor == t.goalsFor) { if(this.name.compareTo(t.name) < 0) { return HIGHER; } } } } return LOWER; }
7
public void setSecondCorner(Rectangle secondCorner) { this.secondCorner = secondCorner; }
0
public void train() { training = true; BHypothesis.training = true; BHypothesis.MARGIN_RATE = 48D; for(int i = 0; i < maxRound; i++) { for(int j = 0; j < sample.size(); j++) { System.err.println((new StringBuilder()).append("Sentence ").append(j).toString()); curSenID = j; BLinTagSample blintagsample = (BLinTagSample)sample.get(j); Vector vector = new Vector(); Vector vector1 = new Vector(); int k = 0; int l = -1; int i1 = 0; initCands(vector1, blintagsample); do { if(vector1.size() <= 0) break; inner++; if(k == l) { if(++i1 >= 50) break; } else { l = k; i1 = 0; } BLinIsland blinisland = selectCand(vector1); boolean flag = checkCand(blinisland); if(flag) { applyCand(vector, vector1, blinisland, blintagsample); k++; } else { vector1.clear(); if(vector.size() == 0) initCands(vector1, blintagsample); else genAllCands(vector1, vector, blintagsample); } } while(true); if(k < blintagsample.words.length) System.err.println((new StringBuilder()).append("LOOP: ").append(j).toString()); } feat.saveWeight((new StringBuilder()).append(proj).append(".").append(i).append(".fea").toString(), inner); } }
9
@SuppressWarnings("InfiniteLoopStatement") private void calculateVerticalScale() { int scale = 1; for (Map.Entry<String, Integer> entry : dataToDraw.entrySet()) { if (entry.getValue() > highestValue) highestValue = entry.getValue(); } while (true) { if (highestValue / noVerticalLines == scale) { this.verticalScale = scale; return; } else { scale += 1; } } }
4
public static pgrid.service.corba.exchange.ExchangeHandle unchecked_narrow (org.omg.CORBA.Object obj) { if (obj == null) return null; else if (obj instanceof pgrid.service.corba.exchange.ExchangeHandle) return (pgrid.service.corba.exchange.ExchangeHandle)obj; else { org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); pgrid.service.corba.exchange._ExchangeHandleStub stub = new pgrid.service.corba.exchange._ExchangeHandleStub (); stub._set_delegate(delegate); return stub; } }
2
@Override protected void draw() { super.draw(); StringRenderer.drawCenteredString("Select your icon:", this.xSize / 2, 42, 26, true, Color.WHITE); int xStart = (xSize / 2) - (34 * 4); boolean hasSelectedSomething = false; for(int i = 0; i < 8; i++) { Monopoly.getInstance().getEngine().bindTexture("/textures/players.png"); Monopoly.getInstance().getEngine().drawTexturedRectangle((xStart + 1) + (i * 34), 120, i % 4 * 32, i / 4 * 32, 32, 32); Monopoly.getInstance().getEngine().bindTexture("/textures/player_border.png"); Monopoly.getInstance().getEngine().drawTexturedRectangle(xStart + i * 34, 119, 0, i == index ? 34 : 0, 34, 34); final int x = MouseLoc.getX() - this.xStart; final int y = MouseLoc.getY() - this.yStart; if (x >= xStart + i * 34 && x <= (xStart + i * 34) + 34 && y >= 119 && y <= 119 + 34) { if (Mouse.isButtonDown(0)) { player.texture = new Point(i % 4 * 32, i / 4 * 32); parent.setPreviousGui(); } this.index = i; hasSelectedSomething = true; } } if (!hasSelectedSomething) { this.index = -1; } }
8
public AndroidSourceSinkManager getSourceSinkManager() { return sourceSinkManager; }
0
int getPitchOffsetInterval(KeyEvent e) { int interval = 0; switch (e.getKeyCode()) { case KeyEvent.VK_UP: case KeyEvent.VK_KP_UP: interval = Pitch.INTERVALS_PER_OCTAVE; break; case KeyEvent.VK_DOWN: case KeyEvent.VK_KP_DOWN: interval = -Pitch.INTERVALS_PER_OCTAVE; break; case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: interval = -1; break; case KeyEvent.VK_RIGHT: case KeyEvent.VK_KP_RIGHT: interval = 1; break; } return interval; }
8
public void start() { if (hiding) { // Control software already running, activate GUI updates: hiding = false; } else { control.start(); } }
1
public static float byte2Float(byte[] b) { int l = b[0]; l &= 0xff; l |= (long) b[1] << 8; l &= 0xffff; l |= (long) b[2] << 16; l &= 0xffffff; l |= (long) b[3] << 24; return Float.intBitsToFloat(l); }
0
private void createPatternsImpl(final AngleUnitFlapPattern seed, final LineType typeToBeAdded, final int indexToAdd, final int additionCount, final int aimedAdditionCount) { recursionCount++; if (acceptablePatternCondition.holds(seed)) { patterns.add(seed.cloneInstance()); } if (additionCount == aimedAdditionCount) { LOGGER.debug(seed); return; } int remainChances = tailIndex + 1 - indexToAdd; int possibleMaxAdditionCount = additionCount + remainChances; if (possibleMaxAdditionCount < aimedAdditionCount) { return; } if (indexToAdd > tailIndex) { return; } for (int i = indexToAdd; i <= tailIndex; i++) { if (!seed.isEmptyAt(i)) { continue; } seed.set(i, typeToBeAdded); if (!pruningCondition.holds(seed)) { createPatternsImpl(seed, typeToBeAdded, i + 1, additionCount + 1, aimedAdditionCount); } seed.set(i, LineType.EMPTY); } }
7
public static void main(String[] args) throws Exception { new World().live(); }
0
static final void handleMessage(String string, String string_37_, int i_38_, String string_39_, String string_40_, int type, int i_42_, String string_43_) { try { anInt10382++; Message message = Class318_Sub2.messages[99]; for (int i_44_ = 99; (i_44_ ^ 0xffffffff) < -1; i_44_--) Class318_Sub2.messages[i_44_] = Class318_Sub2.messages[i_44_ - 1]; if (message == null) message = new Message(type, i_42_, string_39_, string, string_43_, string_40_, i_38_, string_37_); else message.setValues(type, i_42_, string_43_, string, string_40_, -18691, i_38_, string_39_, string_37_); Class318_Sub2.messages[0] = message; Class348_Sub42_Sub3.anInt9501 = LoadingHandler.anInt3918; } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929 (runtimeexception, ("to.K(" + (string != null ? "{...}" : "null") + ',' + (string_37_ != null ? "{...}" : "null") + ',' + i_38_ + ',' + (string_39_ != null ? "{...}" : "null") + ',' + (string_40_ != null ? "{...}" : "null") + ',' + type + ',' + i_42_ + ',' + (string_43_ != null ? "{...}" : "null") + ')')); } }
8
public static ArrayList<Utilisateur> getAllUtilisateur() { Statement stat; ArrayList<Utilisateur> utilisateurs = new ArrayList<>(); try { stat = ConnexionDB.getConnection().createStatement(); stat.executeUpdate("use nemovelo"); ResultSet res = stat.executeQuery("select * from utilisateur"); Utilisateur utilisateur; int id_utilisateur, fk_id_carte, fk_id_velo; String prenom, nom, dateNaissance, adresse, codePostal, ville, carteBancaire, dateValiditeCarteBancaire, rib, iban, dateCreation, login, password; while (res.next()) { id_utilisateur = res.getInt("id_utilisateur"); prenom = res.getString("prenom"); nom = res.getString("nom"); dateNaissance = res.getString("dateNaissance"); adresse = res.getString("adresse"); codePostal = res.getString("codePostal"); ville = res.getString("ville"); carteBancaire = res.getString("carteBancaire"); dateValiditeCarteBancaire = res.getString("dateValiditeCarteBancaire"); rib = res.getString("rib"); iban = res.getString("iban"); dateCreation = res.getString("dateCreation"); login = res.getString("login"); password = res.getString("password"); fk_id_carte = res.getInt("fk_id_carte"); if(res.getInt("fk_id_velo")==0){ fk_id_velo = -1; } else{ fk_id_velo = res.getInt("fk_id_velo"); } utilisateur = new Utilisateur(id_utilisateur, prenom, nom, dateNaissance, adresse, codePostal, ville, carteBancaire, dateValiditeCarteBancaire, rib, iban, dateCreation, login, password, fk_id_carte, fk_id_velo); utilisateurs.add(utilisateur); } } catch (SQLException e) { while (e != null) { System.out.println(e.getErrorCode()); System.out.println(e.getMessage()); System.out.println(e.getSQLState()); e.printStackTrace(); e = e.getNextException(); } } return utilisateurs; }
4
@Override public Ptg getPtgVal() { Object value = getValue(); if( value instanceof Ptg ) { return (Ptg) value; } if( value instanceof Boolean ) { return new PtgBool( (Boolean) value ); } if( value instanceof Integer ) { return new PtgInt( (Integer) value ); } if( value instanceof Number ) { return new PtgNumber( ((Number) value).doubleValue() ); } if( value instanceof String ) { return new PtgStr( (String) value ); } return new PtgErr( PtgErr.ERROR_VALUE ); }
5
@Override public void executeMsg(Environmental host, CMMsg msg) { if((affected instanceof Armor)&&(msg.source()==((Armor)affected).owner())) { if((msg.targetMinor()==CMMsg.TYP_REMOVE) ||(msg.sourceMinor()==CMMsg.TYP_WEAR) ||(msg.sourceMinor()==CMMsg.TYP_WIELD) ||(msg.sourceMinor()==CMMsg.TYP_HOLD) ||(msg.sourceMinor()==CMMsg.TYP_DROP)) checked=false; else { check(msg.source(),(Armor)affected); super.executeMsg(host,msg); } } else super.executeMsg(host,msg); }
7
@SuppressWarnings("unchecked") protected void UnZip() throws PrivilegedActionException { String szZipFilePath; String szExtractPath; String path = (String) AccessController .doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { return Util.getWorkingDirectory() + File.separator; } }); int i; szZipFilePath = path + "bin" + File.separator + "client.zip"; File f = new File(szZipFilePath); if (!f.exists()) { System.out.println("\nNot found: " + szZipFilePath); } if (f.isDirectory()) { System.out.println("\nNot file: " + szZipFilePath); } System.out.println("Enter path to extract files: "); szExtractPath = path; File f1 = new File(szExtractPath); if (!f1.exists()) { System.out.println("\nNot found: " + szExtractPath); } if (!f1.isDirectory()) { System.out.println("\nNot directory: " + szExtractPath); } ZipFile zf; @SuppressWarnings("rawtypes") Vector zipEntries = new Vector(); try { zf = new ZipFile(szZipFilePath); @SuppressWarnings("rawtypes") Enumeration en = zf.entries(); while (en.hasMoreElements()) { zipEntries.addElement((ZipEntry) en.nextElement()); } for (i = 0; i < zipEntries.size(); i++) { ZipEntry ze = (ZipEntry) zipEntries.elementAt(i); extractFromZip(szZipFilePath, szExtractPath, ze.getName(), zf, ze); } zf.close(); System.out.println("Done!"); } catch (Exception ex) { System.out.println(ex.toString()); } f.delete(); }
7
protected void updateText( final BaseUI UI, Text headerText, Text detailText ) { if (selected == null) return ; headerText.setText(selected.fullName()) ; headerText.append("\n") ; final String cats[] = selected.infoCategories() ; if (cats != null) { for (int i = 0 ; i < cats.length ; i++) { final int index = i ; final boolean CC = categoryID == i ; headerText.append(new Text.Clickable() { public String fullName() { return ""+cats[index]+" " ; } public void whenClicked() { setCategory(index) ; } }, CC ? Colour.GREEN : Text.LINK_COLOUR) ; } } if (previous != null) { headerText.append(new Description.Link("UP") { public void whenClicked() { UI.selection.pushSelection(previous, false) ; } }) ; } detailText.setText("") ; selected.writeInformation(detailText, categoryID, UI) ; }
5
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Corner other = (Corner) obj; if (e1 == null) { if (other.e1 != null) return false; } else if (!e1.equals(other.e1)) return false; if (e2 == null) { if (other.e2 != null) return false; } else if (!e2.equals(other.e2)) return false; return true; }
9
private List getPositionsStop(Traject traject) throws FileNotFoundException, UnsupportedEncodingException, IOException { FileInputStream stream = new FileInputStream("json/stops.csv"); CSVReader reader = new CSVReader(new InputStreamReader(stream, "UTF-8")); String[] nextLine; List stopArray = new ArrayList<ArrayList>(); int marcheCount = 0; for (int i = 0; i < traject.getEtapes().size(); i++) { if (i + 2 < traject.getEtapes().size()) { if (!((Etapes) traject.getEtapes().toArray()[i + 1]).isMarche()) { List stopsByPoints = new ArrayList<ArrayList>(); stopsByPoints.add(new ArrayList<String>()); stopsByPoints.add(new ArrayList<String>()); stopArray.add(i - marcheCount, stopsByPoints); } else { marcheCount++; } } } while ((nextLine = reader.readNext()) != null) { marcheCount = 0; for (int i = 0; i < traject.getEtapes().size(); i++) { if (i + 2 < traject.getEtapes().size()) { Etapes etape1 = (Etapes) traject.getEtapes().toArray()[i]; Etapes etape2 = (Etapes) traject.getEtapes().toArray()[i + 1]; if (!etape2.isMarche()) { if (nextLine[1].equals(etape1.getArretStop().getLibelle())) { List stopStartPositionsArray = (ArrayList) stopArray.get(i - marcheCount); List stopStartPositions = (ArrayList) stopStartPositionsArray.get(0); stopStartPositions.add(nextLine[3] + "" + nextLine[4]); } else if (nextLine[1].equals(etape2.getArretStop().getLibelle())) { List stopEndPositionsArray = (ArrayList) stopArray.get(i - marcheCount); List stopEndPositions = (ArrayList) stopEndPositionsArray.get(1); stopEndPositions.add(nextLine[3] + "" + nextLine[4]); } } else { marcheCount++; } } } } return stopArray; }
9
@Override public void keyReleased(KeyEvent e) { boolean unique=true; if (view.getNameTextField().getText().equals("")){ model.setWarning("Attribute name is empty"); view.getOkButton().setEnabled(false); } else { for (int i=0; i<view.getModel().getObjectUmlAtIndex(view.getIndex()).attributListSize(); i++){ if (view.getModel().getObjectUmlAtIndex(view.getIndex()).getAttributeAt(i).getName().equals(view.getNameTextField().getText())){ unique=false; } } if (unique){ model.setWarning(""); view.getOkButton().setEnabled(true); } else { model.setWarning("This Attribute already exist"); view.getOkButton().setEnabled(false); } if(view.getNameTextField().getText().charAt(0)>='A'&&view.getNameTextField().getText().charAt(0)<='Z'){ model.setWarning("Attribute Name begin with a lower case"); } } }
6
static void input(double[][] matrix){ for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix[i].length; j++){ matrix[i][j] = scan.nextDouble(); } } }
2
public String multiply(String a, String b) { // Start typing your Java solution below // DO NOT write main() function if ("0".equals(b) || "0".equals(a)) // 先排除,不然后面排除更麻烦 return "0"; int m = a.length(); int n = b.length(); if (m < n) { String c = a; int p = m; a = b; b = c; m = n; n = p; } int cnt = 0; String res = "0"; while (n > 0) { String tmpRes = subTask(a, b.substring(Math.max(0, n - 4), n)); n -= 4; for (int i = 0; i < cnt; i++) tmpRes += "0000"; cnt++; res = sumTask(tmpRes, res); } return res; }
5
public static JsonElement fetchJson(String username, String password, String urlEndpoint) throws IOException { URL url = new URL(urlEndpoint); URLConnection urlConnection = url.openConnection(); if (username != null && password != null) { String authString = username + ":" + password; byte[] encodedBasicAuth = Base64.encodeBase64(authString.getBytes()); String encodedBasicAuthStr = new String(encodedBasicAuth); urlConnection.setRequestProperty("Authorization", "Basic " + encodedBasicAuthStr); } urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.connect(); JsonReader reader = new JsonReader(new InputStreamReader(urlConnection.getInputStream())); JsonParser parser = new JsonParser(); return parser.parse(reader); }
2
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Producto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Producto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Producto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Producto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Producto().setVisible(true); } }); }
6
private boolean checkQuantity(Item item, Order cOrder, int quantity, boolean checkCart) throws Exception { ItemStack is = cOrder.getItem(item.getId()); int checkQt = quantity; if (is != null && checkCart) { checkQt += is.quantity; // we have to check quantity summing items already in cart } if (checkQt <= 0) { return false; } else if (checkQt == 1 || !(item instanceof QAvailability)) { if (!item.isAvailable()) { throw new Exception("This item is not available!"); } } else { if (!((QAvailability) item).isAvailable(checkQt)) { throw new Exception("This quantity is not available!"); } } return true; }
7
public boolean opEquals(Operator o) { return (o instanceof BinaryOperator) && o.operatorIndex == operatorIndex; }
1
@Override public void setSourceItem( DefaultBox<?> sourceItem ) { if( sourceItem != null ) { comment = (DefaultCommentBox) sourceItem; comment.setConnection( this ); } else { comment = null; } super.setSourceItem( sourceItem ); }
2
private double shade() { Vector poi = i.poi; Ray ray; LinkedBody lb; Body b; int numLights = lights.length; double distance = -1.0, brightness = 0.0, lambertian = 0.0, brightnessPerLight = 1.0 / numLights; boolean hitSomething; for (Vector L : lights) { lambertian = L.dot(i.normal); if (lambertian > 0.0) { hitSomething = false; ray = new Ray(i.poi, L); lb = bodies; while (lb != null) { b = lb.b(); lb = lb.next(); distance = b.intersection(ray); if (distance > 0.0 && (b != i.body || distance > 0.00001)) { lb = null; hitSomething = true; } } if (!hitSomething) { brightness += brightnessPerLight * lambertian; } } } brightness = Math.max(brightness, baseBrightness); return Math.min(1.0, brightness); }
7
private String map(int year, int month, int day) throws NodeMeaningKeyErrorException { System.err.println(year + "/" + month + "/" + day); year -= baseYear; if (year < minYear || year > maxYear) { throw new NodeMeaningKeyErrorException(); } if (month < minMonth || month > maxMonth) { throw new NodeMeaningKeyErrorException(); } if (day < minDay || day > maxDay) { throw new NodeMeaningKeyErrorException(); } year -= minYear; month -= minMonth; day -= minDay; int monthLength = maxMonth - minMonth + 1; int dayLength = maxDay - minDay + 1; int value = year * monthLength * dayLength + month * dayLength + day; return String.valueOf(value); }
6
public boolean isItemConnected(int xx, int yy) { try { if(enabledGrid[xx-1][yy]) return true; } catch (Exception e) {} try { if(enabledGrid[xx+1][yy]) return true; } catch (Exception e) {} try { if(enabledGrid[xx][yy+1]) return true; } catch (Exception e) {} try { if(enabledGrid[xx][yy-1]) return true; } catch (Exception e) {} return false; }
8