method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
3d193e10-296f-450e-a8c1-7d5d9a74ac07
3
public void inheritAllConstructors() throws CannotCompileException, NotFoundException { CtClass superclazz; CtConstructor[] cs; superclazz = getSuperclass(); cs = superclazz.getDeclaredConstructors(); int n = 0; for (int i = 0; i < cs.length; ++i) { CtConstructor c = cs[i]; int mod = c.getModifiers(); if (isInheritable(mod, superclazz)) { CtConstructor cons = CtNewConstructor.make(c.getParameterTypes(), c.getExceptionTypes(), this); cons.setModifiers(mod & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE)); addConstructor(cons); ++n; } } if (n < 1) throw new CannotCompileException( "no public constructor in " + superclazz.getName()); }
d127efbe-4e72-4505-8314-3fbaa7c3117b
3
public static boolean registerEvent(final IEvent event) { if(!eventMap.containsKey(event)) { //We need to set up the Map to not bitch about things HashSet<Pair<Method, EventListener>> set; TreeMap<Priority, HashSet<Pair<Method, EventListener>>> value = new TreeMap<Priority, HashSet<Pair<Method, EventListener>>>(new PrioritySorter()); for(Priority p : Priority.values()) { set = new HashSet<Pair<Method, EventListener>>(); value.put(p, set); } eventMap.put(event, value); return true; } else { //The Event already exists String classpath = event.getClass().getCanonicalName(); if(classpath == null) classpath = "NULL"; logger.err("EventBus", "Event "+event.getEventName()+" ("+classpath+"):", 0); logger.err("EventBus", "Event was already registered!", 1); return false; } }
3abf6aa3-fec7-4d54-8127-0b93bb3f8432
9
public void setSelectedTimezone(String timezone){ Regions selectedTimezone = Regions.valueOf(timezone); switch (selectedTimezone){ case Simplified: updateForStandard(); break; case All: updateForAll(); break; case Africa: updateForAfrica(); break; case America: updateForAmerica(); break; case Asia: updateForAsia(); break; case Australia: updateForAustralia(); break; case Europe: updateForEurope(); break; case Pacific: updateForPacific(); break; case US: updateForUs(); break; default: updateForStandard(); } }
8d3e99ed-4f9e-40ce-8f78-c249477bb5d9
8
public void parse( InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, TikaException, SAXException { // Process the file straight through once OggFile ogg = new OggFile(stream); // To track the streams we find Map<OggStreamType, Integer> streams = new HashMap<OggStreamType, Integer>(); Map<OggStreamType.Kind, Integer> streamKinds = new HashMap<OggStreamType.Kind, Integer>(); List<Integer> sids = new ArrayList<Integer>(); int totalStreams = 0; // Start XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startDocument(); // Check the streams in turn OggPacketReader r = ogg.getPacketReader(); OggPacket p; while( (p = r.getNextPacket()) != null ) { if (p.isBeginningOfStream()) { totalStreams++; sids.add(p.getSid()); OggStreamType type = OggStreamIdentifier.identifyType(p); Integer prevValue = streams.get(type); if (prevValue == null) { prevValue = 0; } streams.put(type, (prevValue+1)); prevValue = streamKinds.get(type.kind); if (prevValue == null) { prevValue = 0; } streamKinds.put(type.kind, (prevValue+1)); } } // Report about the streams, which is all we really can do metadata.add("streams-total", Integer.toString(totalStreams)); for (OggStreamType type : streams.keySet()) { String key = type.mimetype.substring(type.mimetype.indexOf('/')+1); if (key.startsWith("x-")) { key = key.substring(2); } if (type == OggStreamIdentifier.UNKNOWN) { key = "unknown"; } metadata.add("streams-" + key, Integer.toString(streams.get(type))); } for (OggStreamType.Kind kind : streamKinds.keySet()) { String key = kind.name().toLowerCase(); metadata.add("streams-" + key, Integer.toString(streamKinds.get(kind))); } // If we found a skeleton stream, report the relations between the streams // TODO // Finish xhtml.endDocument(); ogg.close(); }
bfa7184e-a142-4df0-837f-1d795079052d
4
public static void rename(Automaton a) { State[] s = a.getStates(); int maxId = s.length - 1; Set untaken = new HashSet(), reassign = new HashSet(Arrays.asList(s)); for (int i = 0; i <= maxId; i++) untaken.add(new Integer(i)); for (int i = 0; i < s.length; i++) if (untaken.remove(new Integer(s[i].getID()))) reassign.remove(s[i]); // Now untaken has the untaken IDs, and reassign has the // states that need reassigning. s = (State[]) reassign.toArray(new State[0]); Iterator it = untaken.iterator(); for (int i = 0; i < s.length; i++) { s[i].setID(((Integer) it.next()).intValue()); } }
2c87aca8-87a0-48db-99ec-55ee367774a4
8
public static int[] getNextPixel(int orientation_index) { // RSLV: find a mathematical expression for the switch statement? int[] dp = new int[2]; // [0]=dx, [1]=dy switch(orientation_index) { case 0: dp[0] = 1; dp[1] = 0; break; case 1: dp[0] = 1; dp[1] = 1; break; case 2: dp[0] = 0; dp[1] = 1; break; case 3: dp[0] = -1; dp[1] = 1; break; case 4: dp[0] = -1; dp[1] = 0; break; case 5: dp[0] = -1; dp[1] = -1; break; case 6: dp[0] = 0; dp[1] = -1; break; case 7: dp[0] = 1; dp[1] = -1; break; } return dp; }
19378310-b63a-425a-ac60-6802422e07df
7
public boolean checkDuplicate(String checkThis, int choice) throws ClassNotFoundException, SQLException { String query = ""; if(choice == 0) query = "select suppvname from supplier where suppvname='"+checkThis+"'"; else if(choice==1)//mabelle query = "select compvname from company where compvname-='"+checkThis+"'"; else if(choice==2)//mabelle query = "select billid from or_hdr where billid='"+checkThis+"'"; else if(choice==3)//mabelle query = "select orno from or_hdr where orno='"+checkThis+"'"; PreparedStatement stmt = null; Connection con = null; ResultSet rs; try { Class.forName(DATABASE_CLASS); con = DriverManager.getConnection (DATABASE_URL, DATABASE_NAME, DATABASE_PASSWORD); stmt = con.prepareStatement(query); } catch (SQLException e) { } try { rs = stmt.executeQuery(query); if(!rs.next()) { con.close(); return true; } } catch (SQLException e) { e.printStackTrace(); } con.close(); return false; }
f76c6766-49c5-459b-86b5-28b74f875f91
8
@Override public void mouseDragged(MouseEvent e) { // TODO Auto-generated method stub /*System.out.println("Mouse: (" + e.getX() + ", " + e.getY() + ")"); System.out.println("MouseOnScreen: (" + e.getXOnScreen() + ", " + e.getYOnScreen() + ")"); System.out.println("Pane: (" + this.getX() + ", " + this.getY() + ")"); */ /*if(clicked && rollerClicked && App.state == pointerState.ROLLER && e.getButton()!=MouseEvent.BUTTON3) { System.out.println("Dragging."); if(e.getYOnScreen() != lastScreenY) { App.robot.mouseMove(e.getXOnScreen(), lastScreenY); } if(e.getX()<0) { App.robot.mouseMove(this.getLocationOnScreen().x, lastY); //horizontalScrollBar. } else if(e.getX() >this.getWidth()) { App.robot.mouseMove(this.getLocationOnScreen().x+this.getWidth(), lastY); } //this.getGraphics().setColor(Color.); Color c = Color.BLACK; Graphics g = this.getGraphics(); //this.getGraphics().setColor(c); g.setColor(c); System.out.println(g.getColor() + " " + (Color)App.colorsBox.getSelectedItem()); g.fillRect(lastX, lastY+10, e.getX()-lastX, 8); } else */ if(clicked && (App.state == pointerState.DRAW || App.state == pointerState.EXCLUSION) && e.getButton()!=MouseEvent.BUTTON3) { //System.out.println("Dragging."); if(e.getYOnScreen() != lastScreenY) { App.robot.mouseMove(e.getXOnScreen(), lastScreenY); } if(e.getX()<0) { App.robot.mouseMove(this.getLocationOnScreen().x, lastY); //horizontalScrollBar. } else if(e.getX() >this.getWidth()) { App.robot.mouseMove(this.getLocationOnScreen().x+this.getWidth(), lastY); } Graphics g = this.getGraphics(); if(App.state == pointerState.DRAW) { Color c = (Color)App.colorsBox.getSelectedItem(); //this.getGraphics().setColor(c); g.setColor(c); System.out.println(g.getColor() + " " + (Color)App.colorsBox.getSelectedItem()); } else { Color c = Color.GRAY; g.setColor(c); } g.fillRect(lastX, lastY, e.getX()-lastX, 16); } }
18cd6f0c-8b1a-4105-bb8f-27ed734c3eb4
6
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LinkedThread that = (LinkedThread) o; if (id != that.id) return false; if (headLine != null ? !headLine.equals(that.headLine) : that.headLine != null) return false; return true; }
bcf7ed61-4278-45c5-9539-f64f859db008
1
private boolean jj_3_6() { if (jj_3R_24()) return true; return false; }
6ccd4b4f-766d-41de-a214-31d16f1cd597
5
public <T> ObjectConstructor<T> get(TypeToken<T> typeToken) { final Type type = typeToken.getType(); final Class<? super T> rawType = typeToken.getRawType(); // first try an instance creator @SuppressWarnings("unchecked") // types must agree final InstanceCreator<T> typeCreator = (InstanceCreator<T>) instanceCreators.get(type); if (typeCreator != null) { return new ObjectConstructor<T>() { public T construct() { return typeCreator.createInstance(type); } }; } // Next try raw type match for instance creators @SuppressWarnings("unchecked") // types must agree final InstanceCreator<T> rawTypeCreator = (InstanceCreator<T>) instanceCreators.get(rawType); if (rawTypeCreator != null) { return new ObjectConstructor<T>() { public T construct() { return rawTypeCreator.createInstance(type); } }; } ObjectConstructor<T> defaultConstructor = newDefaultConstructor(rawType); if (defaultConstructor != null) { return defaultConstructor; } ObjectConstructor<T> defaultImplementation = newDefaultImplementationConstructor(type, rawType); if (defaultImplementation != null) { return defaultImplementation; } // finally try unsafe return newUnsafeAllocator(type, rawType); }
2bc2be87-1ad6-4276-84e1-f21e74c3f735
7
public static Rule_EQ parse(ParserContext context) { context.push("EQ"); boolean parsed = true; int s0 = context.index; ArrayList<Rule> e0 = new ArrayList<Rule>(); Rule rule; parsed = false; if (!parsed) { { ArrayList<Rule> e1 = new ArrayList<Rule>(); int s1 = context.index; parsed = true; if (parsed) { boolean f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { rule = Terminal_NumericValue.parse(context, "%x3d", "[\\x3d]", 1); if ((f1 = rule != null)) { e1.add(rule); c1++; } } parsed = c1 == 1; } if (parsed) e0.addAll(e1); else context.index = s1; } } rule = null; if (parsed) rule = new Rule_EQ(context.text.substring(s0, context.index), e0); else context.index = s0; context.pop("EQ", parsed); return (Rule_EQ)rule; }
d04cd76b-c0a8-4744-a7e0-e570306ebaca
5
public void update(Observable o, Object arg1) { if (arg1 != null && arg1 instanceof String && ((String) arg1).contains("VS")) // View settings updates { m_frame.remove(m_centerPanel); m_centerPanel.removeAll(); if (ViewPreferences.getInstance().getCenterView() == CenterView.WEEK) m_centerPanel.add(m_weekView, BorderLayout.CENTER); else if (ViewPreferences.getInstance().getCenterView() == CenterView.LIST) m_centerPanel.add(m_listView, BorderLayout.CENTER); else m_centerPanel.add(m_taskListView, BorderLayout.CENTER); m_centerPanel.add(m_viewToolBar.getUI(), BorderLayout.NORTH); m_frame.add(m_centerPanel, BorderLayout.CENTER); m_frame.revalidate(); m_frame.repaint(); } m_frame.setTitle(ApplicationSettings.getInstance().getLocalizedMessage("window.title")); }
2699a4fc-0036-4fcf-b19f-e25289837e3b
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(StartProgramFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(StartProgramFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(StartProgramFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(StartProgramFrame.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 StartProgramFrame().setVisible(true); } }); }
e14a9200-bebf-45ea-8c02-72a0c8ac3ef3
9
int insertKeyRehash(float val, int index, int hash, byte state) { // compute the double hash final int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (state == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } state = _states[index]; // A FREE slot stops the search if (state == FREE) { if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } else { consumeFreeSlot = true; insertKeyAt(index, val); return index; } } if (state == FULL && _set[index] == val) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); }
87d5b392-209b-44cd-bc8c-8afc8e3ea54a
0
public void setOutlinerDocument(OutlinerDocument doc) { super.setDocument(doc); }
d7755200-523b-41f6-ba34-07fac01e1006
2
public boolean siirtoTormays(int xMuutos){ Palikka[][] pelipalikat = peli.getPalikkaTaulukko(); for (Palikka palikka : this.palikat) { if (pelipalikat[palikka.getY()][palikka.getX()+xMuutos] != null){ return true; } } return false; }
f512706c-a1da-480f-8156-c048b576a97e
3
@Override public void run (){ String line; BufferedReader fromClient; DataOutputStream toClient; boolean verbunden = true; System.out.println("Thread started: "+this); // Display Thread-ID try{ fromClient = new BufferedReader // Datastream FROM Client (new InputStreamReader(client.getInputStream())); toClient = new DataOutputStream (client.getOutputStream()); // TO Client while(verbunden){ // repeat as long as connection exists line = fromClient.readLine(); // Read Request parseFromClient(line); System.out.println("Received: "+ line); if (line.equals(".")) verbunden = false; // Break Conneciton? else toClient.writeBytes(line.toUpperCase()+'\n'); // Response } fromClient.close(); toClient.close(); client.close(); // End System.out.println("Thread ended: "+this); }catch (Exception e){System.out.println(e);} }
01c5bf19-df01-438a-a592-6322807edf66
8
@Parameters({"browser"}) @Test(groups = {"newaccount"}) @BeforeClass public void beforeClass(String browser) throws IOException, InterruptedException { if (browser.equals("firefox")) { driver=browserFirefox(); } if (browser.equals("chrome")) { driver=browserChrome(); } if (browser.equals("ie9")) { driver=browserIE9(); } if (browser.equals("iPad")) { driver=browserIpad(); } if (browser.equals("safari")) { driver=browserSafari(); } if (browser.equals("Android")) { driver=browserAndroid(); } System.out.println("Let me see which one get tested " +browser); System.out.println("Let me run get driver "+driver); String name=""+ browser+"/CreateAccount/" + timeStamp + "_" + "Successful-Created-Account.png"; fail=""+ browser+"/Failed/" + timeStamp + "_" + "create_account.png"; baseUrl = "http://stage.coffee-mate.com"; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.get("http://stage.coffee-mate.com/Registration/Create-Account.aspx?email=" + timeStamp +"%40yahoo.com&stt=True"); //driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_txtFirstName")).clear(); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_txtFirstName")).sendKeys("PubmoTestFirst"); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_txtLastName")).clear(); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_txtLastName")).sendKeys("PubmoTestLast"); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_txtPassword")).clear(); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_txtPassword")).sendKeys("Password123"); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_txtConfirmPassword")).clear(); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_txtConfirmPassword")).sendKeys("Password123"); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_txtAddress")).clear(); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_txtAddress")).sendKeys("1000 BroadwAY LANE"); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_txtAddress2")).clear(); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_txtAddress2")).sendKeys("Suite 3V"); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_txtCity")).sendKeys("New York"); new Select(driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_ddlStates"))).selectByVisibleText("Florida"); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_txtZipCode")).clear(); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_txtZipCode")).sendKeys("10003"); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_chkEmailCommunication")).click(); // driver.findElement(By.name("flavorTheme")).click(); driver.findElement(By.id("ctl00_ContentPlaceHolder1_ucRegisterUser_btnRegister")).click(); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); takeScreen(name); WebDriverWait wait = new WebDriverWait(driver, 30); java.util.List<WebElement> results=wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.id("ctl00_ContentPlaceHolder1_lvQuestions_ctrl0_ucSurveyQuestion_ddlAnswers"))); new Select(driver.findElement(By.id("ctl00_ContentPlaceHolder1_lvQuestions_ctrl0_ucSurveyQuestion_ddlAnswers"))).selectByVisibleText("0"); driver.findElement(By.cssSelector("option[value=\"1E4C6A78-1980-459F-BE01-049AB4CB432C\"]")).click(); long end = System.currentTimeMillis() + 5000; while (System.currentTimeMillis() < end) { WebElement resultsDiv = driver.findElement(By.id("ctl00_ContentPlaceHolder1_lvQuestions_ctrl1_ucSurveyQuestion_ddlAnswers")); // If results have been returned, the results are displayed in a drop down. if (resultsDiv.isDisplayed()) { System.out.println("I found the element"); new Select(driver.findElement(By.id("ctl00_ContentPlaceHolder1_lvQuestions_ctrl1_ucSurveyQuestion_ddlAnswers"))).selectByVisibleText("0"); break; } } driver.findElement(By.cssSelector("option[value=\"138A6025-F98D-4A64-B36C-4A08DAB4F075\"]")).click(); driver.findElement(By.id("ctl00_ContentPlaceHolder1_btnSubmit")).click(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); Thread.sleep(4000); takeScreen(name); //Reporter.log("<a href='"+ local+"/" + name + "'> <img src='"+ local+"/"+ name + " ' height='100' width='100'/>" + "<a href='"+ urlname+"'>'"+ urlname+"'</a> " + " </a>"); //Reporter.log("<a href='"+ safe+"/" + name + "'> <img src='"+ safe+"/"+ name + " ' height='100' width='100'/>" + "<a href='"+ myTitle+"'>'"+ myTitle+"'</a> " + " </a>"); }
de79ea93-afd0-47e9-8f15-bd674d0dde37
2
public Bird(Vector2 position, float radius, Vector2 velocity, float maxSpeed, Vector2 heading, float mass, Vector2 scale, float turnRate, float maxForce, BirdMinigame minigame) { super(position, radius, velocity, maxSpeed, heading, mass, scale, turnRate, maxForce); behavior = new SteeringBehavior(this); //behavior.addBehavior(new HideBehavior(this, minigame.obstacles)); //behavior.addBehavior(new Explore(this)); //behavior.addBehavior(new HideBehavior(this, minigame.obstacles)); availableBehaviors.put(0, new ArriveBehavior(this)); availableBehaviors.put(1, new FleeBehavior(this)); availableBehaviors.put(2, new SeekBehavior(this)); availableBehaviors.put(3, new ExploreBehavior(this)); availableBehaviors.put(4, new HideBehavior(this, minigame.obstacles)); for(int i = 0; i < availableBehaviors.size(); i++) { enabledBehaviors.put(i, false); } try { birdSheet = new SpriteSheet("res/sprites/birdminigame/bird.png", 40, 40); birdLeft = new Animation(birdSheet, 0, 0, 2, 0, true, 150, true); birdRight = new Animation(birdSheet, 0, 1, 2, 1, true, 150, true); birdLeft.setPingPong(true); birdRight.setPingPong(true); currentAnimation = birdRight; } catch (SlickException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
9c6b940f-3651-45df-b7c7-0fd3dcc2cb0c
2
private void checkSymbolInRange(int symbol) { if (symbol < 0 || symbol >= getSymbolLimit()) throw new IllegalArgumentException("Symbol out of range"); }
bbf2d631-6dc5-4a5c-9bab-4dff5ba79516
7
public void run() { int frames = 0; int tickCount = 0; double delta = 0; double secondsPerTick = 1 / 60.0; long lastTime = System.nanoTime(); requestFocus(); while(running) { long now = System.nanoTime(); long elapsedTime = now - lastTime; lastTime = now; if (elapsedTime < 0) elapsedTime = 0; if (elapsedTime > 100000000) elapsedTime = 100000000; delta += elapsedTime / 1000000000.0; boolean ticked = false; while (delta > secondsPerTick) { tick(); delta -= secondsPerTick; ticked = true; tickCount++; if (tickCount % 60 == 0) { System.out.println(frames + " fps"); lastTime += 1000; frames = 0; } } if (ticked) { render(); frames++; } else { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }
e4ede3ea-e39f-4bea-9645-b324b4d7bd40
1
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; if (!isTokenValid(request)) { ((HttpServletResponse) resp).sendRedirect("/error.ctrl"); } saveToken(request); chain.doFilter(req, resp); }
2df56b6a-f650-4d5a-9c6d-b2e7c842c4a5
4
public static boolean contains( Object[] array, Object value ) { if( array == null || value == null ) return( false ); for( int i = 0; i < array.length; i++ ) { if( value.equals( array[ i ] ) ) return( true ); } return( false ); }
8f0bdcc0-7817-45a2-bd37-8adfdc4cfee1
9
private void shortLoop(Raster source, Raster dest, Rectangle destRect, int incr1, int incr2, int s_x, int s_y) { MultiPixelPackedSampleModel sourceSM = (MultiPixelPackedSampleModel)source.getSampleModel(); DataBufferUShort sourceDB = (DataBufferUShort)source.getDataBuffer(); int sourceTransX = source.getSampleModelTranslateX(); int sourceTransY = source.getSampleModelTranslateY(); int sourceDataBitOffset = sourceSM.getDataBitOffset(); int sourceScanlineStride = sourceSM.getScanlineStride(); MultiPixelPackedSampleModel destSM = (MultiPixelPackedSampleModel)dest.getSampleModel(); DataBufferUShort destDB = (DataBufferUShort)dest.getDataBuffer(); int destMinX = dest.getMinX(); int destMinY = dest.getMinY(); int destTransX = dest.getSampleModelTranslateX(); int destTransY = dest.getSampleModelTranslateY(); int destDataBitOffset = destSM.getDataBitOffset(); int destScanlineStride = destSM.getScanlineStride(); short[] sourceData = sourceDB.getData(); int sourceDBOffset = sourceDB.getOffset(); short[] destData = destDB.getData(); int destDBOffset = destDB.getOffset(); int dx = destRect.x; int dy = destRect.y; int dwidth = destRect.width; int dheight = destRect.height; int sourceOffset = 16*(s_y - sourceTransY)*sourceScanlineStride + 16*sourceDBOffset + (s_x - sourceTransX) + sourceDataBitOffset; int destOffset = 16*(dy - destTransY)*destScanlineStride + 16*destDBOffset + (dx - destTransX) + destDataBitOffset; for (int j = 0; j < dheight; j++) { int sOffset = sourceOffset; int dOffset = destOffset; int selement, val, dindex, delement; int i = 0; while ((i < dwidth) && ((dOffset & 15) != 0)) { selement = sourceData[sOffset >> 4]; val = (selement >> (15 - (sOffset & 15))) & 0x1; dindex = dOffset >> 4; int dshift = 15 - (dOffset & 15); delement = destData[dindex]; delement |= val << dshift; destData[dindex] = (short)delement; sOffset += incr1; ++dOffset; ++i; } dindex = dOffset >> 4; if ((incr1 & 15) == 0) { int shift = 15 - (sOffset & 5); int offset = sOffset >> 4; int incr = incr1 >> 4; while (i < dwidth - 15) { delement = 0; for (int b = 15; b >= 0; b--) { selement = sourceData[offset]; val = (selement >> shift) & 0x1; delement |= val << b; offset += incr; } destData[dindex] = (short)delement; sOffset += 16*incr1; dOffset += 16; i += 16; ++dindex; } } else { while (i < dwidth - 15) { delement = 0; for (int b = 15; b >= 0; b--) { selement = sourceData[sOffset >> 4]; val = (selement >> (15 - (sOffset & 15))) & 0x1; delement |= val << b; sOffset += incr1; } destData[dindex] = (short)delement; dOffset += 15; i += 16; ++dindex; } } while (i < dwidth) { selement = sourceData[sOffset >> 4]; val = (selement >> (15 - (sOffset & 15))) & 0x1; dindex = dOffset >> 4; int dshift = 15 - (dOffset & 15); delement = destData[dindex]; delement |= val << dshift; destData[dindex] = (short)delement; sOffset += incr1; ++dOffset; ++i; } sourceOffset += incr2; destOffset += 16*destScanlineStride; } }
2261c7d4-a8b3-4379-9659-847ab19e9f07
2
public static Connection getWDMRConnetion(final String url, final String database// , final String user, final String password// ) { final String connetUrl = JDBCConnector.JDBC_URI_MYSQL + url + "/" + database; try { Class.forName(JDBCConnector.JDBC_DRIVER_MYSQL); Connection conn = DriverManager.getConnection(connetUrl, user, password); return conn; } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { System.out.println("DB driver classes were not found."); e.printStackTrace(); } System.out.println("Connect DB failed."); return null; //TODO sould return error messge object }
fc455d8c-121d-4ddb-a454-6dbea551cb91
9
final void method3505(boolean bool, int i, int i_84_, boolean bool_85_, int i_86_, boolean bool_87_, int i_88_) { if (bool_85_ != true) ((Class361) this).anInt4453 = 116; anInt4434++; int i_89_ = 256; if (bool_87_) i_89_ |= 0x20000; i_86_ -= ((Class361) this).anInt4453; i_84_ -= ((Class361) this).anInt4441; if (bool) i_89_ |= 0x40000000; for (int i_90_ = i_86_; i_86_ + i > i_90_; i_90_++) { if ((i_90_ ^ 0xffffffff) <= -1 && ((((Class361) this).anInt4437 ^ 0xffffffff) < (i_90_ ^ 0xffffffff))) { for (int i_91_ = i_84_; (i_84_ + i_88_ ^ 0xffffffff) < (i_91_ ^ 0xffffffff); i_91_++) { if (i_91_ >= 0 && ((Class361) this).anInt4443 > i_91_) method3494(i_90_, i_89_, i_91_, -6496); } } } }
aa6acdb5-6ab4-4b1f-808a-ce6286113ec5
4
void kill () { if (Windows.trace) System.err.println ("kill bus" + this); // notify any listeners that the bus died, and // clear backlinks that we control if (listeners.size () > 0) { synchronized (devices) { for (int i = 0; i < devices.length; i++) { if (devices [i] == null) continue; removed (devices [i]); } } } }
dfbfa907-4269-4f72-8db3-2682bd0513a6
7
public static boolean[] nextPosition(boolean switches[], int numTrue){ String value = ""; boolean retSwitches[] = new boolean [switches.length]; for(int i = 0; i < switches.length; i++){ value += switches[i] == true ? 1 : 0; } value = value.replaceAll( "[^\\d]", "" ); int currentValue = Integer.parseInt(value,2); int count = 0; do{ currentValue += 1; //System.err.println("currentValue = " + currentValue); String test = new String(Integer.toBinaryString(currentValue) + ""); //System.err.println("currentValue = " + test); int length = test.length(); test = test.replaceAll("1", ""); if(length - test.length() == numTrue) break; }while(count < 100); //System.out.println("Next value is " + Integer.toBinaryString(currentValue)); String reverseSwitch = Integer.toBinaryString(currentValue) + ""; int j = switches.length-1; for(int i = reverseSwitch.length()-1; i >= 0; i--){ //System.err.println("i" + i + " revSw:" + reverseSwitch + " value =" + (reverseSwitch.charAt(i) == '1' ? true: false) + " char = " + reverseSwitch.charAt(i)); retSwitches[j] = (reverseSwitch.charAt(i) == '1' ? true: false); j--; } for(; j >=0 ; j--) retSwitches[j] =false; // System.out.println("results : " ); // for(boolean i : retSwitches){ // System.out.print( i == true ? "1" : "0"); // } //System.out.println("Value:" + Integer.toBinaryString(Integer.parseInt(value,2)) + " from " + value + " from " + Integer.parseInt(value,2)); return retSwitches; }
df6847ef-fed5-48ab-9113-6612dbb39ddd
1
public static WriteYCbCr getInstance() { if (writeYCbCrSingleton == null) { writeYCbCrSingleton = new WriteYCbCr(); } return writeYCbCrSingleton; }
585c94ba-2d5f-41a0-9dbc-5ccdf061e594
3
public static int countStringInText(String src, String targetString) { if (isStringNullOrWhiteSpace(src) || isStringNullOrWhiteSpace(targetString)) return 0; int start = 0, index = -1, count = 0; while ((index = src.indexOf(targetString, start)) != -1) { count++; start = index + targetString.length(); } return count; }
02824b80-4144-460f-894e-845b64b92234
2
private void uploadAgenciesData(ArrayList<ArrayList<GenericGtfsData>> all_entities_data, String username, String password){ try{ for (int i=0; i<all_entities_data.size(); i++){ uploadAgencyData(all_entities_data.get(i), username, password); } } catch(Exception e){ _log.error(e.getMessage()); return; } }
0f04b1d4-68e2-44ac-8b9c-6c01197374a0
8
public static int getContactDist(Integer pS, Integer pD, int maxDistLim) { LinkedList<Integer> q = new LinkedList<Integer>(); q.add(pS); HashSet<Integer> visited = new HashSet<Integer>(); visited.add(pS); HashSet<Integer> done = new HashSet<Integer>(); HashMap<Integer,Integer> distances = new HashMap<Integer,Integer>(); distances.put(pS, new Integer(0)); int maxDist = 0; while (q.size() > 0 && maxDist < maxDistLim && !distances.containsKey(pD)) { Integer u = q.poll(); Iterator<Integer> neighbors = getNeighbors(u).iterator(); while (neighbors.hasNext()) { Integer v = neighbors.next(); if (!visited.contains(v) && !done.contains(v)) { int d = distances.get(u).intValue() + 1; distances.put(v, new Integer(d)); visited.add(v); q.add(v); if (d > maxDist) maxDist = d; } } done.add(u); } if (distances.containsKey(pD)) return distances.get(pD).intValue(); else return -1; }
79854b3e-a5f3-49e4-b510-2518a714290c
8
public String evaluate(int i, LinkedList linkedlist) { String s = ""; if(linkedlist == null) return ""; for(ListIterator listiterator = linkedlist.listIterator(0); listiterator.hasNext();) { XMLNode xmlnode = (XMLNode)listiterator.next(); if(xmlnode != null) switch(xmlnode.XMLType) { default: break; case 0: // '\0' case 1: // '\001' try { s = s + processTag(i, xmlnode); } catch(ProcessorException processorexception) { throw new DeveloperError(processorexception.getMessage(), processorexception); } break; case 2: // '\002' case 3: // '\003' s = s + xmlnode.XMLData; break; } } return s; }
b33531fb-0a2e-4abb-b788-d7f79c437197
2
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get register form data String firstname = request.getParameter("firstname"); String lastname = request.getParameter("lastname"); String email = request.getParameter("email"); String password = request.getParameter("password"); //Check database for duplicate email, i.e. account already exists boolean duplicateExists = regService.checkEmail(email); if (duplicateExists) { //If email already exists, return to register page with message request.setAttribute("failureMessage", "User with that email already registered."); request.getRequestDispatcher("register.jsp").forward(request, response); return; } else { //Make new user try { regService.createNewUser(email, firstname, lastname, SecurityUtils.sha1(password)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } response.sendRedirect("login"); //Success, go to login page return; } }
41e4927d-fb16-49bc-9054-7494dba94883
7
public void generateDatasetFromBeginning(String datasetFile, HashMap<String, Integer> files, int numOperations) throws IOException { FileWriter fstream = new FileWriter(datasetFile); BufferedWriter out = new BufferedWriter(fstream); int fileNum = files.values().size() + 1; int totalFiles = fileNum - 1; Object[] filesPath = files.keySet().toArray(); HashSet<String> folders = this.getFoldersFromFilesList(filesPath); ArrayList<Integer> operations = getOperationsListBeginning(numOperations); totalTime = 0; for (int opNum : operations) { switch (opNum % 3) { case 0: // ADD logger.debug("ADD"); int newFileSize = this.random.nextInt(Config.getMaxSize() - Config.getMinSize() + 1) + Config.getMinSize(); boolean created = createFile(newFileSize, fileNum, folders); // Select folder to copy the new file String path = "/"; if (created) { String fileName = "file" + fileNum + ".dat"; int time = this.getWaitTime(); totalTime += time; Add addAction = new Add(totalTime, "/" + fileName, path); files.put(path + fileName, newFileSize); filesPath = files.keySet().toArray(); out.write(addAction.toString()); fileNum++; totalFiles++; } break; case 1: // UPDATE logger.debug("UPDATE"); if (totalFiles <= 0) { continue; } Object fileToModify = filesPath[random.nextInt(totalFiles)]; int fileSize = files.get(fileToModify); this.generateUpdate(out, fileToModify, fileSize); break; case 2: // REMOVE logger.debug("REMOVE"); if (totalFiles <= 0) { continue; } String fileToRemove = (String) filesPath[random.nextInt(totalFiles)]; totalFiles--; files.remove(fileToRemove); filesPath = files.keySet().toArray(); int time = this.getWaitTime(); totalTime += time; Remove remove = new Remove(totalTime, fileToRemove); out.write(remove.toString()); break; } } out.close(); fstream.close(); }
c0d9f425-a07f-4d01-877c-ca6fe463e53b
3
@Override public void render(Graphics2D graphics) { final int startPointGridXCoordinate = 150; final int startPointGridYCoordinate = 20; final Set<Position> positions = objectTron.getElements().keySet(); for (int i = 0; i < objectTron.getGridWidth(); i++) { for (int j = 0; j < objectTron.getGridHeight(); j++) { final Position currentPos = new Position(i, j); Image cellToRender = cell; if (!positions.contains(currentPos)) cellToRender = notongridcell; graphics.drawImage(cellToRender, (i * 41) + startPointGridXCoordinate, (j * 41) + startPointGridYCoordinate, 40, 40, null); } } }
d671f298-bfc3-4382-947a-8abed7b70ce1
6
public VariableCreator() { setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); if(System.getProperty("resources") == null) System.setProperty("resources", System.getProperty("user.dir") + "/resources"); setBounds(100, 100, 450, 300); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); { JSplitPane splitPane = new JSplitPane(); splitPane.setBounds(0, 0, 434, 229); contentPanel.add(splitPane); { JScrollPane scrollPane = new JScrollPane(); splitPane.setLeftComponent(scrollPane); { listModel = new DefaultListModel<String>(); fillList(); list = new JList<String>(listModel); list.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(e.getClickCount() == 2 || e.getButton() == MouseEvent.BUTTON3) { addPopup(e.getX(), e.getY()); } else { if(list.getSelectedIndex() != -1 && list.getSelectedValue() != null) { enableEdit(); } else disableEdit(); } } }); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); scrollPane.setViewportView(list); } } { JPanel panel = new JPanel(); splitPane.setRightComponent(panel); panel.setLayout(null); JLabel lblName = new JLabel("Name:"); lblName.setBounds(10, 11, 46, 14); panel.add(lblName); nameField = new JTextField(); nameField.setEnabled(false); nameField.setBounds(66, 8, 86, 20); panel.add(nameField); nameField.setColumns(10); JSeparator separator = new JSeparator(); separator.setBounds(10, 36, 258, 6); panel.add(separator); JLabel lblString = new JLabel("String:"); lblString.setBounds(10, 53, 46, 14); panel.add(lblString); stringField = new JTextField(); stringField.setEnabled(false); stringField.setBounds(10, 78, 86, 20); panel.add(stringField); stringField.setColumns(10); JLabel lblInteger = new JLabel("Integer:"); lblInteger.setBounds(106, 53, 46, 14); panel.add(lblInteger); intSpinner = new JSpinner(); intSpinner.setEnabled(false); intSpinner.setBounds(106, 78, 86, 20); panel.add(intSpinner); JLabel lblBoolean = new JLabel("Boolean:"); lblBoolean.setBounds(10, 109, 46, 14); panel.add(lblBoolean); booleanBox = new JCheckBox("True"); booleanBox.setEnabled(false); booleanBox.setBounds(10, 130, 86, 23); panel.add(booleanBox); JLabel lblFloat = new JLabel("Float:"); lblFloat.setBounds(106, 109, 46, 14); panel.add(lblFloat); floatSpinner = new JSpinner(); floatSpinner.setEnabled(false); floatSpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); floatSpinner.setBounds(106, 131, 86, 20); panel.add(floatSpinner); save = new JButton("Save"); save.setEnabled(false); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { parseVariable(); } }); save.setBounds(10, 162, 76, 25); panel.add(save); remove = new JButton("Remove"); remove.setEnabled(false); remove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { listModel.remove(list.getSelectedIndex()); list.clearSelection(); disableEdit(); } }); remove.setBounds(106, 162, 76, 25); panel.add(remove); } splitPane.setDividerLocation(0.35); } { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { saveVariables(); } catch (IOException e) { e.printStackTrace(); } dispose(); } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } setModalityType(ModalityType.APPLICATION_MODAL); setVisible(true); }
52d720c4-3d0f-44c0-801b-74bbede4e149
0
public void highlight(int row, int column) { highlight(row, column, THRG); }
1c422510-2e18-4b9c-b8f7-5be7263256c8
7
public void moveSouth() { boolean [] temp = WhenShitHits.Enemy2Setpiece(this, 5); if(temp[2] == false) { if(direction != 5) { direction = 5; anamationFrame = 0; pic = southAnamation()[anamationFrame]; animate = false; if(animationTimer.isRunning()) { animationTimer.restart(); } else { animationTimer.start(); } } else { if(animate == true) { if((anamationFrame + 1) < southAnamation().length) { anamationFrame++; } else { anamationFrame = 0; } pic = southAnamation()[anamationFrame]; animate = false; } } yPos = yPos + speed; } else if(temp[1] == false) { moveEast(); } else if(temp[3] == false) { moveWest(); } else { System.out.println("unable to proceed"); } }
bb730c5f-fee7-441f-af94-9255158ddbac
9
public static boolean initFunctions(Object obj, List<Func> dst, String funcStr) { if (StringUtils.isEmpty(funcStr) || StringUtils.isBlank(funcStr)) { return true; } int PRE_ARGS_NUM = -1; Class<?>[] PRE_ARGS_TYPE = null; try { PRE_ARGS_NUM = obj.getClass().getDeclaredField("PRE_ARGS_NUM").getInt(obj); PRE_ARGS_TYPE = (Class<?>[]) obj.getClass().getDeclaredField("PRE_ARGS_TYPE").get(obj); } catch (IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchFieldException ex) { NoticeMessageJFrame.noticeMessage(ex.getClass() + ":" + ex.getMessage()); } List<String> funcs = getFunctions(funcStr); for (String func : funcs) { String funcName = getFuncName(func); String[] funcParams = getFuncParams(func); Class<?>[] paramsType = new Class[funcParams.length + PRE_ARGS_NUM]; Arrays.fill(paramsType, PRE_ARGS_NUM, paramsType.length, String.class); System.arraycopy(PRE_ARGS_TYPE, 0, paramsType, 0, PRE_ARGS_NUM); try { Method method = obj.getClass().getMethod(funcName, paramsType); //根据函数名 && 参数类型,找到对应的函数 dst.add(new Func(obj, method, PRE_ARGS_NUM, funcParams)); } catch (SecurityException | NoSuchMethodException ex) { NoticeMessageJFrame.noticeMessage(ex.getClass() + ":" + ex.getMessage()); return false; } catch (IllegalArgumentException ex) { NoticeMessageJFrame.noticeMessage(ex.getClass() + ":" + ex.getMessage()); } } return dst.size() > 0; }
559b0662-243c-4d43-a357-c3017442c432
8
private void trySearch(int k) { // loai bo cac o de bai while (k < SIZE * SIZE && matrix[k / SIZE][k % SIZE] != 0) { k++; } if (k == SIZE * SIZE) return; int row = k / SIZE, col = k % SIZE; for (int x = 1; x <= SIZE; x++) { // duyet cac TH if (isOK(row, col, x)) { matrix[row][col] = x; if (k == lastK) { int[][] rs = new int[SIZE][SIZE]; // copy ket qua sang 1 array khac for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { rs[i][j] = matrix[i][j]; } } results.add(rs); // them vao list } else { trySearch(k + 1); } matrix[row][col] = 0; } } }
b4bdee2b-5ea6-4e68-b5a1-d5c99f5c05ea
8
public void calcLightDepths(int var1, int var2, int var3, int var4) { for(int var5 = var1; var5 < var1 + var3; ++var5) { for(int var6 = var2; var6 < var2 + var4; ++var6) { int var7 = this.blockers[var5 + var6 * this.width]; int var8; for(var8 = this.depth - 1; var8 > 0 && !this.isLightBlocker(var5, var8, var6); --var8) { ; } this.blockers[var5 + var6 * this.width] = var8; if(var7 != var8) { int var9 = var7 < var8?var7:var8; var7 = var7 > var8?var7:var8; for(var8 = 0; var8 < this.listeners.size(); ++var8) { ((LevelRenderer)this.listeners.get(var8)).queueChunks(var5 - 1, var9 - 1, var6 - 1, var5 + 1, var7 + 1, var6 + 1); } } } } }
785d0797-62a9-47b9-9331-d9f09eb8779c
7
@Override public HashMap<String, Integer> parsePoints(String seasson, String day) throws IOException { HashMap<String, Integer> playersPoints = new HashMap<String,Integer>(); URL url = new URL(buildURL(seasson, day)); URLConnection uc = url.openConnection(); InputStreamReader input = new InputStreamReader(uc.getInputStream()); BufferedReader in = new BufferedReader(input); String inputLine; boolean print = false; Map<String,Integer> puntuacion = new HashMap<String,Integer>(); while ((inputLine = in.readLine()) != null ){ inputLine = inputLine.trim(); if(inputLine.contains("id=\"table261\"")){ print = true; } if(inputLine.contains("</table>")){ print = false; } if(print && !inputLine.startsWith("<") && !inputLine.startsWith("&")){ String [] parts = inputLine.split("<"); inputLine = parts[0]; System.out.println(inputLine); inputLine = inputLine.trim(); String nombre = inputLine.substring(0,inputLine.lastIndexOf(" ")); String puntosString = inputLine.substring(inputLine.lastIndexOf(" ") + 1 , inputLine.length()); if("sc".equals(puntosString)) puntosString = "0"; int puntos = Integer.parseInt(puntosString); playersPoints.put(nombre, puntos); System.out.println("NOMBRE: " + nombre + " PUNTOS: " + puntos); } } return playersPoints; }
967a2e61-31e8-4b8a-ae5c-4215df13f971
4
public void print(String ans, int leftCount, int rightCount) { if (leftCount == 0 && rightCount == 0) { System.out.println(ans); return; } if (leftCount > 0) { print(ans + "(", leftCount - 1, rightCount); } if (rightCount > leftCount) { print(ans + ")", leftCount, rightCount - 1); } }
e43d09af-7d84-4c73-a865-8f806cac2be9
1
@Override public void start() throws Exception { String[] args= this.par.getArgs(); int inputNumberValues= args.length - 1; //-1 for command word if(inputNumberValues != 3) throw new Exception("Incorrect input for kmeans"); int clusterNumber= Integer.valueOf(args[1]); int maxIter= Integer.valueOf(args[2]); String dir= args[3]; System.out.println("KMEANS CLUSTERING STARTED: Please wait..."); KMeans kmeans= new KMeans(clusterNumber, maxIter, dir); kmeans.execute(); System.out.println("KMEANS CLUSTERING COMPLETED"); }
1a33d94a-3b6a-4a22-888a-94cc35101cb5
1
@Override public List<Integer> sort(List<Integer> list) { // checking input parameter for null if (list == null) { throw new IllegalArgumentException("Disallowed value"); } int low = 0; return sortPartition(list, low, list.size() - 1); }
df1b8325-e157-404a-ae02-65a9e5522acb
7
@Override public boolean tick(Tickable ticking, int tickID) { if(!(affected instanceof MOB)) return super.tick(ticking,tickID); final MOB mob=(MOB)affected; if((CMLib.flags().isStanding(mob)) &&(mob.isInCombat()) &&((mob.fetchAbility(ID())==null)||proficiencyCheck(null,0,false)) &&(tickID==Tickable.TICKID_MOB)) { setActivated(true); if(CMLib.dice().rollPercentage()==1) helpProficiency(mob, 0); } else setActivated(false); return super.tick(ticking,tickID); }
e2fcfd8d-bcef-4629-8811-6963822ee7b1
2
public static boolean validPalindrome(int n) { final String numberToString = Integer.toString(n); final int length = numberToString.length(); for (int i = 0; i <= (int) length / 2; i++) { if (!(numberToString.charAt(i) == numberToString.charAt((length - 1) - i))) { return false; } } return true; }
b23bd071-56bc-479f-b660-ca443a219616
2
public void method280(int tileZ, int z, int y, Entity entity, byte objectConfig, int uid, int x) { if (entity == null) { return; } GroundDecoration groundDecoration = new GroundDecoration(); groundDecoration.entity = entity; groundDecoration.x = x * 128 + 64; groundDecoration.y = y * 128 + 64; groundDecoration.z = z; groundDecoration.uid = uid; groundDecoration.objectConfig = objectConfig; if (groundTiles[tileZ][x][y] == null) { groundTiles[tileZ][x][y] = new GroundTile(tileZ, x, y); } groundTiles[tileZ][x][y].groundDecoration = groundDecoration; }
cb9253d2-4c77-4288-967f-d1ee48d66c6e
9
@Override protected void xread_activated (Pipe pipe_) { // There are some subscriptions waiting. Let's process them. Msg sub = null; while ((sub = pipe_.read()) != null) { // Apply the subscription to the trie. byte[] data = sub.data(); int size = sub.size (); if (size > 0 && (data[0] == 0 || data[0] == 1)) { boolean unique; if (data[0] == 0) unique = subscriptions.rm (data , 1, pipe_); else unique = subscriptions.add (data , 1, pipe_); // If the subscription is not a duplicate, store it so that it can be // passed to used on next recv call. (Unsubscribe is not verbose.) if (options.type == ZMQ.ZMQ_XPUB && (unique || (data[0] == 1 && verbose))) pending.add (new Blob (sub.data ())); } } }
dc494f8d-b7af-4d30-9f60-2c9623d6b6a7
9
public Trace getTrace_v3(int xStart, int yStart, int sourceID, int threshold) { // Multiple query to be created based on threshold: String multiQuery = ""; for (int i=0; i < threshold; i++) { for (int j=0; j < threshold; j++) { multiQuery += MACRO_QUERY; }//for }//for // the returned queried value from database: byte [] samples = null; // the returned Trace object: Trace trace = null; // ResultSet objects: ResultSet resultSet; try { // Creating a PreparedStatement object PreparedStatement pStatement = con.prepareStatement(multiQuery); //System.out.println("PreparedStatement object created. \n"); try { // set parameters of the statement: int counter = 1; for (int i=0; i < threshold; i++) { for (int j=0; j < threshold; j++) { pStatement.setInt(counter++, (xStart+i)); pStatement.setInt(counter++, (yStart+j)); pStatement.setInt(counter++, sourceID); }//for }//for // [TEST] measure execution time: long startTime = System.currentTimeMillis(); // run the multiple query in one go: pStatement.execute(); // [TEST] get end time and print: long endTime = System.currentTimeMillis(); //FESVoSystem.out.println("Executed multi-statement query in: " + (endTime - startTime) + " ms."); FESVoSystem.out.print((endTime - startTime) + " "); // get result sets: loop: for (int i=0; i < threshold; i++) { for (int j=0; j < threshold; j++) { // [TEST] measure execution time: //startTime = System.currentTimeMillis(); // get result set resultSet = pStatement.getResultSet(); // [TEST] get end time and print: //endTime = System.currentTimeMillis(); System.out.println("Time: " + (endTime - startTime) + " ms."); // get the value of the property value column: // if no row is available, return null if (resultSet.next()){ samples = resultSet.getBytes(1); trace = new Trace(xStart+i, yStart+j, sourceID); trace.setSamples(samples); break loop; }//if // move to next result set: pStatement.getMoreResults(); }//for (j) }//for (i) }//try finally { // Close the statement pStatement.close(); //System.out.println("Statement object closed. \n"); }//finally }//try catch(SQLException ex) { // A SQLException was generated. Catch it and display // the error information. // Note that there could be multiple error objects chained // together. System.out.println(); System.out.println("*** SQLException caught ***"); while (ex != null) { System.out.println(" Error code: " + ex.getErrorCode()); System.out.println(" SQL State: " + ex.getSQLState()); System.out.println(" Message: " + ex.getMessage()); ////ex.printStackTrace(); System.out.println(); ex = ex.getNextException(); } throw new IllegalStateException ("Sample failed.") ; }//catch // return the retrieved samples as a byte array return trace; }//getTrace
a6d53d7f-d261-47a4-8cbc-32dca64a8ead
0
private Set<Card> threeSevensAndAceKing() { return convertToCardSet("3S,AS,KD,9S,TD,3C,3H"); }
43f41ba3-af98-4ea8-8b8c-563a923c447d
6
public void discard(int amount) { System.out.println("Discarding"); GeometryFactory factory = Helper.getGeometryFactory(); LinkedList<LabelGeneOverlap> overlappingGenes = new LinkedList<LabelGeneOverlap>(); for (int geneI = this.size() - 1; geneI > 0; geneI--) { LabelGene gene = this.get(geneI); double overlapArea = getGeneOverlap(gene, factory); if (overlapArea > 0) { overlappingGenes.add(new LabelGeneOverlap(gene, overlapArea)); } } Collections.sort(overlappingGenes); Geometry clearedArea = null; for(int geneI=0; geneI<amount; geneI++){ LabelGene gene = overlappingGenes.get(geneI).getGene(); if(clearedArea == null){ clearedArea = gene.getGeometry(); } else { clearedArea = clearedArea.union(gene.getGeometry()); } gene.discard(); genes.remove(gene); } for(LabelGene gene:this){ Geometry geneGeometry = gene.getGeometry(); if(geneGeometry.intersects(clearedArea)){ gene.mutate(); } } }
7d45717f-e400-4191-a2ad-a628975541b2
5
public void checkCustomDown(Node node) { this.down = -1; // reset value to -1 // Prevent out of bounds if((node.getX()+2) < this.size.getX()) { if(checkWall(new Node( (node.getX()+2), (node.getY()) ))) { if(this.closedNodes.size()==0) this.down = 1; else { for(int i = 0; i < this.closedNodes.size(); i++) { // Check with closed nodes to differenciate explored or not if(new Node(node.getX()+2, node.getY()).compareTo(this.closedNodes.get(i))==1) { this.down = 2; // explored node break; } else this.down = 1; // empty } } } else { this.down = 0; // set 0 to specify as wall } } }
5c579570-7966-40ee-bfc9-3e7612240a9a
6
@Override public void actionPerformed(ActionEvent e) { //System.out.println("SelectAllAction"); OutlinerCellRendererImpl textArea = null; boolean isIconFocused = true; Component c = (Component) e.getSource(); if (c instanceof OutlineButton) { textArea = ((OutlineButton) c).renderer; } else if (c instanceof OutlineLineNumber) { textArea = ((OutlineLineNumber) c).renderer; } else if (c instanceof OutlineCommentIndicator) { textArea = ((OutlineCommentIndicator) c).renderer; } else if (c instanceof OutlinerCellRendererImpl) { textArea = (OutlinerCellRendererImpl) c; isIconFocused = false; } // Shorthand Node node = textArea.node; JoeTree tree = node.getTree(); OutlineLayoutManager layout = tree.getDocument().panel.layout; //System.out.println(e.getModifiers()); switch (e.getModifiers()) { case 2: if (isIconFocused) { selectAll(node, tree, layout); } else { selectAllText(node, tree, layout); } break; } }
e68eb51a-1ac3-4045-863c-3630697c2702
2
public AccountTypes() { AccountType active = new AccountType(); active.setName(ASSET); // active.setName(getBundle("Balances").getString("ASSET")); AccountType passive = new AccountType(); passive.setName(LIABILITY); // passive.setName(getBundle("Balances").getString("LIABILITY")); passive.setInverted(true); AccountType cost = new AccountType(); cost.setName(COST); // cost.setName(getBundle("Balances").getString("COST")); AccountType revenue = new AccountType(); revenue.setName(REVENUE); // revenue.setName(getBundle("Balances").getString("REVENUE")); revenue.setInverted(true); AccountType credit = new AccountType(); credit.setName(CREDIT); // credit.setName(getBundle("Balances").getString("FUND_FROM_CUSTOMER")); AccountType debit = new AccountType(); debit.setName(DEBIT); // debit.setName(getBundle("Balances").getString("DEBT_TO_SUPPLIER")); debit.setInverted(true); try{ addBusinessObject(active); addBusinessObject(passive); addBusinessObject(cost); addBusinessObject(revenue); addBusinessObject(credit); addBusinessObject(debit); } catch (EmptyNameException e) { System.err.println("The Name of an AccountType can not be empty."); } catch (DuplicateNameException e) { System.err.println("The Name of an AccountType already exists."); } }
12bceb5d-7ba5-4e31-8626-6f520050c244
8
@Override public MoonPhase getMoonPhase(Room room) { int moonDex = (int)Math.round(Math.floor(CMath.mul(CMath.div(getDayOfMonth(),getDaysInMonth()+1),8.0))); if(room != null) { final Area area = room.getArea(); if((room.numEffects()>0) || ((area != null)&&(area.numEffects()>0))) { final List<Ability> moonEffects = new ArrayList<Ability>(1); if(room.numEffects()>0) moonEffects.addAll(CMLib.flags().domainAffects(room, Ability.DOMAIN_MOONALTERING)); if((area != null)&&(area.numEffects()>0)) moonEffects.addAll(CMLib.flags().domainAffects(area, Ability.DOMAIN_MOONALTERING)); for(Ability A : moonEffects) moonDex = (moonDex + A.abilityCode()) % 8; } } return TimeClock.MoonPhase.values()[moonDex]; }
00de14d0-c3bb-4941-8d22-fee745a6518c
1
protected <T> String toJson(final T object) { if (object == null) { throw new IllegalArgumentException("object parameter is null"); } Gson gson = GsonFactory.create(); return gson.toJson(object); }
75b83725-77ef-48ba-b51d-61a5c215ddac
6
public List<String> getSortedFundCodes(String type, int top, SortMethod sortMethod){ List<String> candidates = new ArrayList<String>(); if(mapBasicInfos == null){ mapBasicInfos = new HashMap<String, List<String>>(); for(String[] basicInfo : basicInfos){ List<String> data = new ArrayList<String>(); data.add(basicInfo[0]); data.add(basicInfo[1]); data.add(basicInfo[2]); data.add(basicInfo[3]); mapBasicInfos.put(basicInfo[0], data); } } for(List<String> mapBasicInfo : mapBasicInfos.values()){ if(!type.equals("全部")){ if(mapBasicInfo.get(3).equals(type)){ candidates.add(mapBasicInfo.get(0)); } } else{ candidates.add(mapBasicInfo.get(0)); } } candidates = sortMethod.sort(candidates); return candidates.size()>top?candidates.subList(0, top):candidates; }
ab184bdb-135f-470b-a353-81ba4813cfa0
0
protected Icon getIcon() { java.net.URL url = getClass().getResource("/ICON/blocks.gif"); return new javax.swing.ImageIcon(url); }
335084f8-e7a6-4b0d-a708-8654984d27a1
8
private void sortTuts() { ArrayList<Timeslot>overfilledTuts; for(Student s: students){ if(!s.getFlaggedForTuts()){ s.setAssignedTut(s.getCombinedTuts().get(0)); s.getCombinedTuts().get(0).addStudent(s); } } Student currentStudent; overfilledTuts=overFilledTuts(); while(!overfilledTuts.isEmpty()){ for(Timeslot t: overfilledTuts){ for(int i=t.getPreferredMax();i<t.getAssigned().size();i++){ currentStudent=t.getAssigned().get(i); if(currentStudent.getCurrentIndexTuts()+1<currentStudent.getCombinedTuts().size()){ currentStudent.getCurrentTut().removeStudent(currentStudent); currentStudent.incrementIndexTuts(); currentStudent.getCurrentTut().addStudent(currentStudent); currentStudent.setAssignedTut(currentStudent.getCurrentTut()); } else{ if(currentStudent.getAssignedTut()!=null){ currentStudent.getAssignedTut().removeStudent(currentStudent); currentStudent.setAssignedTut(null); } currentStudent.setFlaggedForTuts(true); if(!flagged.contains(currentStudent)){ flagged.add(currentStudent); } } } overfilledTuts=overFilledTuts(); } } }
de4a4554-dd1a-462e-ad49-d24f791e9ab9
1
public final Image loadImage(String url, int width, int height) { Image image = panel.getToolkit().createImage(ClassLoader.getSystemResource(url)); MediaTracker tracker = new MediaTracker(panel); tracker.addImage(image, 1, width, height); try { tracker.waitForAll(); } catch (InterruptedException e) { throw new RuntimeException(e); } return image; }
1dc3274e-872f-4075-8240-b666ce469d0e
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(CCount_Calc_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CCount_Calc_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CCount_Calc_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CCount_Calc_Form.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 CCount_Calc_Form().setVisible(true); } }); }
2f4afbf4-fd4f-4b6f-bd26-c30f685d9111
9
public boolean addProcess(SwapProcess proc) { SwapProcess tempProc = proc; int size = tempProc.getSize(); int startIndex = 0,index = nextIndex; boolean added = false,firstLoop = false;; while(index < 100 && !added) { startIndex = nextHoleIndex(index); //check if the process will get out of bound if(startIndex + size > 100) { if(!firstLoop) { index = 0; firstLoop = true; }else{ index = 101; } } else { int endPoint = (startIndex + size); //check if the process is too big for the hole for(int i = startIndex ; i < endPoint; i++) { if(!memorySpace[i].equalsIgnoreCase(".")) { index = 200; startIndex = i; added = false; } if(index != 200) { added= true; } } } index++; } if(added == true) { int endPoint = (startIndex+size); nextIndex = startIndex; for(int count = startIndex; count < endPoint; count++) { memorySpace[count] = tempProc.toString(); } activeProcess.add(tempProc); } return added; }
30f789e7-ad60-40b8-95de-9de6c94bd535
0
public void setAdresse(String adresse) { this.adresse = adresse; }
5e3c56db-ade9-44f2-8137-32714c248df0
9
@Override public void initTest(boolean argDeserialized) { if(argDeserialized){ return; } Body ground = null; { BodyDef bd = new BodyDef(); ground = getWorld().createBody(bd); PolygonShape shape = new PolygonShape(); shape.setAsEdge(new Vec2(-40.0f, 0.0f), new Vec2(40.0f, 0.0f)); ground.createFixture(shape, 0.0f); } { PolygonShape shape = new PolygonShape(); shape.setAsBox(0.5f, 0.125f); FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 20.0f; WeldJointDef jd = new WeldJointDef(); Body prevBody = ground; for (int i = 0; i < e_count; ++i) { BodyDef bd = new BodyDef(); bd.type = BodyType.DYNAMIC; bd.position.set(-14.5f + 1.0f * i, 5.0f); Body body = getWorld().createBody(bd); body.createFixture(fd); Vec2 anchor = new Vec2(-15.0f + 1.0f * i, 5.0f); jd.initialize(prevBody, body, anchor); getWorld().createJoint(jd); prevBody = body; } } { PolygonShape shape = new PolygonShape(); shape.setAsBox(0.5f, 0.125f); FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 20.0f; WeldJointDef jd = new WeldJointDef(); Body prevBody = ground; for (int i = 0; i < e_count; ++i) { BodyDef bd = new BodyDef(); bd.type = BodyType.DYNAMIC; bd.position.set(-14.5f + 1.0f * i, 15.0f); bd.inertiaScale = 10.0f; Body body = getWorld().createBody(bd); body.createFixture(fd); Vec2 anchor = new Vec2(-15.0f + 1.0f * i, 15.0f); jd.initialize(prevBody, body, anchor); getWorld().createJoint(jd); prevBody = body; } } { PolygonShape shape = new PolygonShape(); shape.setAsBox(0.5f, 0.125f); FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 20.0f; WeldJointDef jd = new WeldJointDef(); Body prevBody = ground; for (int i = 0; i < e_count; ++i) { BodyDef bd = new BodyDef(); bd.type = BodyType.DYNAMIC; bd.position.set(-4.5f + 1.0f * i, 5.0f); Body body = getWorld().createBody(bd); body.createFixture(fd); if (i > 0) { Vec2 anchor = new Vec2(-5.0f + 1.0f * i, 5.0f); jd.initialize(prevBody, body, anchor); getWorld().createJoint(jd); } prevBody = body; } } { PolygonShape shape = new PolygonShape(); shape.setAsBox(0.5f, 0.125f); FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 20.0f; WeldJointDef jd = new WeldJointDef(); Body prevBody = ground; for (int i = 0; i < e_count; ++i) { BodyDef bd = new BodyDef(); bd.type = BodyType.DYNAMIC; bd.position.set(5.5f + 1.0f * i, 10.0f); bd.inertiaScale = 10.0f; Body body = getWorld().createBody(bd); body.createFixture(fd); if (i > 0) { Vec2 anchor = new Vec2(5.0f + 1.0f * i, 10.0f); jd.initialize(prevBody, body, anchor); getWorld().createJoint(jd); } prevBody = body; } } for (int i = 0; i < 2; ++i) { Vec2 vertices[] = new Vec2[3]; vertices[0] = new Vec2(-0.5f, 0.0f); vertices[1] = new Vec2(0.5f, 0.0f); vertices[2] = new Vec2(0.0f, 1.5f); PolygonShape shape = new PolygonShape(); shape.set(vertices, 3); FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 1.0f; BodyDef bd = new BodyDef(); bd.type = BodyType.DYNAMIC; bd.position.set(-8.0f + 8.0f * i, 12.0f); Body body = getWorld().createBody(bd); body.createFixture(fd); } for (int i = 0; i < 2; ++i) { CircleShape shape = new CircleShape(); shape.m_radius = 0.5f; FixtureDef fd = new FixtureDef(); fd.shape = shape; fd.density = 1.0f; BodyDef bd = new BodyDef(); bd.type = BodyType.DYNAMIC; bd.position.set(-6.0f + 6.0f * i, 10.0f); Body body = getWorld().createBody(bd); body.createFixture(fd); } }
a69b51ad-97f7-4ba5-b154-f75c4f7d4ed5
0
public T1 getFoo1() { return foo1; }
1d51d901-2168-4096-9d6e-b346d3374dff
0
@Override public void init(List<String> argumentList) { offset = Integer.parseInt(argumentList.get(0)); identifier = argumentList.get(1); }
d0ea31c4-af1f-4be3-a801-5e74c41698d3
2
public Match getMatch(int noMatch){ for (Match match : liste) { if(match.getId() == noMatch) return match; } return null; }
e83ebea5-f24c-426b-85c4-c3fb08d1905e
9
public String toString() { if(isRoyalFlush()) return "a Royal Flush"; else if(isStraightFlush()) return "a Straight Flush"; else if(isFour()) return "four of a kind"; else if(isFullHouse()) return "a Full House"; else if(isFlush()) return "a Flush"; else if(isStraight()) return "a Straight"; else if(isThree()) return "three of a kind"; else if(numPairs() == 2) return "two pairs"; else if(numPairs() == 1) return "a pair"; else return "High Card"; }
e75e15c6-3089-417a-9940-300c4b296194
2
public void removePush() { if (stack != null) instr = stack.mergeIntoExpression(instr); if (pushedLocal != null) { Expression store = new StoreInstruction(new LocalStoreOperator( pushedLocal.getType(), pushedLocal)).addOperand(instr); instr = store; } super.removePush(); }
7ecc937f-c156-4807-8f87-787e15dc181e
0
private void controlsKitParam(){ final int X_SIDE = 235; final int Y_SIDE = 180; final int HEIGHT_KIT_PARAM_GROUP = 100; final int MIN_VALUE = 1; final int MAX_VALUE = 10; final int DEF_VALUE = 5; JPanel groupKitParam = new JPanel(); LayoutManager layoutGroupKitParam = getContentPane().getLayout(); groupKitParam.setLayout(layoutGroupKitParam); groupKitParam.setBorder(BorderFactory.createTitledBorder("Parameters of kit")); groupKitParam.setSize(FIELD_WIDTH+20, HEIGHT_KIT_PARAM_GROUP); groupKitParam.setLocation( X_SIDE, Y_SIDE); SpinnerNumberModel snm = new SpinnerNumberModel(); snm.setMinimum(MIN_VALUE); snm.setMaximum(MAX_VALUE); snm.setValue(DEF_VALUE); JLabel labelNumberElemInKit = new JLabel("Elements in kit"); labelNumberElemInKit.setSize(FIELD_WIDTH*2/3,FIELD_HEIGHT); labelNumberElemInKit.setLocation(10, 20); numberKitElem = new JSpinner(snm); numberKitElem.setSize(FIELD_WIDTH/3, FIELD_HEIGHT); numberKitElem.setLocation(groupKitParam.getWidth()-80, 20); groupKitParam.add(numberKitElem); groupKitParam.add(labelNumberElemInKit); add(groupKitParam); }
c2a8db27-2dcc-42bb-80ef-5834933d5f77
6
public static Object getValue(String key,Object obj) { String error = ""; if ( obj instanceof Map ) { return ((Map)obj).get(key); } try { BeanInfo binfo = Introspector.getBeanInfo(obj.getClass(), Object.class); PropertyDescriptor[] props = binfo.getPropertyDescriptors(); for (int i = 0; i < props.length; i++) { String pname = props[i].getName(); if ( key.equals(pname) ) { Method m = props[i].getReadMethod(); Object v = m.invoke(obj, null); return v; } }//for } catch (IntrospectionException ex) { error = ex.getMessage(); } catch (IllegalAccessException ex) { error = ex.getMessage(); } catch (java.lang.reflect.InvocationTargetException ex) { error = ex.getMessage(); } throw new NullPointerException("An object of type " + obj.getClass() + " doesn't contain a field with a name " + key + "(" + error + ")"); }
c5e8b799-2f4f-478a-a923-a00c9a66a9f3
0
@ManyToOne @JsonIgnore public Car getCar() { return car; }
2039d467-6e72-47be-9467-9f618f6d01c4
4
public double rawItemRange(int index){ if(!this.dataPreprocessed)this.preprocessData(); if(index<1 || index>this.nItems)throw new IllegalArgumentException("The item index, " + index + ", must lie between 1 and the number of items," + this.nItems + ", inclusive"); if(!this.variancesCalculated)this.meansAndVariances(); return this.rawItemRanges[index-1]; }
42cd2b43-d956-46d5-82a4-4f661d80ba5b
5
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String user = request.getRemoteUser(); PrintWriter out = response.getWriter(); showBartenderOrdersForm(out); int p=0; // u.getAccess()==1 if (user != null) { try { p=loggedInUser.getAccess(user); } catch (SQLException e1) { response.getWriter().println("<p> Exception</p>"); } if (p==1) { // response.getWriter().println("<center><br><br><h3>Order Placement! </h3></center>"); try { appendOrderTable(response); appendAddForm(response); } catch (Exception e) { response.getWriter().println( "Persistence operation failed with reason: " + e.getMessage()); LOGGER.error("Persistence operation failed", e); } } else { response.getWriter().println("You don't have the permision to view this"); response.getWriter().println("<p>"+user+"</p>"); } } else { LoginContext loginContext; try { loginContext = LoginContextFactory.createLoginContext("FORM"); loginContext.login(); response.getWriter().println("Hello, " + request.getRemoteUser()); } catch (LoginException e) { e.printStackTrace(); } } }
4ed0a2d6-c9e2-4ab2-9838-a44f4d3d179f
9
public String addBinary(String a, String b) { if (a == null || a.length() == 0) return b; if (b == null || b.length() == 0) return a; int i = a.length() - 1; int j = b.length() - 1; int carry = 0; StringBuilder res = new StringBuilder(); while (i >= 0 && j >= 0) { int digit = (int) (a.charAt(i) - '0' + b.charAt(j) - '0') + carry; carry = digit / 2; digit %= 2; res.insert(0, digit); i--; j--; } while (i >= 0) { int digit = (int) (a.charAt(i) - '0') + carry; carry = digit / 2; digit %= 2; res.insert(0, digit); i--; } while (j >= 0) { int digit = (int) (b.charAt(j) - '0') + carry; carry = digit / 2; digit %= 2; res.insert(0, digit); j--; } if (carry > 0) { res.insert(0, carry); } return res.toString(); }
ba8d21ff-b72b-4ffd-a2fb-6fad2d04263e
6
final public FuncName FuncName() throws ParseException { Token n; FuncName f; n = jj_consume_token(NAME); f = new FuncName(n.image); label_4: while (true) { switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case 73: ; break; default: jj_la1[14] = jj_gen; break label_4; } jj_consume_token(73); n = jj_consume_token(NAME); f.adddot(n.image); } switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case 74: jj_consume_token(74); n = jj_consume_token(NAME); f.method = n.image; break; default: jj_la1[15] = jj_gen; ; } L(f, n); { if (true) return f; } throw new Error("Missing return statement in function"); }
8dfcf7b4-97e2-4e46-af1a-897057ae4534
7
boolean loadScriptFileInternal(String filename) { if (filename.toLowerCase().indexOf("javascript:") == 0) return loadScript(filename, viewer.eval(filename.substring(11))); Object t = viewer.getInputStreamOrErrorMessageFromName(filename); if (!(t instanceof InputStream)) return loadError((String) t); BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) t)); StringBuffer script = new StringBuffer(); try { while (true) { String command = reader.readLine(); if (command == null) break; script.append(command); script.append("\n"); } } catch (IOException e) { try { reader.close(); } catch (IOException ioe) { } return ioError(filename); } try { reader.close(); } catch (IOException ioe) { } return loadScript(filename, script.toString()); }
39070f34-8e53-4087-b09a-659b07f97e94
3
public Object getValueAt(int row, int column) { switch (column) { case 0: return variables[row]; case 1: return firstSets[row]; case 2: return followSets[row]; } return null; }
2f195742-9518-4e20-a560-304740bcce1a
5
@Override protected void read(InputBuffer b) throws IOException, ParsingException { iv = b.get(0, 16); int curve = Util.getShort(b.get(16, 2)); if (curve != 714) { throw new ParsingException("Unknown curve: " + 714); } int xLength = Util.getShort(b.get(18, 2)); if (xLength > 32 || xLength < 0) { throw new ParsingException("xLength must be between 0 and 32: " + xLength); } BigInteger x = Util.getUnsignedBigInteger(b.get(20, xLength), 0, xLength); b = b.getSubBuffer(xLength + 20); int yLength = Util.getShort(b.get(0, 2)); if (yLength > 32 || yLength < 0) { throw new ParsingException("yLength must be between 0 and 32: " + yLength); } BigInteger y = Util.getUnsignedBigInteger(b.get(2, yLength), 0, yLength); b = b.getSubBuffer(2 + yLength); publicKey = CryptManager.getInstance().createPublicEncryptionKey(x, y); encrypted = b.get(0, b.length() - 32); mac = b.get(b.length() - 32, 32); }
8bd094e3-8d09-4e7c-b02c-c4423168c3b8
6
private void createRoadsRelations() { // Cas des villes voisines pour les routes. for (JTown t: towns) { // Pour chaque ville. for (JRoad r: t.getRoadNeighbours()) { // Pour chaque route voisine de la ville. r.addTownNeighbour(t); // Ajouter la ville en tant que ville voisine de la route. } } // Cas des routes voisines pour les routes. for (JRoad r1: roads) { // Pour chaque route. for (JTown t: r1.getTownNeighbours()) { // Pour chaque ville voisine de la route. for (JRoad r2: t.getRoadNeighbours()) { // Pour chaque route voisine de la ville. if (r1 != r2) r1.addRoadNeighbour(r2); // Si la route voisine n'est pas la route initiale, l'ajouter en tant que route voisine a la route initiale. } } } }
d4fa0ca4-6ab0-4d14-9b18-82c3b7dbd50e
7
private RGBImage(final int width, final int height, final int type, final PixelSupplier supplier) { this.width = width; this.height = height; this.type = type; this.pixelValues = new int[width * height * 3]; final ErrorHandler errorHandler = new ErrorHandler(); final ExecutorService service = Executors.newWorkStealingPool(); for (int y = 0; (y < height) && errorHandler.isClean(); ++y) { // for (int x = 0; x < width; ++x) { // setPixel(x, y, supplier.supply(x, y)); // } service.execute(new LineWise(y, supplier, errorHandler)); if (0 == (y % 64)) { System.out.print('.'); } } try { if (errorHandler.isDirty()) { service.shutdownNow(); } else { service.shutdown(); } if (!service.awaitTermination(2, TimeUnit.MINUTES)) { throw new InterruptedException("timeout occurred"); } } catch (final InterruptedException e) { errorHandler.accept(e); } if (errorHandler.isDirty()) { //noinspection ProhibitedExceptionThrown,AccessingNonPublicFieldOfAnotherObject throw new Error(errorHandler.caught); } }
14720974-43a8-46df-ae89-9868ed56a15e
7
public static List<String> getColumnList(File file, int index, String sep,boolean ignore) { List<String> ret = new ArrayList<String>(); BufferedReader br = null; try { // 构造BufferedReader对象 br = new BufferedReader(new FileReader(file)); int ln = 0; String line = null; while ((line = br.readLine()) != null) { ln++; if(ln%1000000==0){ System.out.println("loading "+file.getName()+"\t"+ln+" lines."); } String[] cols = line.split(sep); if(cols.length>=(index+1)){ String col = cols[index]; ret.add(col); }else{ // //将出错line文本打印到控制台 System.err.println("index overflow error at line "+ln+ ": "+line); if (!ignore){ ret.add(null); } } } } catch (IOException e) { e.printStackTrace(); } finally { // 关闭BufferedReader if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return ret; }
64a946a8-864d-47b0-9042-9b7a5976f6dc
6
private void recMinMax(Node currentNode, int player, int depth) { // depth_lpnode = depth of (l)ast (p)arent node if (currentNode.empty) { return; } // until last node with children (max_depth -1 means depth_lpnode = last parent node) // if (currentNode.nodeDepth != depth_lastParentNode) { // for (int i = 0; i < currentNode.children.size(); i++) { // recMinMax(currentNode.children.get(i), depth_lastParentNode, player); // } // } if (!currentNode.children.isEmpty()) { for (int i = 0; i < currentNode.children.size(); i++) { Node n; if (!(n = currentNode.children.get(i)).children.isEmpty()) { recMinMax(n, player, depth + 1); } } // now we are in right depth. currentNode has 7 children int minOrMax = depth % 2; try { if (minOrMax == 1) { // odd depth value --> maximize // currentNode.value = max(currentNode.children); max(currentNode); } else { // even depth value --> minimize // currentNode.value = min(currentNode.children); min(currentNode); } } catch (AllNodesEmptyException ex) { currentNode.empty = true; } } }
bd6a83fa-a033-42b0-a46b-e768e03deec9
2
@Override public void propertyChange(PropertyChangeEvent pce) { if (pce.getSource() instanceof AbstractModel) { registeredViews.forEach(x -> x.modelPropertyChange(pce)); } else if (pce.getSource() instanceof AbstractView) { registeredModels.forEach(x -> x.viewPropertyChange(pce)); } }
6ccecfe8-3961-405c-b628-7ac00383f846
1
public String getWord() { //if more than 90% of the word occurrences are capital, //then use capital style if ((mFreq * 0.90) < mCapitalFreq) return Character.toUpperCase(mWord.charAt(0)) + mWord.substring(1); else return mWord; }
22272124-ac4d-48da-8ebc-1ba9bf62b85a
1
private void declareLabel(final Label l) { String name = (String) labelNames.get(l); if (name == null) { name = "l" + labelNames.size(); labelNames.put(l, name); buf.append("Label ").append(name).append(" = new Label();\n"); } }
be791321-3dc4-4c7a-8ce9-55472e760f94
1
public boolean ModificarCultivo(Cultivo p){ if (p!=null) { cx.Modificar(p); return true; }else { return false; } }
bc159606-dfcd-4d97-ad78-2ffc952ad91f
3
public Object getValueAt(int row, int col) { if(row>-1 && col>-1 && data!=null) return data[row][col]; else return null; }
5bfd878b-d541-4e7c-93e0-9b1cf4e03964
2
private boolean searchTableColumns( String keyword ) { for ( Column column : table.getColumns() ) { if ( column.getFldType().equalsIgnoreCase( keyword ) ) { return true; } } return false; }
0e8b0764-44e9-4d8e-840f-af822e169674
7
public static void postfix(String postfixInput) { int result = 0; int val = 0; int var1 = 0; int var2 = 0; char ch = ' '; Stack s = new Stack(); for (int i = 0; i < postfixInput.length(); i++) { ch = postfixInput.charAt(i); val = ch - '0'; if(val >=0 && val <9) { s.push(val); } else { var1 = (int)s.pop(); var2 = (int)s.pop(); switch(ch) { case '+': result = var1 + var2; break; case '-': result = var1 - var2; break; case '/': result = var1 / var2; break; case '*': result = var1 * var2; break; default: result = 0; System.out.println("Invalid characterr encountered!!"); break; } s.push(result); } } result = (int)s.pop(); System.out.println("The result of postfix " + postfixInput + " is: " + result); }
efb27741-9889-4b8f-90e7-e802b0b07e41
0
public void setLevel(int level) { this.level = level; }
7cb787c2-342a-4982-b3ae-50522bc08639
4
private boolean parseStart(){ // There MUST be tokens left at the start int[] parsed = parsePrefix(); if (parsed == null){ // Error parsing return false; } NumberToken next = peek(); if (next == null){ // Units, can't parse any more units = parsed; return true; } else if (next.type == TokenType.MILLION){ // Millions, parse again for thousands and below millions = parsed; consume(); return parseAfterMillion(); } else if (next.type == TokenType.THOUSAND){ // Thousands, parse again for units thousands = parsed; consume(); return parseAfterThousand(); } em.error("Expected million, thousand, or end-of-file; got \"%s\"", next); return false; }
5d4b7d7b-6f98-4f62-bc17-db8152b659cb
0
public Primes() { super("Find Prime Numbers"); }
23e732bc-c597-4ed1-908c-992e1749cae8
7
@Override public void setData(ByteBuffer in) { size = in.getInt(); width = in.getInt(); height = in.getInt(); planes = in.getShort(); bitsPerPixel = in.getShort(); compression = in.getInt(); sizeOfBitmap = in.getInt(); horzResolution = in.getInt(); vertResolution = in.getInt(); colorsUsed = in.getInt(); colorsImportant = in.getInt(); int cols = (int) colorsUsed; if (cols == 0) { cols = 1 << bitsPerPixel; } palette = new PaletteElement[cols]; for (int i = 0; i < palette.length; i++) { PaletteElement el = new PaletteElement(); el.Blue = in.get(); el.Green = in.get(); el.Red = in.get(); el.Reserved = in.get(); palette[i] = el; } // int xorbytes = (((int)height/2) * (int)width * (int)bitsPerPixel) / 8; int xorbytes = (((int) height / 2) * (int) width); // System.out.println("POSITION " + in.position() + " : xorbitmap = " + xorbytes + " bytes"); bitmapXOR = new short[xorbytes]; for (int i = 0; i < bitmapXOR.length; i++) { switch (bitsPerPixel) { case 4: { int pix = in.get(); bitmapXOR[i] = (short) ((pix >> 4) & 0x0F); i++; bitmapXOR[i] = (short) (pix & 0x0F); } break; case 8: { bitmapXOR[i] = in.get(); } break; } } int height = (int) (this.height / 2); int rowsize = (int) width / 8; if ((rowsize % 4) > 0) { rowsize += 4 - (rowsize % 4); } // System.out.println("POSITION " + in.position() + " : andbitmap = " + andbytes + " bytes"); int andbytes = height * rowsize; // (((int)height/2) * (int)width) / 8; bitmapAND = new short[andbytes]; for (int i = 0; i < bitmapAND.length; i++) { bitmapAND[i] = in.get(); } }
a459be55-0e01-4084-b986-8c13f5156a19
8
@Override public void update() { for(Planet p : planets){ p.update(); } Set<Ship> toremove = new HashSet<Ship>(); for(Ship s : ships){ s.update(); { double x = s.getCentrePoint().getX(); double y = s.getCentrePoint().getY(); if(x < 0 || x > width || y < 0 || y > height){ toremove.add(s); continue; } } for(Planet p : planets){ if(s.intersects(p)){ p.acceptShip(s); toremove.add(s); break; } } } ships.removeAll(toremove); }
0f8164bc-e5eb-4274-aa98-35045612de74
6
void initInputFrame( final ClassWriter cw, final int access, final Type[] args, final int maxLocals){ inputLocals = new int[maxLocals]; inputStack = new int[0]; int i = 0; if((access & Opcodes.ACC_STATIC) == 0) { if((access & MethodWriter.ACC_CONSTRUCTOR) == 0) { inputLocals[i++] = OBJECT | cw.addType(cw.thisName); } else { inputLocals[i++] = UNINITIALIZED_THIS; } } for(int j = 0; j < args.length; ++j) { int t = type(cw, args[j].getDescriptor()); inputLocals[i++] = t; if(t == LONG || t == DOUBLE) { inputLocals[i++] = TOP; } } while(i < maxLocals) { inputLocals[i++] = TOP; } }
4cbe52ba-c3c9-46ad-9b9e-d872bcc728be
1
public int leiaInt() { int numero = 0; String linha ; BufferedReader entra = new BufferedReader(new InputStreamReader(System.in)) ; try { linha = entra.readLine() ; numero = Integer.valueOf(linha).intValue(); } catch (Exception erro) { System.out.println("erro de entrada de dados"); } return numero ; }