method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
86d1ff03-edb3-47b8-b3f0-5c14bcd2d065
6
public boolean isRespawnSafe(ArrayList<SpaceJunk> spaceJunk, ArrayList<Planet> planets) { double x, y, h; boolean ret = true; for (int i = 0; i < spaceJunk.size(); i++) { SpaceJunk sj = spaceJunk.get(i); x = sj.xPosition - Game.SPACE_WIDTH / 2; y = sj.yPosition - Game.SPACE_HEIGHT / 2; h = Math.sqrt(x * x + y * y); if (h < 600) { if (h > 0) { double normX = x / h; double normY = y / h; sj.xVelocity += normX * 3; sj.yVelocity += normX * 3; } ret = false; } } for (int i = 0; i < planets.size(); i++) { Planet p = planets.get(i); x = p.xPosition - Game.SPACE_WIDTH / 2; y = p.yPosition - Game.SPACE_HEIGHT / 2; h = Math.sqrt(x * x + y * y); if (h < 700 + p.diameter/2) { if (h > 0) { double normX = x / h; double normY = y / h; p.xVelocity += normX * 3; p.yVelocity += normX * 3; } ret = false; } } return ret; }
f83d42b3-2f6c-402f-a872-7b1c4f173915
4
public byte[] getPackedCode(int bit) { assert ((bit == 0) || (bit == 1)) : "getPackedCode: input isn't a bit!"; byte[] packed_code = new byte[NBYTESG + 1]; int i; if (bit == 0) { packed_code[0] = (byte) (perm + 1); // +1 to escape the leading 0 problem for (i = 0; i < NBYTESG; i++) packed_code[i + 1] = code0[i]; } else { packed_code[0] = (byte) ((perm ^ 1) + 1); // +1 to escape the leading 0 problem for (i = 0; i < NBYTESG; i++) packed_code[i + 1] = code1[i]; } return packed_code; }
b7a490f0-eb4a-42cc-b744-ca1666a9f76e
0
public RecordList getRecordList() { return recordList; }
456c2d71-887b-45a1-a720-3382ceb00ca1
8
public static void main( String[] args ) { // Create game window... JFrame app = new JFrame(); app.setIgnoreRepaint( true ); app.setUndecorated( true ); // Add ESC listener to quit... app.addKeyListener( new KeyAdapter() { public void keyPressed( KeyEvent e ) { if( e.getKeyCode() == KeyEvent.VK_ESCAPE ) running = false; } }); // Get graphics configuration... GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gd.getDefaultConfiguration(); // Change to full screen gd.setFullScreenWindow( app ); if( gd.isDisplayChangeSupported() ) { gd.setDisplayMode( new DisplayMode( 640, 480, 32, DisplayMode.REFRESH_RATE_UNKNOWN ) ); } // Create BackBuffer... app.createBufferStrategy( 2 ); BufferStrategy buffer = app.getBufferStrategy(); // Create off-screen drawing surface BufferedImage bi = gc.createCompatibleImage( 640, 480 ); // Objects needed for rendering... Graphics graphics = null; Graphics2D g2d = null; Color background = Color.BLACK; Random rand = new Random(); // Variables for counting frames per seconds int fps = 0; int frames = 0; long totalTime = 0; long curTime = System.currentTimeMillis(); long lastTime = curTime; running = true; while( running ) { try { // count Frames per second... lastTime = curTime; curTime = System.currentTimeMillis(); totalTime += curTime - lastTime; if( totalTime > 1000 ) { totalTime -= 1000; fps = frames; frames = 0; } ++frames; // clear back buffer... g2d = bi.createGraphics(); g2d.setColor( background ); g2d.fillRect( 0, 0, 639, 479 ); // draw some rectangles... for( int i = 0; i < 20; ++i ) { int r = rand.nextInt(256); int g = rand.nextInt(256); int b = rand.nextInt(256); g2d.setColor( new Color(r,g,b) ); int x = rand.nextInt( 640/2 ); int y = rand.nextInt( 480/2 ); int w = rand.nextInt( 640/2 ); int h = rand.nextInt( 480/2 ); g2d.fillRect( x, y, w, h ); } // display frames per second... g2d.setFont( new Font( "Courier New", Font.PLAIN, 12 ) ); g2d.setColor( Color.GREEN ); g2d.drawString( String.format( "FPS: %s", fps ), 20, 20 ); // Blit image and flip... graphics = buffer.getDrawGraphics(); graphics.drawImage( bi, 0, 0, null ); if( !buffer.contentsLost() ) buffer.show(); } finally { // release resources if( graphics != null ) graphics.dispose(); if( g2d != null ) g2d.dispose(); } } gd.setFullScreenWindow( null ); System.exit(0); }
f3c810cb-0a68-460d-93ff-43d308f8a72d
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FinderModeConfig other = (FinderModeConfig) obj; if (mode != other.mode) return false; if (radiusSquared != other.radiusSquared) return false; if (mode == FinderMode.CYLINDER && height != other.height) return false; return true; }
33f05d6d-a6b3-47fc-82d0-c5c82ae36656
7
public void add(Component comp, Object constraints) { super.add(comp, constraints); componentsByContraints.put(constraints, comp); contraintsByComponents.put(comp, constraints); if(comp instanceof ToolBarPanel) { ToolBarPanel panel = (ToolBarPanel) comp; if(constraints.equals(BorderLayout.EAST) || constraints.equals(BorderLayout.WEST)) { panel.setOrientation(SwingConstants.VERTICAL); } // install the UI border if(constraints.equals(BorderLayout.NORTH)) { panel.setBorder(UIManager.getBorder("ToolBarPanel.topBorder")); } else if(constraints.equals(BorderLayout.WEST)) { panel.setBorder(UIManager.getBorder("ToolBarPanel.leftBorder")); } else if(constraints.equals(BorderLayout.EAST)) { panel.setBorder(UIManager.getBorder("ToolBarPanel.rightBorder")); } else if(constraints.equals(BorderLayout.SOUTH)) { panel.setBorder(UIManager.getBorder("ToolBarPanel.bottomBorder")); } } }
0902bfdd-f8ab-4df0-b95e-93febe5236ce
3
public void update(float tslf) { switch (gamestate) { case 0: menu.update(tslf); break; case 1: world.update(tslf); if(Keyboard.isKeyPressed(KeyEvent.VK_ESCAPE)) gamestate = 0; break; default: break; } world.update(tslf); }
0c5728cb-75b0-4708-81fb-a87f804d1f00
5
private Operator findI(O O, ArrayList<I> Iids){ for(I I:Iids){ if(I.id.equals(O.id)){ return I; } } Operator curr = O.next; while(curr != null){ if(curr.type == Operator.Type.I && O.id.equals(curr.id)){ return curr; } curr = curr.next; } return null; }
bb897ce5-d5e5-4a3f-8d1e-bfd5503b45f5
0
@Override public int hashCode() { long longBits = Double.doubleToLongBits(this.value); return (int)(longBits ^ longBits >>>32); }
e504e741-e6f5-4d7b-9775-1bc75f32a1b4
1
public int calcTotalAmount() { totalAmount = 0; for (Account account : accounts) { totalAmount += account.getAmount(); } return totalAmount; }
ac26e0af-2693-4255-b968-7d28adff35b5
5
private void prepareMatrix() { for (int i = 0; i < K + 1; i++) { M[i][0] = 1l; M[i][i] = 1l; for (int j = 1; j < i; j++) { M[i][j] = M[i - 1][j] + M[i - 1][j - 1]; if (M[i][j] >= mod) M[i][j] -= mod; } } for (int j = 0; j < K + 1; j++) { M[K + 1][j] = M[K][j]; } M[K + 1][K + 1] = 1l; powersOfM[0] = M; for (int i = 1; i < 50; i++) { powersOfM[i][0][0] = -1; //denotes M ^ (2 ^ i) is not yet computed } tmp = new long[K + 2][K + 2]; }
9ac2b61e-1246-4a3d-9b17-b1aa86ad6650
3
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String userName = "", password = ""; userName = request.getParameter("userName"); password = request.getParameter("securityKey"); if (userName.equals("") || password.equals("")) { response.sendRedirect("/websocchatroom/error?errorCode=UPNULL"); //out.println("Please don't fool our Server :-) !"); } else { signinDAO signinObject = new signinDAO(userName, password); try { String pass = signinObject.forgotPass(); Handler handler = new Handler(); out.println("Your Password is: " + pass); // getServletContext().getRequestDispatcher("/home.jsp").forward(request,response); } catch (Exception e) { System.out.println("Error in signin.java unable to communicate with signinDAO" + e); response.sendRedirect("/websocchatroom/error?errorCode=LOGINERR"); // out.println("Error while login, please try again !"); } } }
273e9345-6899-43e9-b44e-9a9c99977b8a
8
@SuppressWarnings("unchecked") public static <K, V> Map<K, V> getMap(List<MapHelper> list, Class<K> classK, Class<V> classV) { Map<K, V> map = new HashMap<K, V>(); if (list != null) { for (MapHelper h : list) { Object en = h.getValue(); if (en instanceof String) { String svalue = (String) en; try { Method m = classV.getDeclaredMethod("valueOf", String.class); en = m.invoke(classV, svalue); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } map.put((K) h.getKey(), (V) en); } } } return map; }
4a2cb236-ff47-4c39-85de-4dbb8aac373b
1
public boolean isLaying() { Layered layered = gob().getattr(Layered.class); if (layered != null) { return layered.containsLayerName("gfx/borka/body/dead/"); } return false; }
1f6128ac-c48f-4dd2-9617-da5c0aac7146
8
public Set<Map.Entry<Double,Double>> entrySet() { return new AbstractSet<Map.Entry<Double,Double>>() { public int size() { return _map.size(); } public boolean isEmpty() { return TDoubleDoubleMapDecorator.this.isEmpty(); } public boolean contains( Object o ) { if (o instanceof Map.Entry) { Object k = ( ( Map.Entry ) o ).getKey(); Object v = ( ( Map.Entry ) o ).getValue(); return TDoubleDoubleMapDecorator.this.containsKey(k) && TDoubleDoubleMapDecorator.this.get(k).equals(v); } else { return false; } } public Iterator<Map.Entry<Double,Double>> iterator() { return new Iterator<Map.Entry<Double,Double>>() { private final TDoubleDoubleIterator it = _map.iterator(); public Map.Entry<Double,Double> next() { it.advance(); double ik = it.key(); final Double key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik ); double iv = it.value(); final Double v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv ); return new Map.Entry<Double,Double>() { private Double val = v; public boolean equals( Object o ) { return o instanceof Map.Entry && ( ( Map.Entry ) o ).getKey().equals(key) && ( ( Map.Entry ) o ).getValue().equals(val); } public Double getKey() { return key; } public Double getValue() { return val; } public int hashCode() { return key.hashCode() + val.hashCode(); } public Double setValue( Double value ) { val = value; return put( key, value ); } }; } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } public boolean add( Map.Entry<Double,Double> o ) { throw new UnsupportedOperationException(); } public boolean remove( Object o ) { boolean modified = false; if ( contains( o ) ) { //noinspection unchecked Double key = ( ( Map.Entry<Double,Double> ) o ).getKey(); _map.remove( unwrapKey( key ) ); modified = true; } return modified; } public boolean addAll( Collection<? extends Map.Entry<Double, Double>> c ) { throw new UnsupportedOperationException(); } public void clear() { TDoubleDoubleMapDecorator.this.clear(); } }; }
15947ffc-4a4c-4705-9ffe-83abd2451197
9
public NewCharNameCheckResult finishNameCheck(String login, String ipAddress) { if((CMProps.getIntVar(CMProps.Int.MUDTHEME)==0) ||((CMSecurity.isDisabled(CMSecurity.DisFlag.LOGINS)) &&(!CMProps.isOnWhiteList(CMProps.WhiteList.LOGINS, login)) &&(!CMProps.isOnWhiteList(CMProps.WhiteList.LOGINS, ipAddress)))) return NewCharNameCheckResult.NO_NEW_LOGINS; else if((CMProps.getIntVar(CMProps.Int.MAXNEWPERIP)>0) &&(CMProps.getCountNewUserByIP(ipAddress)>=CMProps.getIntVar(CMProps.Int.MAXNEWPERIP)) &&(!CMSecurity.isDisabled(CMSecurity.DisFlag.MAXNEWPERIP)) &&(!CMProps.isOnWhiteList(CMProps.WhiteList.NEWPLAYERS, login)) &&(!CMProps.isOnWhiteList(CMProps.WhiteList.NEWPLAYERS, ipAddress))) return NewCharNameCheckResult.CREATE_LIMIT_REACHED; return NewCharNameCheckResult.OK; }
f053b49f-18d6-4112-8fe6-949ab228a422
2
public Collection<File> getClassPath(OperatingSystem os, File base) { Collection<Library> libraries = getRelevantLibraries(); Collection result = new ArrayList(); for (Library library : libraries) { if (library.getNatives() == null) { result.add(new File(base, "launcher/" + library.getArtifactPath())); } } result.add(new File(base, "versions/" + getId() + "/" + getId() + ".jar")); return result; }
8ce3a2d2-5646-43dd-904d-c406f1d093bd
5
public static Object retCheck(Object obj) throws NotSerializableException { Object ret = obj; /* Check if return object is serializable, if the return object is null, * we should still pass it back, no matter a non-return method or the * return value is null */ if ( (obj != null) && !(obj instanceof Serializable) ) { throw new NotSerializableException("Non-serializable parameter"); } if ((obj instanceof Remote440) && !(obj instanceof Stub440)) { RemoteObjectRef ror = Naming.getROR((Remote440)obj); if (ror != null) { ret = ror.localise(); } } return ret; }
9c8c2e27-d84c-4218-afbb-c2830ea74733
0
public Blog getBlogDetail(long pBlogId) { return (Blog) this.blogModelDao.findByPrimaryKey(pBlogId); }
6a2f0e14-23b7-46c3-8565-04a6c7807492
3
public CourseFilterFrame(CourseModel model) { super("Filter", model); Dimension dim = new Dimension(200, 200); this.setMinimumSize(dim); this.setSize(dim); model.addListener(this); // Make a root node initTree(); treeModel = new FilterTreeModel(root); tree = new JTree(treeModel) { public boolean isPathEditable(TreePath path) { Object comp = path.getLastPathComponent(); if (getFilterOut(comp) != null) return true; Object option = getDescOut(comp); if (option != null) { CourseFilter filter = getFilterOut(((DefaultMutableTreeNode) comp) .getParent()); if (filter != null) { return true; } } return false; } }; tree.setCellRenderer(new FilterTreeRenderer()); tree.setCellEditor(new FilterCellEditor()); tree.setEditable(true); tree.setRootVisible(true); // otherwise checkboxes are not visible in // Win tree.setRowHeight(-1); this.add(new JScrollPane(tree)); }
b5414eb7-f425-4fda-a7e4-d788a6cdae3d
2
public void setDefaultColor(Color c) { if (c == null) c = Color.black; if (! c.equals(defaultColor)) { defaultColor = c; setBackground(c); forceRedraw(); } }
b7177a3d-d9bf-4453-a487-4b1d569a0e7f
0
public static void main(String[] args) { Sleeper sleepy = new Sleeper("Sleepy", 1500), grumpy = new Sleeper("Grumpy", 1500); Joiner dopey = new Joiner("Dopey", sleepy), doc = new Joiner("Doc", grumpy); grumpy.interrupt(); }
679d5e76-153e-42c6-bd8f-a657fdc2173a
4
public static SectionState state(FragKind kind ) { switch ( kind ) { case merged: return SectionState.merged; case almost: return SectionState.almost; default: case inserted: case aligned: return disjoint; } }
a996eaca-1f2a-4540-b329-3a10ec47b383
3
public EntityFactionsList() { setTitle("Factions List"); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setBounds(100, 100, 325, 500); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(new BorderLayout(0, 0)); { JScrollPane scrollPane = new JScrollPane(); contentPanel.add(scrollPane, BorderLayout.CENTER); { list = new JList<String>(); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { list.setSelectedIndex(list.locationToIndex(e.getPoint())); if(e.getClickCount() == 2) { makeSelection(); } else if(e.getButton() == MouseEvent.BUTTON3 && list.getSelectedIndex() != -1) { addPopup(e.getX(), e.getY()); } } }); list.setModel(buildList()); scrollPane.setViewportView(list); } } { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton btnNew = new JButton("New"); btnNew.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { @SuppressWarnings("unused") NewFactionEditor factionEditor = new NewFactionEditor(); list.setModel(buildList()); } }); buttonPane.add(btnNew); } { JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { makeSelection(); } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } setModalityType(ModalityType.APPLICATION_MODAL); setVisible(true); }
5f8cdeb2-e59e-48a4-a2d7-0cf2298c20b7
3
private List<String> getAllJCheckBoxValue(JFrame ct){ List<String> list=new ArrayList<String>(); Component[] cs = ct.getContentPane().getComponents();//遍历内容控制面版 for(Component item : cs){ if(item instanceof JCheckBox){ if(((JCheckBox) item).isSelected()){ list.add(((JCheckBox) item).getText()); } } } return list; }
92be3dff-0485-4994-8233-bcb87f9028f4
0
public int getMaxArena() { return config.getInt("CommonOption.MaxArena",5); }
e006010c-8e54-4f86-b2cc-b6aa85cc59c3
8
public void render(Bitmap b) { if(dir == 0) { ImageManager.renderFromImage(entityType, b, (int)x, (int)y, 0, 16, ((animation_frame == 0) ? 1 : 0)); } else if (dir == 1) { ImageManager.renderFromImage(entityType, b, (int)x, (int)y, 1, 16, ((animation_frame == 0) ? 1 : 0)); } else if (dir == 2) { ImageManager.renderFromImage(entityType, b, (int)x, (int)y, 2 + ((animation_frame == 0) ? 1 : 0), 16); } else if (dir == 3) { ImageManager.renderFromImage(entityType, b, (int)x, (int)y, 2 + ((animation_frame == 0) ? 1 : 0), 16, 1); } }
7baa7c34-1805-4e2e-a9b2-c95a628aec54
0
public int getIdCliente() { return idCliente; }
b380f291-81ea-4e6f-ac96-a43a4c82af87
0
public int getPage() { return page; }
3169d322-710e-4eef-ba0f-c3e1ba3c18a2
9
public void geraMatrizScors(ArrayList<FieldCandidate> shortRecord, ArrayList<ArrayList<FieldCandidate>> rowsCadidates, int idealNumColumn) { ArrayList<ArrayList<FieldCandidate>> correctColumns = new ArrayList<ArrayList<FieldCandidate>>(); Score score = Score.getInstance(); Line line = new Line(); Value value = new Value(); Table table = new Table(); double equalsFieldScore = 0; double scoreBasedExpressions = 0; for (int i = 0; i < rowsCadidates.size(); i++) { if (rowsCadidates.get(i).size() == idealNumColumn) { correctColumns.add(rowsCadidates.get(i)); } } for (int i = 0; i < shortRecord.size(); i++) { boolean mustAdd = false; for (int j = 0; j < idealNumColumn; j++) { if (correctColumns.get(j).size() == idealNumColumn) { mustAdd = true; double occurrencesSum = 0; int numberLinesCorrectColumns = 0; numberLinesCorrectColumns = correctColumns.size(); for (int t = 0; t < correctColumns.size(); t++) { if (correctColumns.get(j).size() == idealNumColumn) { occurrencesSum += funcaoCompara(shortRecord.get(i).getField(), correctColumns.get(t).get(j).getField()); value.setValor(shortRecord.get(i).getField()); } } equalsFieldScore = computePercentage(occurrencesSum, numberLinesCorrectColumns); scoreBasedExpressions = scoreBasedExpressions(correctColumns, idealNumColumn, shortRecord.get(i).getField()); /** * Verificar a construção da list de scores na classe Line! */ score.setScore(equalsFieldScore); line.addScore(score); //Add o Score que acabou de ser definido. System.out.println(">" + line.getScores()); if (scoreBasedExpressions != Double.MAX_VALUE) { score.setScore(scoreBasedExpressions); line.addScore(score); System.out.println(line.getScores()); } else; } } if (mustAdd) { value.addLine(line); // System.out.println(line.getScores()); // System.out.println(value.getLines()); table.addValue(value); // System.out.println(table.getValuesScores()); } } // System.out.println(table.getValuesScores()); System.out.println("------"); // printaMatriz(matrizScors); }
e1d2258e-4e55-4a72-b70d-7b9b65c7178c
3
public void run() { for (JButton b:controllers) b.setEnabled(false); while (year<endYear) tick(); for (JButton b:controllers) b.setEnabled(true); System.out.println("History through "+year); }
9a151eab-2348-4bb1-b861-8299752d3eeb
1
public static void showTokens(List<Token> tokens) { if(janelaLexico == null) janelaLexico = new JanelaAnaliseLexica(tokens); else janelaLexico.refresh(tokens); janelaLexico.setVisible(true); }
3dfdeb03-0d2e-4657-bc5f-27b59787bc78
8
private void initProfiles() throws IOException { if (profilespath.isEmpty()) return; profiles = Profiles.read(new File(profilespath)); // Group the packages to be documented by the lowest profile (if any) // in which each appears Map<Profile, List<PackageDoc>> interimResults = new EnumMap<Profile, List<PackageDoc>>(Profile.class); for (Profile p: Profile.values()) interimResults.put(p, new ArrayList<PackageDoc>()); for (PackageDoc pkg: packages) { if (nodeprecated && Util.isDeprecated(pkg)) { continue; } // the getProfile method takes a type name, not a package name, // but isn't particularly fussy about the simple name -- so just use * int i = profiles.getProfile(pkg.name().replace(".", "/") + "/*"); Profile p = Profile.lookup(i); if (p != null) { List<PackageDoc> pkgs = interimResults.get(p); pkgs.add(pkg); } } // Build the profilePackages structure used by the doclet profilePackages = new HashMap<String,PackageDoc[]>(); List<PackageDoc> prev = Collections.<PackageDoc>emptyList(); int size; for (Map.Entry<Profile,List<PackageDoc>> e: interimResults.entrySet()) { Profile p = e.getKey(); List<PackageDoc> pkgs = e.getValue(); pkgs.addAll(prev); // each profile contains all lower profiles Collections.sort(pkgs); size = pkgs.size(); // For a profile, if there are no packages to be documented, do not add // it to profilePackages map. if (size > 0) profilePackages.put(p.name, pkgs.toArray(new PackageDoc[pkgs.size()])); prev = pkgs; } // Generate profiles documentation if any profile contains any // of the packages to be documented. showProfiles = !prev.isEmpty(); }
91a985a4-9092-4760-ad25-7267069262f2
1
public DefaultComboBoxModel<String> buildFrameBox() { DefaultComboBoxModel<String> frameBoxModel = new DefaultComboBoxModel<String>(); hitboxes = new Rectangle[maxDir * maxFrame]; for(int x = 0; x<hitboxes.length; x++) { frameBoxModel.addElement("Rect " + (x / maxDir) + ", " + (x % maxFrame)); hitboxes[x] = new Rectangle(0,0,0,0); } return frameBoxModel; }
a25a323d-f908-4b78-9bb0-c1f78cc985b6
0
public boolean removeEntry(String variable, String lookahead, String expansion) { int[] r = getLocation(variable, lookahead); boolean removed = entries[r[0]][r[1]].remove(expansion); fireTableCellUpdated(r[0], r[1] + 1); return removed; }
c659517b-085f-4e96-a126-300d4f4f140c
6
public static String makeTitle(HashMap<String,String> mp3, String template){ String x = template; x = x.replaceFirst("%Track%", mp3.get("TrackNum")!=null ? mp3.get("TrackNum") : "NA"); x = x.replaceFirst("%Artist%", mp3.get("ArtistName")!=null||!mp3.get("ArtistName").isEmpty() ? mp3.get("ArtistName"):""); x = x.replaceFirst("%Title%", mp3.get("SongName")!=null?mp3.get("SongName"):mp3.get("Name") ); x = x.replaceFirst("%Album%",mp3.get("AlbumName")!=null?mp3.get("AlbumName"):""); x = x.replaceFirst("%Year%", mp3.get("Year")!=null?mp3.get("Year"):""); return x; }
a8453fec-0b6d-4973-83a4-d1bdc1ddfd35
1
@RequestMapping(value = "/new", method = RequestMethod.POST) public String newPostItem(@ModelAttribute("contentForm") ContentForm contentForm, BindingResult result, HttpSession session) { if (!result.hasErrors()) { Content content = new Content(); content.setQuestion(contentForm.getQuestion()); content.setAnswer(contentForm.getAnswer()); contentService.addContent(content); session.setAttribute("contentForm", contentForm); } return "redirect:/questionnaire/list"; }
d8c915f9-0170-4230-9eb9-763c826eb4c6
7
@Override public boolean equals(Object obj) { if(!super.equals(obj)) { return false; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final SpdyFrameSynStream other = (SpdyFrameSynStream) obj; if (this.associatedToStreamId != other.associatedToStreamId) { return false; } if (this.priority != other.priority) { return false; } if (this.slot != other.slot) { return false; } if (!Objects.equals(this.nameValueBlock, other.nameValueBlock)) { return false; } return true; }
02b68b19-3cc4-487b-b835-e04f81f056c3
6
public void weaponCardFromInt(int inputWeapon) { switch (inputWeapon) { case 1: this.weapon =(Weapons.candlestick); break; case 2: this.weapon =(Weapons.crowbar); break; case 3: this.weapon =(Weapons.dagger); break; case 4: this.weapon =(Weapons.gun); break; case 5: this.weapon =(Weapons.rope); break; case 6:this.weapon =(Weapons.wrench); break; default:this.weapon=null; } }
3e1cbd18-2bf5-4326-b016-52fc7730aedd
9
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("rawtypes") Pair other = (Pair) obj; if (first == null) { if (other.first != null) { return false; } } else if (!first.equals(other.first)) { return false; } if (second == null) { if (other.second != null) { return false; } } else if (!second.equals(other.second)) { return false; } return true; }
39c4e546-837a-47c8-9fdd-8a43dabfb661
8
private Component cycle(Component currentComponent, int delta) { int index = -1; loop : for (int i = 0; i < m_Components.length; i++) { Component component = m_Components[i]; for (Component c = currentComponent; c != null; c = c.getParent()) { if (component == c) { index = i; break loop; } } } // try to find enabled component in "delta" direction int initialIndex = index; while (true) { int newIndex = indexCycle(index, delta); if (newIndex == initialIndex) { break; } index = newIndex; // Component component = m_Components[newIndex]; if (component.isEnabled() && component.isVisible() && component.isFocusable()) { return component; } } // not found return currentComponent; }
10f6d842-0b78-4e73-ab47-a041b31b08c1
3
public void disposeFontResources() { Set<Reference> test = refs.keySet(); Object tmp; for (Reference ref:test) { tmp = refs.get(ref); if (tmp instanceof Font || tmp instanceof FontDescriptor) { refs.remove(ref); } } }
c2759dcd-0ed2-45ae-bd05-b33e51ebd82d
0
public BounceFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); setTitle("BounceThread"); comp = new BallComponent(); add(comp, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(); addButton(buttonPanel, "Start", new ActionListener() { public void actionPerformed(ActionEvent event) { addBall(); } }); addButton(buttonPanel, "Close", new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); add(buttonPanel, BorderLayout.SOUTH); }
33017979-b5ed-40e1-9304-bb1d0789ffe6
4
@Override public V remove(Object key) { int temp = index((K) key); Entry<K, V> list = table[temp]; if (list != null) { if (list.getKey().equals((K) key)) { table[temp] = list.next; list.next = null; return list.getValue(); } else { while (list.next != null) { if (list.next.getKey().equals((K) key)) { V v = list.next.getValue(); list.next = list.next.next; return v; } list = list.next; } } } return null; }
f2f88d16-e908-44cb-ad45-f6ba2b121ce7
3
@Override public List<Action> process(Board board) { List<Action> actions = new ArrayList<Action>(); for (int w = 0; w < board.w; w++) for (int h = 0; h < board.h; h++) if (board.cells[w][h]) actions.add(new PaintAction(w,h,0)); return actions; }
0d0c3b71-5cc0-4e14-941a-4530a20278ab
0
@Override public String toString() { return "isPrivate()"; }
b5fc0ce5-c713-429b-8501-3e1a8b97005e
0
public String getDoctorID(){ return doctorID; }
0ba8101c-e327-4e49-b5be-65656b0b95db
3
private void animate() { new Thread(new Runnable() { public void run() { while(m_panel.getAnimationThread().isAlive()){ } m_panel.updatePieces(getGame().getPieces()); if (!getGame().boardIsFull()) { if (m_panel.getCurrentPiece().getPieceColour() == ConnectFourPanel.YELLOW_PIECE) { m_panel.setCurrentPiece(new ConnectFourPiece( ConnectFourPanel .RED_PIECE)); } else { m_panel.setCurrentPiece(new ConnectFourPiece( ConnectFourPanel .YELLOW_PIECE)); } } m_panel.refreshDisplay(); } }).start(); }
fc575bbe-d4dc-4634-b514-a005de0567da
2
public void testPropertyCompareToHour() { Partial test1 = new Partial(TYPES, VALUES1); Partial test2 = new Partial(TYPES, VALUES2); assertEquals(true, test1.property(DateTimeFieldType.hourOfDay()).compareTo(test2) < 0); assertEquals(true, test2.property(DateTimeFieldType.hourOfDay()).compareTo(test1) > 0); assertEquals(true, test1.property(DateTimeFieldType.hourOfDay()).compareTo(test1) == 0); try { test1.property(DateTimeFieldType.hourOfDay()).compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.property(DateTimeFieldType.hourOfDay()).compareTo(dt2) < 0); assertEquals(true, test2.property(DateTimeFieldType.hourOfDay()).compareTo(dt1) > 0); assertEquals(true, test1.property(DateTimeFieldType.hourOfDay()).compareTo(dt1) == 0); try { test1.property(DateTimeFieldType.hourOfDay()).compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} }
8563af26-4728-47f2-ac61-759cb77c33a2
2
public Grammar getGrammar() { Production[] p = editingGrammarModel.getProductions(); try { p = CNFConverter.convert(p); } catch (UnsupportedOperationException e) { JOptionPane.showMessageDialog(this, e.getMessage(), "CNF Conversion Error", JOptionPane.ERROR_MESSAGE); return null; } try { Grammar g = (Grammar) grammar.getClass().newInstance(); g.addProductions(p); g.setStartVariable(grammar.getStartVariable()); return g; } catch (Throwable e) { System.err.println(e); } return null; }
1bd10f66-0757-4f21-9716-ae2c3947b0c5
4
public void compactEnd() { final int compactSize = compactIndexUsed.cardinality(); if (compactSize == map.size()) { return; } for (int i = 1; i < list.size(); i++) { if (compactIndexUsed.get(i)) continue; // to be removed T t = list.get(i); list.set(i, null); map.remove(t); if (addPosition > i) addPosition = i; } }
90c0acc9-62af-4ffb-aba2-7e4f0c3f8309
5
public static IEncrypterDecryptor getInstance(ALGORITHMS algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException { if (algorithm.equals(ALGORITHMS.TRIPLEDES)) { if (tripleDescDESEncrypter == null) { tripleDescDESEncrypter = new TripleDESEncrypter(); } return tripleDescDESEncrypter; } else if (algorithm.equals(ALGORITHMS.MD5)) { if (md5DesEncrpter == null) { try { md5DesEncrpter = new MD5ANDDESEncrypter(); } catch (InvalidKeySpecException ex) { ex.printStackTrace(); } } return md5DesEncrpter; }else{ throw new NoSuchAlgorithmException("Algorithm not found"); } }
5fe6d105-1526-43bd-88b0-0c26de2379ca
4
public void fromByteHelper(Node currentNode, Bits bits) { if (currentNode != null) { if (currentNode.parent != null) { if (currentNode.parent.right != null) { bits.offerFirst(currentNode.parent.right == currentNode); } else if (currentNode.parent.left != null) { bits.offerFirst(currentNode.parent.left != currentNode); } fromByteHelper(currentNode.parent, bits); } } }
0bd1bbb6-b6e0-473b-a8cd-893dc3449cc9
4
private String obtemIdentificador(HttpServletRequest req) throws RecursoSemIdentificadorException{ String requestURI = req.getRequestURI(); String[] pedacosDaUri = requestURI.split("/"); boolean contextoCervejasEncontrado = false; for(String contexto : pedacosDaUri){ if(contexto.equals("cervejas")){ contextoCervejasEncontrado = true; continue; } if(contextoCervejasEncontrado){ try{ return URLDecoder.decode(contexto, "UTF-8"); }catch(UnsupportedEncodingException e){ return URLDecoder.decode(contexto); } } } throw new RecursoSemIdentificadorException("Recurso sem identificador"); }
39ebc56a-2d84-494d-b20b-55bbce60243f
2
public void testWithers() { LocalTime test = new LocalTime(10, 20, 30, 40); check(test.withHourOfDay(6), 6, 20, 30, 40); check(test.withMinuteOfHour(6), 10, 6, 30, 40); check(test.withSecondOfMinute(6), 10, 20, 6, 40); check(test.withMillisOfSecond(6), 10, 20, 30, 6); check(test.withMillisOfDay(61234), 0, 1, 1, 234); try { test.withHourOfDay(-1); fail(); } catch (IllegalArgumentException ex) {} try { test.withHourOfDay(24); fail(); } catch (IllegalArgumentException ex) {} }
cfdb6cb1-bcb8-4d6d-a03c-04f07d4e223a
0
public Map<Integer, BigDecimal> getPrices() { return prices; }
0bb01b87-e156-4c1c-b817-a10316bfb492
6
public void searchOneWayFlights() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Where is your MySQL JDBC Driver?"); e.printStackTrace(); } PreparedStatement ps = null; Connection con = null; ResultSet rs; try { con = DriverManager.getConnection("jdbc:mysql://mysql2.cs.stonybrook.edu:3306/mlavina", "mlavina", "108262940"); if (con != null) { con.setAutoCommit(false); String sql = "Create OR Replace view SearchResults(Name, FlightNo, DepTime, ArrTime, DepAirportID, ArrAirportID, LegNo, Class, fare, AirlineID)\n" + "as\n" + "SELECT DISTINCT R.Name, L.FlightNo, L.DepTime, L.ArrTime, L.DepAirportId, L.ArrAirportId, L.LegNo, M.Class, M.Fare, L.AirlineID\n" + "FROM Flight F, Leg L, Airport A , Fare M, Airline R\n" + "WHERE F.AirlineID = L.AirlineID AND F.FlightNo = L.FlightNo \n" + " AND (L.DepAirportId = ? OR L.ArrAirportId = ?) AND M.AirlineID = L.AirlineID \n" + "AND M.FlightNo = L.FlightNo AND R.Id = L.AirlineID AND M.FareType = 'Regular' \n" + "AND L.DepTime > ? AND L.DepTime < ? "; ps = con.prepareStatement(sql); ps.setString(1, flightFrom); ps.setString(2, flightTo); ps.setDate(3, new java.sql.Date(departing.getTime())); ps.setDate(4, new java.sql.Date(departing.getTime() + +(1000 * 60 * 60 * 24))); System.out.println(ps); try { ps.execute(); sql = "select Distinct A.Name, A.FlightNo, A.DepTime, B.ArrTime ,A.class, A.fare, A.DepAirportID, A.LegNo, A.AirlineID, B.ArrAirportID\n" + "From searchresults A, searchresults B\n" + "Where ((A.ArrAirportID = B.DepAirportID) OR (A.DepAirportID = ? AND B.ArrAirportID = ?))"; ps = con.prepareStatement(sql); ps.setString(1, flightFrom); ps.setString(2, flightTo); ps.execute(); rs = ps.getResultSet(); flightResults.removeAll(flightResults); int i = 0; while (rs.next()) { //flightResults.add() flightResults.add(new Flight(rs.getString("AirlineID"), rs.getString("Name"), rs.getInt("FlightNo"), rs.getTimestamp("DepTime"), rs.getTimestamp("ArrTime"), rs.getString("Class"), rs.getDouble("fare"), rs.getString("DepAirportID"), rs.getString("ArrAirportID"), i, rs.getInt("LegNo"))); i++; } con.commit(); } catch (Exception e) { con.rollback(); } } } catch (Exception e) { System.out.println(e); } finally { try { con.setAutoCommit(true); con.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } }
83417c7a-7203-4568-870f-68b92fee1fa8
5
private boolean checkOptimumInfini(Matrice delta) { boolean optimumIsInfini = true; for(int i = 0; i<delta.getNbColumns(); i++) { if(delta.getValueAt(0, i) < 0) { for(int j = 0; j<this.Abarre.getNbLines(); j++) { if(this.Abarre.getValueAt(j, i) >= 0) { optimumIsInfini = false; } } //Si pour un delta <0 tous les aij barre sont <0 if(optimumIsInfini) { return true; } else{ optimumIsInfini = true; } } } return false; }
2eccaafc-b434-4846-a24e-2f2e1c7f85b5
6
public static Stella_Object access_SampleContents_Slot_Value(SampleContents self, Symbol slotname, Stella_Object value, boolean setvalueP) { if (slotname == Sample.SYM_SAMPLE_sampleAttr) { if (setvalueP) { self.sampleAttr = ((StringWrapper)(value)).wrapperValue; } else { value = StringWrapper.wrapString(self.sampleAttr); } } else if (slotname == Sample.SYM_SAMPLE_sub) { if (setvalueP) { self.sub = ((SampleNested)(value)); } else { value = self.sub; } } else if (slotname == Sample.SYM_SAMPLE_SampleListItem) { if (setvalueP) { self.SampleListItem = ((List)(value)); } else { value = self.SampleListItem; } } else { { OutputStringStream STREAM_000 = OutputStringStream.newOutputStringStream(); STREAM_000.nativeStream.print("`" + slotname + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(STREAM_000.theStringReader()).fillInStackTrace())); } } return (value); }
7e6722d2-17e6-425a-81f4-340b1b2edbba
1
public void deactivate() { try { socket.getInputStream().close(); socket.getOutputStream().close(); socket.close(); GUI.println("Socket closed!!!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
a9be6660-7d5b-4201-800b-2253c22f6e67
2
private char[] insertCharToStr(char ch, char[] s, int pos) { int newLen = s.length + 1; char[] result = new char[newLen]; // copy anything before position for (int i = 0; i < pos; i++) { result[i] = s[i]; } for (int j = pos; j < s.length; j++) { result[j + 1] = s[j]; } result[pos] = ch; return result; }
72cdb739-8049-47a4-b446-cea4ee478db5
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Sony.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Sony.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Sony.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Sony.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 Sony().setVisible(true); } }); }
f877002a-4814-49d2-8a7c-ab37705950a2
4
@EventHandler public void onSignChange(SignChangeEvent evt){ if(evt.getLine(0).contains("Arena-") && Util.isNumeric(evt.getLine(0).replace("Arena-", ""))){ Arena a = ArenaManager.getManager().getArena(Integer.parseInt(evt.getLine(0).replace("Arena-", ""))); if(a != null){ String line2 = a.getSize() + " / " + evt.getLine(2); evt.setLine(2, line2); if(!SignUpdate.getCons().signLocs.containsValue(evt.getBlock().getLocation())){ SignUpdate.getCons().signLocs.put(a, evt.getBlock().getLocation()); } } } }
e6a9dcba-a097-49b9-b1ca-64a6a19d27ee
6
public static int searchInsert(int[] source, int target) { int start = 0; int end = source.length; int guard = end; int index = 0; if (end == 0) { return index; } while (end >= start) { // 防止end与start相加之后超过int的最大值 int middle = start + (end - start) / 2; if (middle < guard) { int temp = source[middle]; if (temp > target) { end = middle - 1; } else if (temp < target) { start = middle + 1; } else { return middle; } } else { return middle; } } if (end < start) { index = end + 1; } return index; }
576676cc-d163-4eb4-a08f-3a2602769f44
3
private String getUpdateSetClause(String dbColumnName, Object value) { if (value instanceof Date) { return dbColumnName + "='" + DaoUtils.DATE_FORMATTER.format(value) + "'"; } else if (value.getClass().isEnum()) { return dbColumnName + "=" + EnumUtils.getId(value) + ""; } else if (value instanceof String) { value = value.toString().replaceAll("'", "''"); return dbColumnName + "='" + value + "'"; } else { // All types of Numbers return dbColumnName + "=" + value.toString() + ""; } }
82f02300-af37-4de4-9af5-dcfe3d3992a1
0
public Member getMember() { return member; }
13073b69-4c78-4351-91a9-2ba6d6fae4bb
2
public static boolean isMatchForPassword(String password, String confPassword) { if (password == null || confPassword == null) return false; return password.equals(confPassword); }
51bb7b35-a0a1-47bd-9e47-2644f3bda846
8
public void executeRemotely(Command<?>... commands) { CommandFacade facade = context.getBean("commandFacade", CommandFacade.class); List<Command<?>> incomeCommands = Arrays.asList(commands); CommandList commandsToServer = new CommandList(incomeCommands); Command<List<Command<?>>> resultCommand = facade.executeRemotely(commandsToServer); List<Command<?>> resultCommandList = resultCommand.getResult(); for (Iterator<Command<?>> resultIterator = resultCommandList.iterator(), incomeIterator = incomeCommands.iterator(); resultIterator.hasNext() && incomeIterator.hasNext();) { Command<?> resCmd = resultIterator.next(); Command incomeCmd = incomeIterator.next(); incomeCmd.setResult(resCmd.getResult()); } }
7d44e267-826b-4cd8-89bd-cc1baa7798c7
3
@Override public void run() { Date dte = new Date(); Timestamp ts = new Timestamp(dte.getTime()); while (true) { try { while (true) { Thread.sleep(20000); lastRTime = (ts.getTime()/1000) + 20000; dbConnect("jdbc:jtds:sqlserver://172.16.0.100:1433/CDR", "CT_USER", "ct2007voice"); } } catch (InterruptedException e) { Logger.getLogger(CallmanagerCDR.class.getName()).log(Level.SEVERE, null, e); } } }
26b4a813-f5f3-4bce-b8d3-dc44fd2eda94
4
private static int getCoordinateOfCell(Field field, char coordinateName){ Scanner scanner = new Scanner(System.in); int coordinate = 0; System.out.println("Please enter cell " + coordinateName + " coordinate:"); while(true){ if(scanner.hasNextInt()) { coordinate = scanner.nextInt(); if(coordinate >= field.getMinCoordinateValue() && coordinate < field.getFieldSize() ){ return coordinate; } else { coordinate = 0; System.out.println("This number is not valid. Please try again"); } } else { System.out.println("This number is not integer. Please try again"); } } }
7c468f14-1790-4ef2-a605-42e229268436
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Projeto)) { return false; } Projeto other = (Projeto) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
138cb401-06cd-4c4b-90c6-2882df1f06d1
5
@Override public void paint(Graphics g) { super.paint(g); if (cache == null) cache = bufferOwner.getWaveData(); if (cache == null || cache.length == 0) { g.drawString("No wave data available at this time.",0,200); return; } g.drawString(Integer.toString(cache.length),0,30); final int height = 128, origin = height + 10, ticks = 100; double scale = (double) getWidth() / cache.length; g.drawLine(0,origin - height,getWidth(),origin - height); g.drawLine(0,origin,getWidth(),origin); g.drawLine(0,origin + height,getWidth(),origin + height); for (int i = 0; i < cache.length - 1; i++) { g.drawLine((int) (i * scale),cache[i] + origin,(int) ((i + 1) * scale),cache[i + 1] + origin); if (i % ticks == 0) { Color c = g.getColor(); g.setColor(Color.RED); g.drawLine(i,origin - 10,i,origin + 10); g.drawString(Integer.toString(i),i + 2,origin - 2); g.setColor(c); } } //data points } //paint
83fdada7-97af-4e73-bbbe-df8ad7631bae
6
@Override public QueryResult updateQuery(Query q) { Statement st = null; if(!q.isParsed()) { q.parse(); } try { st = con.createStatement(); st.executeUpdate(q.getParsedQuery()); }catch (SQLException e) { plugin.getLogger().log(Level.SEVERE, " Could not execute query!"); if(this.dbg) { plugin.getLogger().log(Level.INFO, e.getMessage(), e); } } finally { try { if(st != null) { st.close(); } }catch (Exception e) { plugin.getLogger().log(Level.SEVERE, " Could not close database connection"); if(this.dbg) { plugin.getLogger().log(Level.INFO, e.getMessage(), e); } } } return QueryResult.QR(); }
7b150794-e9c0-41cf-b5e7-44cb8a73c315
3
private void dribbleAwayOtherGoal(){ turnTowardBall(); if(distanceBall < 0.7){ if(canSeeOtherGoal){ if(distanceOtherGoal < 30) {getPlayer().kick(100, directionOtherGoal); } else{ getPlayer().kick(40, directionOtherGoal+5); } }else getPlayer().turnNeck(90); } getPlayer().dash(60); }
b6d90b1c-badd-4c50-8129-79ade03019da
1
public static String getWebINFPath() { String path = getWebClassesPath(); if (path.indexOf("WEB-INF") > 0) { path = path.substring(1, path.indexOf("WEB-INF") + 8); path = path.replace("/", File.separator); return path; } return null; }
2124c3b8-6a47-456a-99fa-44636a2a9793
1
public void newCustomer() { Database db = dbconnect(); try { String query = "INSERT INTO customer (firstName, lastName, username, password, telephone, email) VALUES " + "(?,?,?,?,?,?)"; db.prepare(query); db.bind_param(1, this.c_firstname); db.bind_param(2, this.c_lastname); db.bind_param(3, this.c_username); db.bind_param(4, this.c_pw); db.bind_param(5, this.c_tel); db.bind_param(6, this.c_email); db.executeUpdate(); db.close(); } catch(SQLException e){ Error_Frame.Error(e.toString()); } }
98db2a6a-6bf3-45a6-abd3-f16e51ab9314
8
@Override public void run(DetAdv da, GameVars gameVars) { Scanner inputReader = saveAndGetScanner(gameVars); if (policeStationState == JUST_ENTERED) { System.out.println("The police force has been riddled with worthless cases lately.\nPeople will call the police over such stupid things nowadays."); DetUtil.doContinue(inputReader); System.out.println("\""+gameVars.getCharacterName()+"! You need to get to the scene of the crime immediately!\""); ChoiceMenu first = new ChoiceMenu(); first.addOption("inquire"); first.addOption("leave"); first.execute(gameVars); if (first.getChoice() == 2) { policeStationState = LEAVING; run(da, gameVars); }else if (first.getChoice() == 1) { policeStationState = INQUIRE; run(da, gameVars); } }else if (policeStationState == LEAVING) { System.out.println("I left the police station. I figure this'll be just a cuff and book case..."); DetUtil.doContinue(inputReader); System.out.println("Oh how wrong I was..."); DetUtil.doContinue(inputReader); gameVars.setLocation(GameVars.CAR); gameVars.car.state = Car.DRIVING_TO_MANSION; da.run(gameVars); }else if (policeStationState == INQUIRE) { System.out.println(gameVars.getCharacterName()+": \"What's this mess about, Walt?\""); DetUtil.doContinue(inputReader); String explainStrange = "Walt: \"This is a strange one, "+gameVars.getCharacterName()+", but important none the less!\""; System.out.println(explainStrange); ChoiceMenu strange = new ChoiceMenu(); strange.setFailText(explainStrange+"\nYou have to choose an option:"); strange.addOption("comment on this"); strange.addOption("continue"); strange.execute(gameVars); if (strange.getChoice() == 1) { System.out.println(gameVars.getCharacterName()+": \"Walt... after 25 years on the jobs, nothing surprises me anymore...\""); DetUtil.doContinue(inputReader); System.out.println("I said that thinking this would be another cuff and book case"); DetUtil.doContinue(inputReader); System.out.println("Oh how wrong I was..."); DetUtil.doContinue(inputReader); } String fakeKidText = "Walt: \"The victim is a 3 year old male...\""; System.out.println(fakeKidText); ChoiceMenu kidChoice = new ChoiceMenu(); kidChoice.setFailText(fakeKidText+"\nYou have to choose an option:"); kidChoice.addOption("comment on this"); kidChoice.addOption("continue"); kidChoice.execute(gameVars); if (kidChoice.getChoice() == 1) { System.out.println(gameVars.getCharacterName()+": \"Jesus... Just a kid...\""); DetUtil.doContinue(inputReader); System.out.println("Walt: \"Damnit, "+gameVars.getCharacterName()+", it's a horse! Not a child! Will you stop interrupting!"); DetUtil.doContinue(inputReader); DetUtil.popupImage("angryFace.png"); DetUtil.doContinue(inputReader); System.out.println("Walt: \"Now I need you to get out there ASAP, you hear me!?\""); DetUtil.doContinue(inputReader); }else if (kidChoice.getChoice() == 2) { System.out.println("Walt: \"...horse. It died late last night around 11pm. An important figure wants this wrapped up quickly so get on it!"); DetUtil.doContinue(inputReader); } System.out.println("I head out of the Police Station, it's raining now. I hope that doesn't affect the crime scene..."); DetUtil.doContinue(inputReader); gameVars.setLocation(GameVars.CAR); gameVars.car.state = Car.DRIVING_TO_MANSION; gameVars.rain = GameVars.RAIN; da.run(gameVars); } }
0002b6eb-1a58-463d-a372-cf8356a7e191
0
public boolean isOpen() { return this.open; }
4ab311e3-d64f-4878-9e04-ca5de73dd41d
9
protected AttributeClassObserver newNumericClassObserver() { switch (this.numericEstimatorOption.getChosenIndex()) { case 0: return new GaussianNumericAttributeClassObserver(10); case 1: return new GaussianNumericAttributeClassObserver(100); case 2: return new GreenwaldKhannaNumericAttributeClassObserver(10); case 3: return new GreenwaldKhannaNumericAttributeClassObserver(100); case 4: return new GreenwaldKhannaNumericAttributeClassObserver(1000); case 5: return new VFMLNumericAttributeClassObserver(10); case 6: return new VFMLNumericAttributeClassObserver(100); case 7: return new VFMLNumericAttributeClassObserver(1000); case 8: return new BinaryTreeNumericAttributeClassObserver(); } return new GaussianNumericAttributeClassObserver(); }
0c8b56a0-cfc6-495b-b42b-ae120b14df4b
5
public static void setB(Node[][] nodes){ for (int br=0;br<3;br++){ for (int bc=0;bc<3;bc++){ for (int n=0;n<9;n++){ int index1=(br*3+bc)*9+n+81*3; for (int r=0;r<3;r++){ for (int c=0;c<3;c++){ int index2=(r+br*3)*81+(c+bc*3)*9+n; nodes[index1][index2]=new Node(1); } } } } } }
a488d50c-92e8-4105-87c7-34fc015fac71
4
public void resize() { if (getPrefWidth() > 0 && getPrefHeight() > 0) { if (resizeable) { size = getPrefWidth() < getPrefHeight() ? getPrefWidth() : getPrefHeight(); setPrefSize(size * getSymbolType().WIDTH_FACTOR, size * getSymbolType().HEIGHT_FACTOR); } else { setMinSize(size * getSymbolType().WIDTH_FACTOR, size * getSymbolType().HEIGHT_FACTOR); setPrefSize(size * getSymbolType().WIDTH_FACTOR, size * getSymbolType().HEIGHT_FACTOR); setMaxSize(size * getSymbolType().WIDTH_FACTOR, size * getSymbolType().HEIGHT_FACTOR); } } }
d33f23ba-bca4-4757-86f4-7b900cf66a13
5
private void jTextArea2KeyPressed(java.awt.event.KeyEvent evt) { if (KeyEvent.VK_ESCAPE == evt.getKeyCode()) {// 按ESC键,关闭聊天窗口 this.dispose(); } else if (KeyEvent.VK_ENTER == evt.getKeyCode()) { enter = true; } else if (KeyEvent.VK_CONTROL == evt.getKeyCode()) { ctrl = true; } if (enter && ctrl) {// 如果enter和ctrl同时按下,发送消息 handleMessage(); } }
ca23cca7-006c-4972-adf6-ec6e97ae659c
9
private Node<K,V> floor( V value ) { if(value == null) return null; Node<K,V> node = mRoot; Node<K,V> ret = null; if(mValueComparator != null) { Comparator<? super V> comp = mValueComparator; while(node != null) { int c = comp.compare(value, node.mValue); if(c < 0) { node = node.mAllLeft; }else{ ret = node; node = node.mAllRight; } } }else{ Comparable<? super V> comp = (Comparable<? super V>)value; while(node != null) { int c = comp.compareTo(node.mValue); if(c < 0) { node = node.mAllLeft; }else{ ret = node; node = node.mAllRight; } } } return ret; }
979653ba-2f3e-4b41-b0ad-ddd671ca87c7
6
private static Image createIcon(Component component, Color color) { int rgb = color.getRGB(); int[] pix = new int[12 * 12]; for (int x = 0; x < 12; x++) { for (int y = 0; y < 12; y++) { pix[x + y * 12] = ((x > 0) && (x < 11) && (y > 0) && (y < 11)) ? rgb : 0xff666666; } } return component.createImage( new MemoryImageSource(12, 12, pix, 0, 12)); }
7b7ece8f-1ddd-4c17-931a-387967c7d5c4
0
public String getIssueNo() { return issueNo; }
bf7c6d35-bf56-4da5-b02a-6845c5835640
1
public DalcSong() { try { mConnection = DBConnection.getConnection(); } catch (SQLServerException ex) { } }
2d550b24-32e0-4bf6-a7ad-ca8100ace52d
9
private void login_buttonActionPerformed(ActionEvent evt) { /* * Pass the user name and password to the login system. The login system * will indicate whether the login succeeded. If it did, hide the login * screen and show the splash page according to the user's Role. */ String name = username_field.getText(); String pass = new String(password_field.getPassword()); Account acct; boolean login = false; boolean backdoor = false; int attempts = 0; if (name.equalsIgnoreCase("sysadmin")) { backdoor = true; login = true; acct = new SystemAdmin("Joey", "Tester", 9999, "password", "sysadmin"); } else if (name.equalsIgnoreCase("admin")) { backdoor = true; login = true; acct = new AcademicAdmin("Joey", "Tester", 9999, "password", "admin"); } else if (name.equalsIgnoreCase("assist")) { backdoor = true; login = true; acct = new AssistantAdmin("Joey", "Tester", 9999, "password", "assist"); } else if (name.equalsIgnoreCase("instructor")) { backdoor = true; login = true; acct = new Instructor("Joey", "Tester", 9999, "password", "instructor"); } else if (name.equalsIgnoreCase("tatm")) { backdoor = true; login = true; acct = new TATM("Joey", "Tester", 9999, "password", "ta"); } else { login = Login.login(name, pass); acct = AccountAccess.constructAccountObject(name); } if (acct != null && acct.isBlocked()) { JOptionPane.showMessageDialog(this, "This account is blocked."); } else if (!login) { attempts = AccountAccess.failedLogin(name); JOptionPane.showMessageDialog(this, "Invalid username/password combo. Attempts left: " + (5 - attempts)); } else { if (!backdoor) { AccountAccess.successfulLogin(name); System.out.println("login good"); } System.out.println("Logging in as " + name + " with password `" + pass + "`"); master = new MasterFrame(acct, this); this.setVisible(false); master.run(); } }
6bfc32c6-12e4-4be8-9686-765501f55494
9
@Override public int read(ByteBuffer buffer) throws IOException { if (engine.isInboundDone()) { // We can skip the read operation as the SSLEngine is closed, // instead, propagate EOF one level up return -1; } decryptedIn.clear(); int pos = decryptedIn.position(); // Read from the channel int count = sc.read(encryptedIn); logger.log(Level.FINEST, "{0} Read {1} bytes encrypted", new Object[]{sc.socket().getRemoteSocketAddress(), count}); if (count == -1) { // We have reached EOF, propagate one level up // At this point, we may not have received close_notify from peer, // and as such we cannot SSLEngine.closeInbound(), this will happen // in a subsequent step //engine.closeInbound(); return count; } // Unwrap the data just read encryptedIn.flip(); result = engine.unwrap(encryptedIn, decryptedIn); encryptedIn.compact(); // Process the engineResult.Status switch (result.getStatus()) { case BUFFER_UNDERFLOW: // nothing was read. This is the entry point for initiating a // short timeout in the underlying socket if we are still in the // handshaking phase. The reason is to rule out DDOS attacks // where a high number of idle connections are created with the // sole purpose of either exhausting the ports of the host // machine or depleting the host machine's memory. // Schedule a new timeout toWorker.insert(timeout); logger.log(Level.FINEST, "{0} BUFFER_UNDERFLOW", sc.socket().getRemoteSocketAddress()); return 0; case BUFFER_OVERFLOW: if (!timeout.hasExpired()) { // cancel any previous timeout toWorker.cancel(timeout); } logger.log(Level.FINEST, "{0} BUFFER_OVERFLOW", sc.socket().getRemoteSocketAddress()); // This should never happen (ideally). If this happens, the // thread responsible for emptying the decryptedIn buffer has // not done so in time. Throw an exception to be handled at the // application layer. throw new BufferOverflowException(); case CLOSED: logger.log(Level.FINEST, "{0} CLOSED", sc.socket().getRemoteSocketAddress()); // The SSLEngine was inbound closed, there is and will be no // more input from the engine, so setup the socket appropriately // too. An outbound close_notify will be send by the SSLEngine sc.socket().shutdownInput(); break; case OK: if (!timeout.hasExpired()) { // cancel any previous timeout toWorker.cancel(timeout); } logger.log(Level.FINEST, "{0} OK", sc.socket().getRemoteSocketAddress()); break; } // process any handshaking now required processHandshake(); // put the data to the buffer given to us for (int i = pos; i < decryptedIn.position(); i++) { buffer.put(decryptedIn.get(i)); } // return count of application data read count = decryptedIn.position() - pos; return count; }
6b57315f-90bb-4f31-8d07-2afa88b310cd
0
public final void restart() { environmentStack = new Stack<FunctionEnvironmentRecord>(); environmentStack.add(new FunctionEnvironmentRecord()); savedEnvironmentStackSize = environmentStack.size(); savedArgs = new ArrayList<Integer>(); reasonForStopping = ""; stepOverPending = false; stepInPending = false; stepOutPending = false; executionFinished = false; runStack = new RunTimeStack(); pc = 0; returnAddrs = new Stack<Integer>(); running = false; dumping = false; savedFunctionAddress = 0; }
3aa4aed4-71e2-4966-8d26-4b51db84bf2f
1
public String listaDeUsuarios(){ String lista= ""; for(int i = 0; i < usuarios.size(); i++){ lista = lista + usuarios.get(i).getNombre() + "<BR>"; } return lista; }
0c7114d4-e9cc-4692-a0c4-eb73955c6caa
9
void insert(Object number, int timesPresent){ if(head == null){ Node newNode = new Node(number,timesPresent); head = newNode; tail = newNode; }else{ Node temp = head; if(size() != maxLength){ while(true){ if(temp.timesPresent < timesPresent){ Node newNode = new Node(number,timesPresent); newNode.next = temp; newNode.prev = temp.prev; temp.prev = newNode; if(temp == head) { head = newNode; }else{ temp = newNode.prev; temp.next = newNode; } temp = newNode.next; break; } if(temp.next == null){ Node newNode = new Node(number,timesPresent); tail = newNode; temp.next = newNode; newNode.prev = temp; break; } temp = temp.next; } }else{ temp = head; while(temp !=null){ if(temp.timesPresent < timesPresent){ Node newNode = new Node(number,timesPresent); newNode.next = temp; newNode.prev = temp.prev; temp.prev = newNode; if(temp == head) { head = newNode; }else{ temp = newNode.prev; temp.next = newNode; } temp = newNode.next; removeLast(); break; } temp = temp.next; } } } }
2f2e973e-fa1c-41a9-bbf0-608e71986a91
4
@Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { if (qName.equals("rowset")) { String name = getString(attrs, "name"); oldRoles = name.equals("oldRoles"); newRoles = name.equals("newRoles"); } else if (qName.equals("row")) { if (oldRoles) { roleHistory.addOldRole(getRole(attrs)); } else if (newRoles) { roleHistory.addNewRole(getRole(attrs)); } else { roleHistory = getItem(attrs); response.add(roleHistory); } } else super.startElement(uri, localName, qName, attrs); }
4de41799-f6b0-4e6d-964b-07348a48e0ad
1
public boolean isObjectWithinRange(Placeable obj, Placeable obj2) { if (obj.distanceTo(obj2) <= range) { return true; } return false; }
e9fb539a-98fa-416a-98ec-b6eb946812f0
8
public void loadImagesFile(String fnm) /* Formats: o <fnm> // a single image n <fnm*.ext> <number> // a numbered sequence of images s <fnm> <number> // an images strip g <name> <fnm> [ <fnm> ]* // a group of images and blank lines and comment lines. */ { char ch; String line; String test = GameController.CONFIG_DIR + fnm; try { InputStream in = getClass().getResourceAsStream(GameController.CONFIG_DIR + fnm); BufferedReader br = new BufferedReader(new InputStreamReader(in)); while ((line = br.readLine()) != null) { if (line.length() == 0) { continue; } if (line.startsWith("//")) { continue; } ch = Character.toLowerCase(line.charAt(0)); if (ch == 'o') { getFileNameImage(line); } else if (ch == 'n') { getNumberedImages(line); } else if (ch == 's') { getStripImages(line); } else if (ch == 'g') { getGroupImages(line); } else { EIError.debugMsg("Do not recognize line: " + line, EIError.ErrorLevel.Error); } } in.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } }
37fb8244-473b-47b2-98d1-490351bcf8ab
4
public void gestionDuClavier(KeyEvent ke) { if(ke.getKeyCode() == KeyEvent.VK_RIGHT) this.serpent.setNouvelleDirection(Serpent.Direction.VERS_LA_DROITE); else if(ke.getKeyCode() == KeyEvent.VK_LEFT) this.serpent.setNouvelleDirection(Serpent.Direction.VERS_LA_GAUCHE); else if(ke.getKeyCode() == KeyEvent.VK_UP) this.serpent.setNouvelleDirection(Serpent.Direction.VERS_LE_HAUT); else if (ke.getKeyCode() == KeyEvent.VK_DOWN) this.serpent.setNouvelleDirection(Serpent.Direction.VERS_LE_BAS); }
a6bcb4c0-7574-4f95-8cc6-79563d41cb90
9
@Override @SuppressWarnings({"unchecked","rawtypes"}) public final boolean equals(final Object o) { if (o==this) return true; if (!super.equals(o)) return false; if (o instanceof LegacyNumericRangeQuery) { final LegacyNumericRangeQuery q=(LegacyNumericRangeQuery)o; return ( (q.min == null ? min == null : q.min.equals(min)) && (q.max == null ? max == null : q.max.equals(max)) && minInclusive == q.minInclusive && maxInclusive == q.maxInclusive && precisionStep == q.precisionStep ); } return false; }
12505425-ec40-41f3-af18-5661c84cf6c9
8
private boolean actualizar(){ // Buffer que permite evitar el parpadeo cada vez que se limpia la pantalla, // además es el objeto donde se intaran los sprites BufferedImage pantalla=new BufferedImage(this.getWidth(),this.getHeight(), BufferedImage.TYPE_INT_RGB); pantalla.getGraphics().fillRect(0, 0, pantalla.getWidth(), pantalla.getHeight()); // banderas del control de la partida boolean gameOver=true,jugadorVivo=false; // Gestionamos TODOS los sprites for (int i=0;i<sprites.size();i++) { try {// Pintamos el sprite ((Sprite)sprites.get(i)).putSprite((Graphics2D)pantalla.getGraphics(),((Sprite)sprites.get(i)).getX(), ((Sprite)sprites.get(i)).getY()); // En caso de que el sprite sea la NAVE del jugador if (sprites.get(i).getClass()==Nave.class) { ((Nave)sprites.get(i)).actualiza(); // Mueve la nave acorde a las teclas pulsadas // Comprueba si hay algun MISIL que impacte con la nave jugadorVivo=compruebaImpactoMisil(((Nave)sprites.get(i))); // En caso de que el sprite sea un LASER disparado por el jugador } else if (sprites.get(i).getClass()==Laser.class) { // Comprobamos si hay impacto del LASER con un UFO if (((Laser)sprites.get(i)).isVisible()) compruebaImpactoDelLaser((Laser)sprites.get(i)); // En caso de impacto eliminamos el LASER else sprites.remove(i); // En caso de que el sprite sea un UFO o una nave alienigena } else if (sprites.get(i).getClass()==UFO.class) { // Significará que la partida todavía no ha acabado y qeu faltan UFOs por destruir gameOver=false; // Si el UFO fue impactado por el LASER (invisible) lo eliminamos if (!((UFO)sprites.get(i)).isVisible()) sprites.remove(i); } } catch(IndexOutOfBoundsException ioex){ } } // Volcamos el buffer visual donde se dibujan los sprites a la ventana this.getGraphics().drawImage(pantalla, 0, 0, this); return (!gameOver && jugadorVivo); }
64445425-baf4-41d1-a2c1-33067551f70b
5
public void update() { Set<LivraisonGraphVertex> tree = new HashSet<>(); for(Chemin chemin : chemins) { tree.add(chemin.getOrigine()); tree.add(chemin.getDestination()); } this.noeuds = new ArrayList<>(tree); this.idToIndex = new HashMap<>(); int nbNoeuds = this.getNoeuds().size(); for (int i = 0; i < nbNoeuds; ++i) { LivraisonGraphVertex noeud = this.getNoeuds().get(i); this.idToIndex.put(noeud.getIdNoeud(), i); for (Chemin chemin : noeud.getSortants()) { int cost = chemin.getCost(); this.maxArcCost = cost > this.maxArcCost ? cost : this.maxArcCost; this.minArcCost = cost < this.minArcCost ? cost : this.minArcCost; } } }
27a697e7-87ad-41d3-b726-86c6a5401d23
2
public boolean isComment (char c) throws IOException { char temp = (char)sourceFile.read(); if ((c=='/') && temp=='/') { sourceFile.unread(temp); return true; } sourceFile.unread(temp); return false; }
ccc4b8d4-d03a-4673-adbe-ec8fd033866c
4
@Override public WebSocketResponse endFirstUnitPlacement(GameClient gameClient, JSONObject value) { //System.out.println("end first unitplacement"); int clientId = gameClient.getIdentifyer(); List<ClientMapChange> clientMapChanges = new LinkedList(); Iterator mapChanges = value.entrySet().iterator(); while(mapChanges.hasNext()){ Entry thisEntry = (Entry) mapChanges.next(); ClientMapChange o = new ClientMapChange(); o.CountryId = (String)thisEntry.getKey(); Long temp = (Long)thisEntry.getValue(); o.AddedUnits = temp.intValue() ; clientMapChanges.add(o); } EndFirstUnitPlacementMessage message = gameManager.EndFirstUnitPlacement(clientId, clientMapChanges); RisikoServerResponse response = new RisikoServerResponse(); response.setState(1); response.setMessage( message.getClass().getSimpleName() ); response.addTargetClientList( message.PlayerIDsToUpdate ); response.addChangedObject( message.Player ); if(message.Game != null){ response.addChangedObject(message.Game); } if(message.CurrentMap != null){ List<MapChange> changedMaps = message.CurrentMap; for(int i = 0; i< changedMaps.size(); i++) { response.addChangedObject( changedMaps.get(i) ); } } return response; }