text
stringlengths
14
410k
label
int32
0
9
public void testParseInto_simple() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); MutableDateTime result = new MutableDateTime(0L); assertEquals(20, g.parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); try { g.parseInto(null, "2004-06-09T10:20:30Z", 0); fail(); } catch (IllegalArgumentException ex) {} assertEquals(~0, g.parseInto(result, "ABC", 0)); assertEquals(~10, g.parseInto(result, "2004-06-09", 0)); assertEquals(~13, g.parseInto(result, "XX2004-06-09T", 2)); }
1
private static void checkedException() { FileOutputStream out = null; try { out = new FileOutputStream(new File("/tmp/file.txt")); System.out.println("File opened"); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } }
2
private ASPlayer setLastActivity(ASPlayer data, TableType table, int value) { switch(table) { case DAY: data.lastDay.activity = value; break; case WEEK: data.lastWeek.activity = value; break; case MONTH: data.lastMonth.activity = value; break; default: plugin.severe("Invalid Type in setLastActivity"); } return data; }
3
private static Connection innitializeDB(String URL, final String TABLES) { Statement stmt = null; Connection conn = null; try { conn = DriverManager.getConnection(URL); } catch (SQLException e) { e.printStackTrace(); } try { stmt = conn.createStatement(); } catch (SQLException e) { e.printStackTrace(); } try { stmt.execute(TABLES); } catch (SQLException e) { e.printStackTrace(); } return conn; }
3
public void actionPerformed(ActionEvent e) { if (e.getSource() == trocaMusica) { //System.out.println("Entrou aqui"); if (m_flagPlayStop){ somDaMensagem.interrupt(); m_flagPlayStop = false; } else { somDaMensagem = new ExecutarSom( "musicas/hedwigsTheme.wav"); somDaMensagem.start(); m_flagPlayStop = true; } } else if ( e.getSource()== m_pista ) //Botao que da inicio a escrita de mensagem no Computador1 { JOptionPane.showInternalMessageDialog(null, "Filosofo0", "Filoso[i]", 0); } //Fim do If (e.getSource()== m_mensagemComputador1) else if (e.getSource() == m_botaoParaControlarVisibilidadeDoPainelDeConfiguracoes) { if (m_botaoParaControlarVisibilidadeDoPainelDeConfiguracoes.getText().equals("Configurações")) { m_painelConfiguracoesGerais.setBounds(0,483,900,216);//setBounds(coluna ,linha , largura, altura) m_botaoParaControlarVisibilidadeDoPainelDeConfiguracoes.setText("Minimizar"); }// fim do if else if (m_botaoParaControlarVisibilidadeDoPainelDeConfiguracoes.getText().equals("Minimizar" )) { m_painelConfiguracoesGerais.setBounds(0,658,900,216);//setBounds(coluna ,linha , largura, altura) m_botaoParaControlarVisibilidadeDoPainelDeConfiguracoes.setText("Configurações"); } // fim do else if } // fim do else else if (e.getSource() == m_testaThread) { } else if (e.getSource() == m_testaThread2){ } }//Fim do Metodo actionPerformed
8
@Override public Individual getParent(List<Individual> population) throws Exception{ Random rand = new Random(); List<Individual> local = new ArrayList<Individual>(); Individual best = null; //Form the sample group while(local.size() < tournamentSize){ int random = rand.nextInt(population.size()); if(!local.contains(population.get(random))){ local.add(population.get(random)); if(best == null) best = population.get(random); else if(best.fitness() < population.get(random).fitness()){ best = population.get(random); } } } //When group is full, roll to check if we're picking the best if(chanceBestPick >= Math.random()){ return best; }else{ while(true){ if(!local.get(rand.nextInt(local.size())).equals(best)){ return local.get(rand.nextInt(local.size())); } } } }
7
protected void handleEvilPopupMgrBackup() { if (RegKey.POPUP_MGR.type != null) return; // this will return String (REG_SZ), int (REG_DWORD), or null if the key is missing RegKey.POPUP_MGR.type = WindowsUtils.discoverRegistryKeyType(RegKey.POPUP_MGR.key); Class<?> backupPopupMgrType = discoverPrefKeyType(RegKey.POPUP_MGR.name()); if (RegKey.POPUP_MGR.type == null) { // if official PopupMgr key is missing if (backupPopupMgrType == null) { // we don't know which type it should be; let's take a guess // IE6 can deal with a DWORD 0 RegKey.POPUP_MGR.type = boolean.class; return; } // non-null backup type is our best guess RegKey.POPUP_MGR.type = backupPopupMgrType; return; } if (RegKey.POPUP_MGR.type.equals(backupPopupMgrType)) return; // if we're here, we know the current type of pop-up manager, // and the backup has a different (wrong) type if (backupPopupMgrType != null) { WindowsUtils.deleteRegistryValue(RegKey.POPUP_MGR.key); } if (!backupIsReady()) { return; } // assume they originally wanted it off, set backup pref to false String value = "no"; if (RegKey.POPUP_MGR.type.equals(boolean.class)) { value = "false"; } prefs.put(RegKey.POPUP_MGR.name(), value); }
8
private void begin () { long t__send, dt; double rate; _t_send = System.currentTimeMillis(); while (++times <= Utils.MAX) { broadcast("TEST", String.format("%d", System.currentTimeMillis())); if (times % Utils.STEP == 0) { t__send = System.currentTimeMillis(); dt = t__send - _t_send; if (dt > 0) rate = (double) (Utils.STEP * 1000) / (double) dt; else rate = 0.0; Utils.out(pid, String.format("[SEND] %06d\trate %10.1f m/s", times, rate)); _t_send = t__send; } } }
3
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Positie positie = (Positie) o; if (x != positie.x) return false; if (y != positie.y) return false; return true; }
5
private void connectToServer() { if(iptf.getText().equals("")) { JOptionPane.showMessageDialog(SwitchServerWindow.this, "The IP can't be blank!", "Error", JOptionPane.ERROR_MESSAGE); }else { if(connect == null || !connect.isAlive()) { connect = new Thread( new Runnable() { @Override public void run() { boolean correct = false; connectb.setVisible(false); connectb.repaint(); sp.setVisible(true); try { iptf.setEnabled(false); AdminClient.client = new Client(iptf.getText(), 1234); correct = true; } catch (IOException e1) { iptf.setEnabled(true); iptf.setText(""); sp.setVisible(false); AdminClient.client = null; connectb.setVisible(true); JOptionPane.showMessageDialog(SwitchServerWindow.this, "Couldn't connect with the server.", "Error", JOptionPane.ERROR_MESSAGE); } if(correct) { SwitchServerWindow.this.dispose(); } } }); connect.start(); } } }
5
public void visitLocalExpr(final LocalExpr expr) { // Determines whether or not the LocalExpr in question is the this // pointer. If the LocalExpr resides within an InitStmt, and the // LocalExpr is the first variable defined by the InitStmt, it is // the this pointer. if (thisPtr != null) { return; } if (expr.parent() instanceof InitStmt) { final InitStmt stmt = (InitStmt) expr.parent(); final MethodEditor method = stmt.block().graph().method(); if (!method.isStatic()) { Assert.isTrue(stmt.targets().length > 0); if (expr == stmt.targets()[0]) { thisPtr = expr; if (ValueFolding.DEBUG) { System.out.println("this = " + thisPtr); } } } } }
5
String arrayName(String component, int dims) { // Using char[] since we have no StringBuilder in JDK4, and StringBuffer is slow. // Although, this is more efficient even if we did have one. int i = component.length(); int size = i + dims * 2; char[] string = new char[size]; component.getChars(0, i, string, 0); while (i < size) { string[i++] = '['; string[i++] = ']'; } component = new String(string); return component; }
1
@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 CcsTest)) { return false; } CcsTest other = (CcsTest) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
5
@Override public boolean touchRobot() { boolean touch = false; for (int i = 0; i < Board.robots.size(); i++) { if (Board.robots.get(i) != this.owner) { ArrayList<Line2D.Double> linies = Board.robots.get(i).getBoundLines(); for (int j = 0; j < linies.size(); j++) { if (linies.get(j).getBounds().contains(this.getX(), this.getY())) { touch = true; URL explosionAnimImgUrl = this.getClass().getResource("/resources/images/exploteBullet.png"); try { explosionAnimImg = ImageIO.read(explosionAnimImgUrl); } catch (IOException ex) { Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex); } Explote expAnim = new Explote(explosionAnimImg, 60, 60, 46, 7, false, (int)this.x-50, (int)this.y - explosionAnimImg.getHeight()/3, 0); Board.getExpAnim().add(expAnim); } } } } return touch; }
5
public static ChunkyWorld getChunkyWorld(String worldName) { ChunkyObject object = getObject(ChunkyWorld.class.getName(), worldName); if (object == null) { World world = Bukkit.getServer().getWorld(worldName); if (world != null) { object = new ChunkyWorld(); object.setId(world.getName()).setName(world.getName()); } } return (ChunkyWorld) object; }
2
public void run() { int here = monitor.stop(); while (true) { liftView.moveLift(here, monitor.move()); here = monitor.stop(); } }
1
public static boolean simulate(double height, double v, double angle, double maxX, double[] targetY){ if(parameterCheck(height, v, angle, maxX, targetY)==false){//is the input bad? return false;//stop } y0 = height; v0 = v; a = angle; targetX = maxX; hitbox = targetY; double CD = CD0 + CDA*Math.pow((angle-A0)*Math.PI/180, 2);//Figures Drag Coefficient double CL = CL0 + CLA*angle*Math.PI/180;//Figures Lift Coefficient //Initial reset(); y=height;//frisbee leaves from height vx=v*Math.cos(angle*Math.PI/180);//Initial X velocity vy=v*Math.sin(angle*Math.PI/180);//Initial Y velocity while(y>0 && x<maxX){//while it hasn't hit the ground and hasn't reached the target X distance double dVY = ( RHO * Math.pow(vx,2) * AREA * CL / 2 / MASS - GRAV ) * EULER_STEP;//change in Y velocity. double dVX = ( RHO * Math.pow(vx, 2) * AREA * CD / 2 / MASS ) * -EULER_STEP;//change in X velocity. vx += dVX; vy += dVY; x += vx * EULER_STEP; y += vy * EULER_STEP; if(y>maxHeight){//checks to see if it peaks here maxHeight=y;//if so, this is the peak at=x;//peak occurred at this x value } t += EULER_STEP;//keeps track of flight time } if(y<0){//if it goes "underground" because of an extra iteration, say it hit the ground y=0; } xErr = x-maxX; if(xErr<.1 && xErr>0){//If it goes past the x bound because of an extra iteration, say it hit the wall xErr=0; x=maxX; } if(y>targetY[1]){//positive error if it lands above the upper boundary of the hitbox yErr=y-targetY[1]; } else if(y<targetY[0]){//negative error if it lands below the lower boundary of the hitbox yErr=y-targetY[0]; } else{yErr=0;}//in the hitbox. return true; }
9
public static void main(String[] args){ Boat.createBoat("RaceBoat"); Boat boat = Boat.getInstance(); try{ System.out.println("Setting sail to 0 degrees."); boat.com.sendMessage("set sail 0"); Thread.sleep(5000); for(int i = 10; i <= 360; i += 10){ System.out.print("Setting sail to " +i+" degrees."); boat.com.sendMessage("set sail " + i); Thread.sleep(1000); } }catch(Exception e){ e.printStackTrace(); } }
2
public static StandardUnit addStandardUnit(String name, String typeName, String systemName, double factorToReference) { StandardUnit createdUnit = null; if(!listUnits.containsKey(name) && listTypes.containsKey(typeName) && listSystems.containsKey(systemName)) { Type type = listTypes.get(typeName); System system = listSystems.get(systemName); if(type.getReferenceUnit() != null) { createdUnit = new StandardUnit(name, type, system, factorToReference); type.getReferenceUnit().getFactors().put(createdUnit, 1 / factorToReference); type.getUnits().put(name, createdUnit); system.getUnits().put(name, createdUnit); listUnits.put(name, createdUnit); } } return createdUnit; }
4
public static void loadNewsInfo() throws IOException { checkUSB(); System.out.println("start to load news info from usb"); String rootPath = USBConfig.drivePath; String initnewFolder = rootPath + USBConfig.INI_NEW_FOLDER + "\\"; File folder = new File(initnewFolder); if(!folder.exists()){ folder.mkdirs(); } String newsiniFile = initnewFolder + "news.ini"; File newsIni = new File(newsiniFile); if (!newsIni.exists()) { System.out.println(newsiniFile + " file does not exist!"); // File f = new File(new File("").getAbsolutePath()+"/files/news.ini"); System.out.println("*************path test**************"); System.out.println(InfoUtils.class.getResource("").getPath()); System.out.println(InfoUtils.class.getResource("/").getPath()); System.out.println(InfoUtils.class.getClassLoader().getResource("")); System.out.println(new File("./files").getAbsolutePath()); System.out.println(new File("./files").getPath()); System.out.println(new File("./files").getPath()); System.out.println(new File("").getAbsolutePath()); System.out.println(new File("").getCanonicalPath()); System.out.println(System.getProperty("java.class.path")); System.out.println("*************path test**************"); File f = new File(InfoUtils.class.getResource("/").getPath()+"news.ini"); // TODO develop model // if(!f.exists()){ // f = new File(InfoUtils.class.getClass().getResource("/files/news.ini").getPath()); // } FileReaderUtils.copy(f, newsIni); } List<String> list = FileReaderUtils.readFile(newsIni); if (list != null) { News news = null; for (String s : list) { if (s.startsWith("news")) { int spliterIndex = s.indexOf("="); String index = s.substring(0, spliterIndex); String content = s.substring(spliterIndex + 1, s.length()); news = new News(index, content); NewsDao.instance().addNews(news); } } } }
5
public void setFacOracleDAO(FacOracleDAO casurOracleDAO) { this.facOracleDAO = casurOracleDAO; }
0
@Override public boolean isCellEditable(int row, int col) { return false; }
0
private void makePack(List<Card> cardList) { for (Card.Suit suit : Card.Suit.values()) { for (Card.Rank rank : Card.Rank.values()) { cardList.add(new Card(suit, rank)); } } }
2
@Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) { if (ELEMENT_PROPERTY.equals(qName)) { try { String class_name = atts.getValue(ATTRIBUTE_CLASS); String property_name = atts.getValue(ATTRIBUTE_NAME); String property_value = atts.getValue(ATTRIBUTE_VALUE); Class[] parameterTypes = {(new String("")).getClass()}; Constructor constructor = Class.forName(class_name).getConstructor(parameterTypes); Object[] args = {property_value}; Object property = constructor.newInstance(args); if (container != null) { container.setProperty(property_name, property); } else { System.out.println("Warning: no PropertyContainer to add property to during PropertyContainerXMLParser parsing."); } } catch (Exception e) { e.printStackTrace(); } } else if (ELEMENT_PROPERTY_CONTAINER.equals(qName)) { try { String class_name = atts.getValue(ATTRIBUTE_CLASS); container = (PropertyContainer) Class.forName(class_name).newInstance(); // Instantiate a List if we don't have one by now. if (containers == null) { containers = new ArrayList(); } containers.add(container); } catch (Exception e) { e.printStackTrace(); } } else if (ELEMENT_PROPERTY_CONTAINERS.equals(qName)) { try { String class_name = atts.getValue(ATTRIBUTE_CLASS); containers = (List) Class.forName(class_name).newInstance(); } catch (Exception e) { e.printStackTrace(); } } super.startElement(namespaceURI, localName, qName, atts); }
8
public int compareTo(Object o) { return (equals(o) ? 0 : -1); }
1
protected Class getClass(final Type t) { try { if (t.getSort() == Type.ARRAY) { return Class.forName(t.getDescriptor().replace('/', '.'), false, loader); } return Class.forName(t.getClassName(), false, loader); } catch (ClassNotFoundException e) { throw new RuntimeException(e.toString()); } }
2
@Override public boolean isTypeOf(Property p) { if(p==null) return true; if(equals(p)) return true; return this.superType.isTypeOf(p); }
2
public static void readTemplates(String fileName, boolean resampledFirst, ArrayList<Template> templates){ try { Scanner sc = new Scanner(new File(fileName)); String curTemplate = ""; ArrayList<Point> curPoints = null; while(sc.hasNext()){ String cur = sc.next(); if(cur.charAt(0) == '#'){ if(!curTemplate.equals("") && curPoints != null){ templates.add(new Template(curTemplate, curPoints, resampledFirst)); } curTemplate = cur.substring(1); curPoints = new ArrayList<Point>(); } else { if(curPoints != null){ curPoints.add(new Point(Double.parseDouble(cur), Double.parseDouble(sc.next()))); } } } if(!curTemplate.equals("") && curPoints != null){ //Add the last template templates.add(new Template(curTemplate, curPoints, resampledFirst)); } } catch (FileNotFoundException e) { log.warn("Can't find file."); } if(resampledFirst){ log.debug(templates.size()+" resampled first templates loaded."); } else { log.debug(templates.size()+" resampled last templates loaded."); } }
9
boolean checkMyType(Object object) { if (object == null || !(object instanceof MyType[]) || ((MyType[])object).length == 0) return false; MyType[] myTypes = (MyType[])object; for (int i = 0; i < myTypes.length; i++) { if (myTypes[i] == null || myTypes[i].firstName == null || myTypes[i].firstName.length() == 0 || myTypes[i].lastName == null || myTypes[i].lastName.length() == 0) return false; } return true; }
9
@Override public Grid clone() { Grid ret = new Grid(width, height, intelligentX, intelligentY, targetX, targetY); ret.setCurrentCells(Arrays.copyOf(currentCells, currentCells.length)); for (Integer i : intellingentMovementHistory) { ret.getIntellingentMovementHistory().add(i); } return ret; }
1
public void commandAction(Command command, Displayable displayable) { String commandLabel = command.getLabel(); try { if (PlaygroundApp.ROOM_SELECTED_COMMAND.equals(commandLabel)) { launchRoomScreen(); } else if (PlaygroundApp.TURN_ON_LIGHT_COMMAND.equals(commandLabel)) { turnOnTheLight(); } else if (PlaygroundApp.TURN_OFF_LIGHT_COMMAND.equals(commandLabel)) { turnOffTheLight(); } else if (PlaygroundApp.BACK_COMMAND.equals(commandLabel)) { display.setCurrent(roomCatalogForm); } else if (PlaygroundApp.ENABLE_WIFI_COMMAND.equals(commandLabel)) { bluetoothManager.startDeviceSearch(BluetoothManager.ENABLE_COMMAND, livingRoomForm); } else if (PlaygroundApp.DISABLE_WIFI_COMMAND.equals(commandLabel)) { bluetoothManager.startDeviceSearch(BluetoothManager.DISABLE_COMMAND, livingRoomForm); } } catch (IOException ex) { ex.printStackTrace(); display.setCurrent(new Alert("Error", "Ha ocurrido un error inesperado", null, AlertType.ERROR)); } }
7
private BufferedImage process(BufferedImage old) { int w = old.getWidth(); int h = old.getHeight(); BufferedImage img = new BufferedImage( w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.drawImage(old, 0, 0, null); if(!localClues.isEmpty()) { for(Clue clue : localClues) { Position p = clue.getCrossing().getPos(); p = convert(p); int x = (int) p.getX(); int y = (int) p.getY(); g2d.setPaint(SimulationGUI.localClueCol); Ellipse2D.Double circle = new Ellipse2D.Double(x-circleDiameter/2, y-circleDiameter/2, SimulationGUI.circleDiameter, SimulationGUI.circleDiameter); g2d.fill(circle); } } if(runnerDestination!=null) { Position p = runnerDestination.getPos(); p = convert(p); int x = (int) p.getX(); int y = (int) p.getY(); g2d.setPaint(SimulationGUI.destCol); Ellipse2D.Double circle = new Ellipse2D.Double(x-circleDiameter/2, y-circleDiameter/2, SimulationGUI.circleDiameter, SimulationGUI.circleDiameter); g2d.fill(circle); } if(globalClue!=null) { Position p = globalClue.getCrossing().getPos(); p = convert(p); int x = (int) p.getX(); int y = (int) p.getY(); g2d.setPaint(SimulationGUI.globalClueCol); Ellipse2D.Double circle = new Ellipse2D.Double(x-circleDiameter/2, y-circleDiameter/2, SimulationGUI.circleDiameter, SimulationGUI.circleDiameter); g2d.fill(circle); } if(catchersCrossings!=null) { for(Crossing c : catchersCrossings) { Position p = c.getPos(); p = convert(p); int x = (int) p.getX(); int y = (int) p.getY(); g2d.setPaint(SimulationGUI.catcherCol); Ellipse2D.Double circle = new Ellipse2D.Double(x-circleDiameter/2, y-circleDiameter/2, SimulationGUI.circleDiameter, SimulationGUI.circleDiameter); g2d.fill(circle); } } if(runnerCrossing!=null) { Position p = runnerCrossing.getPos(); p = convert(p); int x = (int) p.getX(); int y = (int) p.getY(); g2d.setPaint(SimulationGUI.runnerCol); Ellipse2D.Double circle = new Ellipse2D.Double(x-runnerCircleDiameter/2, y-runnerCircleDiameter/2, SimulationGUI.runnerCircleDiameter, SimulationGUI.runnerCircleDiameter); g2d.fill(circle); } g2d.dispose(); return img; }
7
public boolean removerDependente(String nomeDependente){ for(String d: dependentes){ if( d.equalsIgnoreCase(nomeDependente) ){ dependentes.remove(nomeDependente); return true; } } return false; }
2
public List<Integer> getFrequents(int[] nums) { // Find all the high frequency candidates for (int num : nums) { Integer count = counters.get(num); if (count != null) { // If it's one of the counters, increment counters.put(num, ++count); } else if (counters.size() < numFrequents) { // If the counters aren't full add this one counters.put(num, 1); } else { // If no match decrement every counter and // remove the ones that would be reset to 0 // Using an iterator here so we can invoke the remove() method Iterator<Entry<Integer,Integer>> iter = counters.entrySet().iterator(); while (iter.hasNext()) { Entry<Integer, Integer> entry = iter.next(); int entryValue = entry.getValue(); if (entryValue == 1) { iter.remove(); } else { // calling setValue() will update the original Map entry.setValue(entryValue - 1); } } } } // Reset the counters for second pass for (Entry<Integer,Integer> entry : counters.entrySet()) { entry.setValue(0); } // Second pass finds the actual frequency of each candidate for (int num : nums) { Integer count = counters.get(num); if (count != null) { counters.put(num, ++count); } } int threshold = nums.length / k; return counters.entrySet().stream() .filter((entry) -> entry.getValue() > threshold) .map((entry) -> entry.getKey()) .collect(Collectors.toList()); }
8
public static Filter annotatedWithType( Class<? extends Annotation> annotationType ) { if ( annotationType == null ) { throw new IllegalArgumentException( "Parameter 'annotationType' must not be null" ); } checkForRuntimeRetention( annotationType ); return new AnnotatedWithType( annotationType ); }
2
@Override public void learnNetworkRules(List<Pair> learningDataset, int startRuleNum, int endRuleNum, int epochPerRule) { double smallestError = 0; int bestRuleCount = 0; for (int r = startRuleNum; r <= endRuleNum; r++) { createRules(r); double iterError = 0; System.out.println("=========="); for (int e = 0; e < epochPerRule; e++) { iterError = learnNetwork(learningDataset); System.out.println("Rules: " + r + " Epoch: " + e + " Error: " + iterError); } if ( r == startRuleNum || iterError < smallestError) { bestRuleCount = r; smallestError = iterError; } } System.out.println("Best Rule Count: " + bestRuleCount + " Error: " + smallestError); }
4
public void set_Intcon_value(int s) { if ((s & 0b00000001) == 1) { label_58.setText("1"); } else { label_58.setText("0"); } if ((s & 0b00000010) == 2) { label_57.setText("1"); } else { label_57.setText("0"); } if ((s & 0b00000100) == 4) { label_56.setText("1"); } else { label_56.setText("0"); } if ((s & 0b00001000) == 8) { label_55.setText("1"); } else { label_55.setText("0"); } if ((s & 0b00010000) == 16) { label_54.setText("1"); } else { label_54.setText("0"); } if ((s & 0b00100000) == 32) { label_53.setText("1"); } else { label_53.setText("0"); } if ((s & 0b01000000) == 64) { label_52.setText("1"); } else { label_52.setText("0"); } if ((s & 0b10000000) == 128) { label_51.setText("1"); } else { label_51.setText("0"); } }
8
public int addLoadParameters(CtClass[] params, int offset) { int stacksize = 0; if (params != null) { int n = params.length; for (int i = 0; i < n; ++i) stacksize += addLoad(stacksize + offset, params[i]); } return stacksize; }
2
private static String changeFirstCharacterCase(String str, boolean capitalize) { if (str == null || str.length() == 0) { return str; } StringBuilder sb = new StringBuilder(str.length()); if (capitalize) { sb.append(Character.toUpperCase(str.charAt(0))); } else { sb.append(Character.toLowerCase(str.charAt(0))); } sb.append(str.substring(1)); return sb.toString(); }
3
@Override public void run() { while(true){ if(engine.getSide().equalsIgnoreCase("None")){ serverTick(); clientTick(); } else if(engine.getSide().equalsIgnoreCase("Client")){ clientTick(); } else if(engine.getSide().equalsIgnoreCase("Server")){ serverTick(); } try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } }
5
@Override //Quick and dirty implementation, needs some hard revision public AbstractStochasticLotSizingSolution solve( AbstractStochasticLotSizingProblem problem, boolean[] setupPattern) throws SolvingInitialisiationException, ConvolutionNotDefinedException { //Check inputs if (problem.getPeriods().length != setupPattern.length) throw new SolvingInitialisiationException("Problem and setup pattern have different planning horizons."); //Get the vector of aggregated demand (there is no ADI in this approach) RealDistribution[] demand = new RealDistribution[problem.getPeriods().length]; for (int i = 0; i < demand.length; i++){ demand[i] = problem.getPeriods()[i].totalDemand(); } int setupPeriod = -1; RealDistribution cycleDemand = null; double inventoryCost = 0.0; double setupCost = 0.0; double[] orderUpToLevel = new double[setupPattern.length]; for (int t = 0; t < demand.length;t++){ if (setupPattern[t]){ setupCost += problem.getPeriods()[t].getSetupCost(); cycleDemand = problem.getPeriods()[t].totalDemand(); int nextSetupPeriod = t+1; while(nextSetupPeriod < demand.length && !setupPattern[nextSetupPeriod]){ cycleDemand = Convoluter.convolute(cycleDemand, cycleDemand = problem.getPeriods()[nextSetupPeriod].totalDemand()); nextSetupPeriod++; } orderUpToLevel[t] = cycleDemand.inverseCumulativeProbability(problem.getServiceLevel()); setupPeriod = t; cycleDemand = problem.getPeriods()[t].totalDemand(); StockFunction stockFunction = new StockFunction(cycleDemand); inventoryCost += problem.getPeriods()[t].getInventoryHoldingCost()*stockFunction.value(orderUpToLevel[setupPeriod]); } else{ cycleDemand = Convoluter.convolute(cycleDemand,problem.getPeriods()[t].totalDemand()); StockFunction stockFunction = new StockFunction(cycleDemand); inventoryCost += problem.getPeriods()[t].getInventoryHoldingCost()*stockFunction.value(orderUpToLevel[setupPeriod]); } } return new SimpleStochasticLotSizingSolution(setupCost, inventoryCost, "Order-up-to-level", orderUpToLevel, setupPattern); }
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(ProjectileSolver.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ProjectileSolver.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ProjectileSolver.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ProjectileSolver.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 ProjectileSolver().setVisible(true); } }); }
6
public void processMouseEvent(MouseEvent event) { transformMouseEvent(event); super.processMouseEvent(event); }
0
boolean isAttackPlaceHorizontallyRightNotHarming(int position, char[] boardElements, int dimension, int rightPosition) { while (rightPosition > 0) { if (isPossibleToPlaceRight(position, dimension, rightPosition) && isBoardElementAnotherFigure(boardElements[position + rightPosition])) { return false; } rightPosition--; } return true; }
3
public LinkedList<Integer> searchForPattern(String pattern, String context) { LinkedList<Integer> foundPatternList = new LinkedList<Integer>(); int patternLength = pattern.length(); int contextLength = context.length(); for(int contextIndex = 0; contextIndex <= contextLength - patternLength; contextIndex++) { int match = 0; for(int patternIndex = 0; patternIndex < patternLength; patternIndex++) { if(pattern.charAt(patternIndex) == context.charAt(patternIndex+contextIndex)) {comparisons++; match++;} else {comparisons++; break;} } if(match == patternLength) foundPatternList.add(contextIndex); comparisons++; } return foundPatternList; }
4
public void visitForceChildren(final TreeVisitor visitor) { if (visitor.reverse()) { target.visit(visitor); } for (int i = 0; i < operands.size(); i++) { final LocalExpr expr = (LocalExpr) operands.get(i); expr.visit(visitor); } if (!visitor.reverse()) { target.visit(visitor); } }
3
public static void weekPrediction(String inputFile) throws FileNotFoundException, IOException{ String line, season = null, jornada = null; ArrayList<String> matchs1 = new ArrayList<>(); ArrayList<String> matchs2 = new ArrayList<>(); Boolean primera = false, segunda = false; FileReader fr = new FileReader(new File(inputFile)); BufferedReader br = new BufferedReader(fr); while ((line = br.readLine()) != null ){ if (line.contains("Primera")){ primera = true; line = br.readLine(); season = line.split(" ")[line.split(" ").length-1]; line = br.readLine(); } if(line.contains("Segunda")){ primera = false; segunda = true; line = br.readLine(); season = line.split(" ")[line.split(" ").length-1]; line = br.readLine(); } if(primera){ matchs1.add(line); } if(segunda){ matchs2.add(line); } } br.close(); try { weekArffFile(matchs1,matchs2, season, jornada); } catch (SAXException ex) { ex.printStackTrace(); } catch (SQLException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } }
8
public static Throwable unwrap(Throwable e) { Throwable unwrapp = e; while (true) { if (unwrapp instanceof InvocationTargetException) { unwrapp = ((InvocationTargetException) unwrapp).getTargetException(); } else if (unwrapp instanceof UndeclaredThrowableException) { unwrapp = ((UndeclaredThrowableException) unwrapp).getUndeclaredThrowable(); } else { return unwrapp; } } }
3
private int evalRPNHelper( List<String> los ){ // trivial case if ( los.size() == 1 ) { return Integer.parseInt(los.get(0)); } // non trivial case // 1. process the los List<String> ret = new ArrayList<>(); int i = 2; // index while ( i < los.size() ){ if ( isOperator( los.get(i)) ){ // once the first operator is found , break. int k = compute(los.get(i-2), los.get(i-1), los.get(i)); ret.add( Integer.toString(k) ); ret.addAll( los.subList(i+1, los.size())); break; } ret.add( los.get(i-2) ); ++i; } // 2. do recursion on the result return evalRPNHelper(ret); }
3
public void readAndParse() throws IOException { String currentLine; int i = 0; Map<Character,Set<Tile>> layoutToUse = wholeLayout1; try{ while((currentLine = cleanLine(lineReader.readLine())) != null) { if(currentLine.length() > 0) { if(currentLine.charAt(0) == '*' && layoutToUse == wholeLayout1) layoutToUse = wholeLayout2; else if(currentLine.charAt(0) == '*') throw new IllegalArgumentException("Parse error: More than one * line!"); else if(pushLineToSet(currentLine, layoutToUse, i)) i--; // Y coordinates must be descending as the file is read top to bottom } } } catch (IllegalArgumentException e) { throw new IllegalArgumentException(e.getMessage() + " at line #" + (-i)); } // Now parse the wholeLayouts to the Board and WinningPosition. parseLayouts(); }
7
public EncryptedDataType getEncryptedValue() { return encryptedValue; }
0
public void Logar() { //cria duas variaveis para receber os dados de login do usuario String login = txtLogin.getText(); String Senha = txtSenha.getText(); //Verifica se a senha digitada estar cadastrada no banco de forma criptografada //hash sha-256 criptografiaUtil criptografiaSenha = new criptografiaUtil(); Senha = criptografiaSenha.criptografiaSenha(Senha); //A variavel userLogado recebe os dados do usuario que realizou o login LoginBO logarBO = new LoginBO(); try { userLogado = logarBO.Logar(login, Senha); getInstancia().setVisible(true); this.dispose(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao Logar no Sistema !!!", "Erro", JOptionPane.ERROR_MESSAGE); } catch (excecaoLogin ex) { JOptionPane.showMessageDialog(null, "login ou Senha Inválidos", "Erro", JOptionPane.ERROR_MESSAGE); } }
2
private void fireNewPeerConnection(Socket socket, byte[] peerId) { for (IncomingConnectionListener listener : this.listeners) { listener.handleNewPeerConnection(socket, peerId); } }
1
public void setPlayer1Name(JLabel label) { boolean test = false; if (test || m_test) { System.out.println("Drawing :: setPlayer1Name() BEGIN"); } m_player1Name = label; if (test || m_test) System.out.println("Drawing:: setPlayer1Name() - END"); }
4
public void run() { // Make the initial map data, convert to PIT format String parts[] = gameData.split("\\|"); String planets[] = parts[0].split(":"); String planetData[]; StringBuilder map = new StringBuilder(); StringBuilder planet; for (String p : planets) { planetData = p.split("\\,"); planet = new StringBuilder("P"); for (String _p : planetData) { planet.append(" "); planet.append(_p); } map.append(planet.toString()); map.append("\n"); } String mapPIT = map.toString(); String turns[] = parts[1].split(":"); // Create the games by issuing the same orders as the game would // copy the object each move into a buffer for rendering games = new Game[turns.length]; // initial game object Game tGame = new Game(mapPIT, turns.length + 1, 1, "log.txt"); tGame.Init(); for (int i = 0; i < turns.length; ++i) { Game thisFrame = (Game)tGame.clone(); String[] items = turns[i].split("\\,"); for (int j = 0; j < tGame.NumPlanets(); ++j) { Planet p = thisFrame.GetPlanet(j); String[] fields = items[j].split("\\."); p.Owner(Integer.parseInt(fields[0])); p.NumShips(Integer.parseInt(fields[1])); } //System.out.println("NumPlanets: " + tGame.NumPlanets()); //System.out.println("Items:"); //for (int j = 0; j < items.length; ++j) { // System.out.println(" " + j + ": " + items[j]); //} for (int j = tGame.NumPlanets(); j < items.length; ++j) { String[] fields = items[j].split("\\."); Fleet f = new Fleet(Integer.parseInt(fields[0]), Integer.parseInt(fields[1]), Integer.parseInt(fields[2]), Integer.parseInt(fields[3]), Integer.parseInt(fields[4]), Integer.parseInt(fields[5])); thisFrame.AddFleet(f); } games[i] = thisFrame; } for (JButton btn : buttons) { if (btn != pauseButton) btn.setEnabled(true); } lastClicked = pauseButton; progress.setIndeterminate(false); progress.setMaximum(100 * games.length); progress.setStringPainted(true); progress.setString("0 / " + Integer.toString(games.length)); int millisecondsBetweenFrames = (int)((double)1000 / desiredFramerate); timer = new Timer(millisecondsBetweenFrames, this); timer.setActionCommand("animTick"); update(); }
7
public boolean chunkExists(int par1, int par2) { if (!this.canChunkExist(par1, par2)) { return false; } else if (par1 == this.lastQueriedChunkXPos && par2 == this.lastQueriedChunkZPosition && this.lastQueriedChunk != null) { return true; } else { int var3 = par1 & 31; int var4 = par2 & 31; int var5 = var3 + var4 * 32; return this.chunks[var5] != null && (this.chunks[var5] == this.blankChunk || this.chunks[var5].isAtLocation(par1, par2)); } }
6
public int getNumberOfZombie(){ int res = 0; for (Being being: beings){ if (being.isZombie()){ res++; } } return res; }
2
public URIMatcher setPort(Integer port) { this.port = port==null?null:(port <= NO_PORT ? NO_PORT : port); return this; }
2
public LocalInfo getLocalInfo() { if (shadow != null) { while (shadow.shadow != null) { shadow = shadow.shadow; } return shadow; } return this; }
2
@Override public synchronized void addReliable(int connectPort) throws RemoteException { try { ServentDescriptor elem = new ServentDescriptor(InetAddress.getByName(RemoteServer. getClientHost()), connectPort, 0); boolean found = false; for (int i = 0; i < reliableServents.size(); i++) { ServentDescriptor tmp = reliableServents.get(i); if (tmp.equals(elem)) { found = true; tmp.touch(); break; } } if (!found) { logger.appendMessage(elem + " dichiara di essere affidabile, lo aggiungo"); reliableServents.add(elem); } for (int i = 0; i < registeredServents.size(); i++) { try { registeredServents.get(i).signalReliableServent(elem); } catch (RemoteException e) { registeredServents.remove(i); } } } catch (UnknownHostException e) { } catch (ServerNotActiveException e) { } }
7
public String getSort() { return sort; }
0
@Override public <E extends ApiResponse> E execute(ApiRequest request, AbstractContentHandler contentHandler, Class<E> clazz) throws ApiException { ApiConnector connector = getConnector(); URL url = connector.getURL(request); Map<String, String> params = connector.getParams(request); InputStream inputStream = connector.getInputStream(url, params); String outputFileName = request.getPage().getPage() + "-" + new Date().getTime() + ".xml"; File outputFile = new File(destinationDirectory, outputFileName); FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(outputFile); inputStream = new InputStreamSplitter(inputStream, outputStream); } catch (FileNotFoundException e) { logger.error("Could not write response xml to file: ", e); } E response = getApiResponse(contentHandler, inputStream, clazz); if (outputStream != null) { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { logger.error("Could not flush/close response xml file: ", e); } } return response; }
3
public void paintExpression(Graphics g, Expression e, double xmid, double xfactor, double ymid, double yfactor) throws UnresolvedNameException { HashMap<String, Double> h = new HashMap<String, Double>(); double lastX = 0, lastY = 0; boolean hasBegan = false; for (double x = xbl; x < xbh; x += xscale) { h.put("x", Math.round(x / xscale) * xscale); double y = e.solve(h); //System.out.println("x = "+Math.round(x/xscale)*xscale+", y = "+y); if (Double.isInfinite(y) || Double.isInfinite(lastY) || Double.isNaN(y) || Double.isNaN(lastY)) hasBegan = false; if (hasBegan) { double xt1 = xmid + x * xfactor, yt1 = ymid - y * yfactor, xt2 = xmid + lastX * xfactor, yt2 = ymid - lastY * yfactor; g.drawLine((int)xt1, (int)yt1, (int)xt2, (int)yt2); } else hasBegan = true; lastX = x; lastY = y; } }
6
private void eltran(double[][] a, double[][] zz, int[] ordr, int n) { int i, j, m; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { zz[i][j] = 0.0; zz[j][i] = 0.0; } zz[i][i] = 1.0; } if (n <= 2) { return; } for (m = n - 1; m >= 2; m--) { for (i = m; i < n; i++) { zz[i][m - 1] = a[i][m - 2]; } i = ordr[m - 1]; if (i != m) { for (j = m - 1; j < n; j++) { zz[m - 1][j] = zz[i - 1][j]; zz[i - 1][j] = 0.0; } zz[i - 1][m - 1] = 1.0; } } }
7
protected void readChild(XMLStreamReader in) throws XMLStreamException { if (in.getLocalName().equals(Colony.getXMLElementTagName())) { settlement = updateFreeColGameObject(in, Colony.class); } else if (in.getLocalName().equals(IndianSettlement.getXMLElementTagName())) { settlement = updateFreeColGameObject(in, IndianSettlement.class); } else if (in.getLocalName().equals(UNITS_TAG_NAME)) { // @compat 0.10.1 while (in.nextTag() != XMLStreamConstants.END_ELEMENT) { if (in.getLocalName().equals(Unit.getXMLElementTagName())) { add(updateFreeColGameObject(in, Unit.class)); } } // end compatibility code } else if (in.getLocalName().equals(TileItemContainer.getXMLElementTagName())) { tileItemContainer = getGame().getFreeColGameObject(in.getAttributeValue(null, ID_ATTRIBUTE), TileItemContainer.class); if (tileItemContainer != null) { tileItemContainer.readFromXML(in); } else { tileItemContainer = new TileItemContainer(getGame(), this, in); } } else if (in.getLocalName().equals(PlayerExploredTile.getXMLElementTagName())) { // Only from a savegame: Player player = getGame().getFreeColGameObject(in.getAttributeValue(null, "player"), Player.class); PlayerExploredTile pet = getPlayerExploredTile(player); if (pet == null) { pet = new PlayerExploredTile(getGame(), in); playerExploredTiles.put(player, pet); } else { pet.readFromXML(in); } } else { super.readChild(in); } }
9
OutputInformation report_table_layout() { OutputInformation infos = new OutputInformation(); infos.add_parameter("V", "discretization", discretizer); if (predefinedFirstThreshold == null || predefinedSecondThreshold == null) { infos.add_parameter("P", "requested P-value", pvalue); } if (predefinedFirstThreshold != null) { infos.add_parameter("T1", "threshold for the 1st matrix", predefinedFirstThreshold); } if (predefinedSecondThreshold != null) { infos.add_parameter("T2", "threshold for the 2nd matrix", predefinedSecondThreshold); } infos.add_parameter("PB", "P-value boundary", pvalueBoundary); if (firstBackground.equals(secondBackground)) { infos.background_parameter("B", "background", firstBackground); } else { infos.background_parameter("B1", "background for the 1st model", firstBackground); infos.background_parameter("B2", "background for the 2nd model", secondBackground); } return infos; }
5
public static void main(String[] args) { Scanner input = new Scanner(System.in); //fuori dal try input.useLocale(Locale.US); boolean done = false; while(done!=true) { try { // Scanner input = new Scanner(System.in); //nel try // input.useLocale(Locale.US); /* perchè quando catturo InputMismatchException devo inizializzare la variabile oggetto input dentro il try, e invece quando catturo IllegalArgumentException invece il codice funziona anche se la variabile oggetto input è inizializzata fuori dal try? */ System.out.println("Inserire il saldo iniziale e il tasso di percentuale : "); double saldo = input.nextDouble(); double tasso = input.nextDouble(); //creo un oggetto contocorrente BankAccount contocorrente = new BankAccount(saldo); //applico due volte il metodo addInterest contocorrente.addInterest(tasso); contocorrente.addInterest(tasso); //saldo dopo due anni System.out.println("Il saldo del conto dopo due anni e' : "+contocorrente.getBalance()); System.out.println("Quanto vuoi prelevare?"); double soldi = input.nextDouble(); //applico il metodo withdraw contocorrente.withdraw(soldi); //nuovo saldo System.out.println("Il nuovo saldo del conto e' : "+contocorrente.getBalance()); input.close(); done = true; //chiudo il ciclo while } catch(IllegalArgumentException error) { System.out.println("Hai inserito un valore non valido!"); } catch(InputMismatchException e) { System.out.println("Hai inserito un valore non valido!"); } } }
3
public void printTransactions(boolean writeHeader, String fileNameTransactions){ try{ String outputFileName = folder + fileNameTransactions; FileWriter writer = new FileWriter(outputFileName, true); if (writeHeader){ writer.write("moHFT;mo;loHFT;lo;tradeTime;FV;Price;buyerPV;sellerPV;buyMO;buyerCosts;sellerCosts;timeLO;" + "\r"); } int sz = history.size(); double mo; // payoff from market order double lo; // payoff from limit order double loTime; // time of limit order submission int moHFT; // is the MO submitter HFT int loHFT; // is the LO submitter HFT int buyMO; for (int i = 0; i < sz; i++){ Trade t = history.get(i); if (t.getTimeBuyer() < t.getTimeSeller()){ // distinguishing if seller initiated mo = t.getPrice() - t.getSellerPV() - t.getFV(); moHFT = t.isSellerIsHFT() ? 1 : 0; lo = t.getFV() + t.getBuyerPV() - t.getPrice(); loHFT = t.isBuyerIsHFT() ? 1 : 0; buyMO = 0; // seller initiated order loTime = t.getTimeBuyer(); } else { mo = t.getFV() + t.getBuyerPV() - t.getPrice(); moHFT = t.isBuyerIsHFT() ? 1 : 0; lo = t.getPrice() - t.getSellerPV() - t.getFV(); loHFT = t.isSellerIsHFT() ? 1 : 0; buyMO = 1; // buyer initiated order loTime = t.getTimeSeller(); } //writer.writeDecisions(history.get(i).printTrade()); writer.write(moHFT + ";" + mo + ";" + loHFT + ";" + lo + ";" + t.getTimeTrade() + ";" + t.getFV() + ";" + t.getPrice() + ";" + t.getBuyerPV() + ";" + t.getSellerPV() + ";" + buyMO + ";" + t.getTrCostsBuyer() + ";" + t.getTrCostsSeller() + ";" + loTime + ";" + t.getFVbeforeBuyer() + ";" + t.getFVbeforeSeller() + ";" + "\r"); } writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
8
public static int returnMax(int[] arr, int start, int end, int n) { int mid = start + (end - start) / 2; // only one element if (mid == 0 && mid == n - 1) return mid; if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) return mid; if (mid > 0 && arr[mid - 1] > arr[mid]) return returnMax(arr, start, mid - 1, n); else return returnMax(arr, mid + 1, end, n); }
8
@Override public void run() { while(running) { try { String s = reader.readLine(); if(s != "" && s != null) { Log.info(s); Message m = new Message(s); m.parse(); } } catch (IOException e) { Log.error(e); } } }
4
public static void main(String args[]) { String filename; File f; if (args.length == 1) { f = new File(args[0]); try { parser = new LogoParser(new java.io.FileInputStream(f)); } catch (java.io.FileNotFoundException e) { e.printStackTrace(); return; } filename = f.getName(); } else { return; } try { code = parser.executeCompiler(); } catch (Exception e) { System.out.println(e.toString()); } if (code == null) { code = new TreeMap<Integer, AbsStatementNode>(); } // RUN UserInterface ui = new UserInterface(); ui.displayOn(); FileInputStream stream; try { stream = new FileInputStream(f); InputStreamReader ipsr = new InputStreamReader(stream); BufferedReader br = new BufferedReader(ipsr); String str; while ((str = br.readLine()) != null) { str += "\n"; ui.setCodeText(ui.getCodeText() + str); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } ExecutionContext context = new ExecutionContext(parser.getSymbolTable(), ui); for (Integer i : code.keySet()) { try { code.get(i).run(context); } catch (InterpretationException e) { System.out.println("Exception at code.get(" + i + ")"); System.out.println(code.get(i)); System.out.println(e.toString()); e.printStackTrace(); } } }
9
@Override public void e(float sideMot, float forMot) { if (this.passenger == null || !(this.passenger instanceof EntityHuman)) { super.e(sideMot, forMot); this.W = 0.5F; // Make sure the entity can walk over half slabs, // instead of jumping return; } EntityHuman human = (EntityHuman) this.passenger; if (!RideThaMob.control.contains(human.getBukkitEntity().getName())) { // Same as before super.e(sideMot, forMot); this.W = 0.5F; return; } this.lastYaw = this.yaw = this.passenger.yaw; this.pitch = this.passenger.pitch * 0.5F; // Set the entity's pitch, yaw, head rotation etc. this.b(this.yaw, this.pitch); // https://github.com/Bukkit/mc-dev/blob/master/net/minecraft/server/Entity.java#L163-L166 this.aO = this.aM = this.yaw; this.W = 1.0F; // The custom entity will now automatically climb up 1 // high blocks sideMot = ((EntityLiving) this.passenger).bd * 0.5F; forMot = ((EntityLiving) this.passenger).be; if (forMot <= 0.0F) { forMot *= 0.25F; // Make backwards slower } sideMot *= 0.75F; // Also make sideways slower float speed = 0.35F; // 0.2 is the default entity speed. I made it // slightly faster so that riding is better than // walking this.i(speed); // Apply the speed super.e(sideMot, forMot); // Apply the motion to the entity try { Field jump = null; jump = EntityLiving.class.getDeclaredField("bc"); jump.setAccessible(true); if (jump != null && this.onGround) { // Wouldn't want it jumping // while // on the ground would we? if (jump.getBoolean(this.passenger)) { double jumpHeight = 0.5D; this.motY = jumpHeight; // Used all the time in NMS for // entity jumping } } } catch (Exception e) { e.printStackTrace(); } }
8
protected Object getPrimitive(Element node) throws Exception { Object result; Object tmpResult; Class cls; cls = determineClass(node.getAttribute(ATT_CLASS)); tmpResult = Array.newInstance(cls, 1); if (cls == Boolean.TYPE) Array.set(tmpResult, 0, new Boolean(XMLDocument.getContent(node))); else if (cls == Byte.TYPE) Array.set(tmpResult, 0, new Byte(XMLDocument.getContent(node))); else if (cls == Character.TYPE) Array.set(tmpResult, 0, new Character(XMLDocument.getContent(node).charAt(0))); else if (cls == Double.TYPE) Array.set(tmpResult, 0, new Double(XMLDocument.getContent(node))); else if (cls == Float.TYPE) Array.set(tmpResult, 0, new Float(XMLDocument.getContent(node))); else if (cls == Integer.TYPE) Array.set(tmpResult, 0, new Integer(XMLDocument.getContent(node))); else if (cls == Long.TYPE) Array.set(tmpResult, 0, new Long(XMLDocument.getContent(node))); else if (cls == Short.TYPE) Array.set(tmpResult, 0, new Short(XMLDocument.getContent(node))); else throw new Exception("Cannot get primitive for class '" + cls.getName() + "'!"); result = Array.get(tmpResult, 0); return result; }
8
public void setAccessToken_secret(String accessToken_secret) { this.accessToken_secret = accessToken_secret; }
0
public String getYearStr() { if (year <= 0) { return ""; } return String.valueOf(year); }
1
public void clearProxies() { for (OutlineProxy proxy : mProxies) { mModel.removeListener(proxy); } mProxies.clear(); }
1
public String toMachineString() { String machineString; if (OPCODE.getValue() == 13 || OPCODE.getValue() == 10) { //For HALT and SKZ instructions with no fields return OPCODE.toString(); } if (OPCODE.getValue() > 7 && OPCODE.getValue() < 10) { //For branch instructions with only one field machineString = OPCODE.getValue() + " " + Integer.toHexString(this.getField1()).toUpperCase(); return machineString; } //For all those instructions with two fields (Transfer and Arithmetic). machineString = OPCODE.getValue() + " " + Integer.toHexString(this.getField1()).toUpperCase() + " " + Integer.toHexString(this.getField2()).toUpperCase(); return machineString; }
4
@Override public void execute() throws MojoExecutionException, MojoFailureException { final InputStream license = OverMapped.class.getResourceAsStream("/COPYING.HEADER.TXT"); if (license != null) { try { getLog().info(new String(ByteStreams.toByteArray(license), "UTF8")); } catch (final IOException ex) { getLog().warn("Missing LICENSE data", ex); } finally { try { license.close(); } catch (final IOException e) { } } } else { getLog().warn("Missing LICENSE data"); } try { process(); } catch (final MojoExecutionException ex) { throw ex; } catch (final MojoFailureException ex) { throw ex; } catch (final Throwable t) { throw new MojoExecutionException(null, t); } }
6
@EventHandler(ignoreCancelled = true) public void onInventoryClick(InventoryClickEvent e) { HumanEntity human = e.getWhoClicked(); if(!(human instanceof Player)) { return; } Player p = (Player)human; Dodgeball m; if((m = mm.getPlayerMinigame(p.getName())) == null) { return; } m.handlePlayerInventoryClick(e); }
2
public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new FileReader("msched.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("msched.out"))); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); sorted = new int[n]; checked = new boolean[n]; int[] time = new int[n]; for(int i=0; i<n; i++){ time[i] = Integer.parseInt(br.readLine()); } int[] incomingCount = new int[n]; pointer = new int[n+1]; edges = new int[m]; int[] x = new int[m]; int[] y = new int[m]; for(int i=0; i<m; i++){ st = new StringTokenizer(br.readLine()); x[i] = Integer.parseInt(st.nextToken())-1; y[i] = Integer.parseInt(st.nextToken())-1; pointer[y[i]]++; incomingCount[x[i]]++; } for(int i=0; i<n; i++) pointer[i+1]+=pointer[i]; for(int i=0; i<m; i++){ edges[--pointer[y[i]]] = x[i]; } for(int i=0; i<n; i++){ if(incomingCount[i]==0){ dfs(i); } } int[] max = new int[n]; for(int u=0; u<n; u++){ int i = sorted[u]; max[i] = time[i]; for(int e=pointer[i]; e<pointer[i+1]; e++){ int j = edges[e]; max[i] = Math.max(max[i], max[j]+time[i]); } } int result = 0; for(int i=0; i<n; i++){ result = Math.max(result, max[i]); } System.out.println(result); out.close(); }
9
public static void main(String[] args) { int n = 20; for(int j = 1; j < MAX_NUMCHANGE; j++){ for(double eP = 0.5; eP < 1; eP+=.1){ eP = ((double)(Math.round(eP * 10)) / 10); int sig = 0; int before = 0; int total = 0; long start = System.currentTimeMillis(); System.out.println("eP: " + eP + " numChange: " + j); for(int y = 0; y < NUM_TRIALS; y++){ UndirectedGraph<Vertex> g = Main.createGraph(n, eP); GreedyColoring.color(g, 3); if(Main.getUncoloredCount(g) > 0){ sig++; before += Main.getUncoloredCount(g); Searcher searcher = new N_Changer(g, 3, j); for(int x = 0; x < STEPS_PER_TRIAL; x++){searcher.step();} // searcher.complete(); for(Vertex v : g.getVertices()) { if(v.getColor() < 0) total++; } } if(y == NUM_TRIALS - 1 /*|| y % PRINT_FREQ == PRINT_FREQ - 1*/) { int done = y + 1; long elapse = System.currentTimeMillis() - start; System.out.printf("after%4d trials:%6.2f uncolored,%7.2f ms elapsed\n", done, (double) total / sig, (double) elapse / sig); System.out.println(" sig: " + sig + " before: " + before + " after: " + total + " Percent gain: " + (1.0-(double)total/before)); } } } } }
8
public boolean isBypassable(Player player) { String name = player.getDisplayName(); if (owner == null) { Citadel.severe(String.format("isBypassable(%s) encountered unowned reinforcement: %s", name, toString())); sendMessage(player, ChatColor.RED, "This reinforcement has an issue. Please send modmail."); return false; } switch (securityLevel) { case PRIVATE: return name.equals(owner.getFounder()); default: return name.equals(owner.getFounder()) || owner.isModerator(name); } }
3
@RequestMapping(value = "/uploadFile.vpage", method=RequestMethod.POST) String uploadFile(@RequestParam("filedata") MultipartFile file,Model model, HttpServletResponse response) throws IOException { String originalFileName = file.getOriginalFilename(); String contentType = file.getContentType(); int pointIndex = originalFileName.lastIndexOf("."); String filename = originalFileName.substring(0,pointIndex); System.out.println(filename); String filetype = originalFileName.substring(pointIndex + 1); System.out.println(filetype); Resource resource = new ClassPathResource("swfconfig.properties"); Properties props = PropertiesLoaderUtils.loadProperties(resource); String baseSwfDir = props.getProperty("swfCacheDir"); try { InputStream stream = file.getInputStream(); mongoDb.uploadFile(originalFileName,contentType,stream); File fs = new File(baseSwfDir+originalFileName); file.transferTo(fs); //转换为swf格式文件 if(filetype.equals("doc") ||filetype.equals("docx") ||filetype.equals("ppt") ||filetype.equals("pptx") ||filetype.equals("xls") ||filetype.equals("xlsx")){ //当为这几种格式时,转为swf格式存储起来 readFile.convertSwf(fs,filename,filetype,baseSwfDir); } } catch (IOException e) { e.printStackTrace(); } return "redirect:/studentMainPage.vpage"; }
7
public void updateEffects() { for(int var1 = 0; var1 < 4; ++var1) { for(int var2 = 0; var2 < this.fxLayers[var1].size(); ++var2) { EntityFX var3 = (EntityFX)this.fxLayers[var1].get(var2); var3.onUpdate(); if(var3.isDead) { this.fxLayers[var1].remove(var2--); } } } }
3
public void analyzeIdentifier(Identifier ident) { if (ident == null) throw new NullPointerException(); toAnalyze.add(ident); }
1
public void play() throws IOException { String response; if (isMultiplayer) { while (true) { response = in.readLine(); if (response.startsWith("LEGAL_MOVE")) { currentButton.setText(team); } else if (response.startsWith("OPPONENT_MOVED")) { setOpponentsMove(Integer.parseInt(response.split(" ")[1])); } else if (response.startsWith("ENDING")) { String ending = response.split(" ")[1]; if ("WON".equals(ending)) { endOfGame("You win!!"); } else if ("LOST".equals(ending)) { endOfGame("Sorry you lose."); } else if ("DRAW".equals(ending)) { endOfGame("Cat's game... it's a draw!"); } } else if (response.startsWith("MESSAGE")) { } } } else { } }
9
@Override public void deserialize(Buffer buf) { presetId = buf.readByte(); if (presetId < 0) throw new RuntimeException("Forbidden value on presetId = " + presetId + ", it doesn't respect the following condition : presetId < 0"); symbolId = buf.readByte(); if (symbolId < 0) throw new RuntimeException("Forbidden value on symbolId = " + symbolId + ", it doesn't respect the following condition : symbolId < 0"); mount = buf.readBoolean(); int limit = buf.readUShort(); objects = new PresetItem[limit]; for (int i = 0; i < limit; i++) { objects[i] = new PresetItem(); objects[i].deserialize(buf); } }
3
protected int[] determineIndices(int numAttributes) throws Exception { int[] result; Vector<Integer> list; int i; StringTokenizer tok; String token; String[] range; int from; int to; list = new Vector<Integer>(); // parse range tok = new StringTokenizer(m_NewOrderCols, ","); while (tok.hasMoreTokens()) { token = tok.nextToken(); if (token.indexOf("-") > -1) { range = token.split("-"); if (range.length != 2) throw new IllegalArgumentException("'" + token + "' is not a valid range!"); from = determineIndex(range[0], numAttributes); to = determineIndex(range[1], numAttributes); if (from <= to) { for (i = from; i <= to; i++) list.add(i); } else { for (i = from; i >= to; i--) list.add(i); } } else { list.add(determineIndex(token, numAttributes)); } } // turn vector into int array result = new int[list.size()]; for (i = 0; i < list.size(); i++) result[i] = list.get(i); return result; }
7
private String preMakeRoom(javax.swing.JTextArea Area) { String bs = ""; int act = Area.getCaretPosition(); try { String ant = Area.getText(act - 1, 1); if (!ant.equalsIgnoreCase("\n")) { bs = "\n"; } } catch (BadLocationException ex) {} return bs; }
2
public static void main(String[] args) { try { Logger logger = LoggerFactory.newLogger(LoggerFactory.CONSOLE); logger.connect(); logger.log("test message #1"); logger.disconnect(); } catch (CannotConnectException cce) { System.err.println("cannot connect to console-based logger"); } catch (NotConnectedException nce) { System.err.println("not connected to console-based logger"); } try { Logger logger = LoggerFactory .newLogger(LoggerFactory.FILE, "x.txt"); logger.connect(); logger.log("test message #2"); logger.disconnect(); } catch (CannotConnectException cce) { System.err.println("cannot connect to file-based logger"); } catch (NotConnectedException nce) { System.err.println("not connected to file-based logger"); } try { Logger logger = LoggerFactory.newLogger(LoggerFactory.FILE); logger.connect(); logger.log("test message #3"); logger.disconnect(); } catch (CannotConnectException cce) { System.err.println("cannot connect to file-based logger"); } catch (NotConnectedException nce) { System.err.println("not connected to file-based logger"); } }
6
public pair ge_add_expression(TextArea area,SimpleNode node,String prefix)throws SemanticErr{ SimpleNode left = (SimpleNode) node.jjtGetChild(0); int ex_num = node.jjtGetNumChildren(); if(ex_num==1) return ge_mul_expression(area, left, prefix); else { pair left_pair =ge_mul_expression(area, left, prefix); for (int i = 0; i < ex_num - 2; ) { SimpleNode right = (SimpleNode) node.jjtGetChild(i + 2); pair right_pair =ge_mul_expression(area,right,prefix); SimpleNode ope = (SimpleNode) node.jjtGetChild(i + 1); if(ope.jjtGetFirstToken().toString().equals("+")) { ge_operation(area,"+",left_pair.var,right_pair.var,prefix); left_pair.ret=1; left_pair.var="%add"+String.valueOf(add_num-1); } else if(ope.jjtGetFirstToken().toString().equals("-")){ ge_operation(area,"-",left_pair.var,right_pair.var,prefix); left_pair.ret=2; left_pair.var="%sub"+String.valueOf(sum_num-1); } i = i + 2; } return left_pair; } }
4
private ArrayList<Integer> getNineInvertedDigits(int value) { ArrayList<Integer> result = new ArrayList<Integer>(); if (value == 0) result.add(0); else while (value > 0) { int digit = value % 9; result.add(digit); value = value / 9; } return result; }
2
public boolean equals(Object other) { // standard two checks for equals() if (this == other) return true; if (!(other instanceof TPoint)) return false; // check if other point same as us TPoint pt = (TPoint)other; return(x==pt.x && y==pt.y); }
3
public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { //String st=request.getParameter("name"); //int i=Integer.parseInt(st); String str=request.getParameter("name"); /*String str1=request.getParameter("option1"); String str2=request.getParameter("option2"); String str3=request.getParameter("option3"); String str4=request.getParameter("option4");*/ response.setContentType("text/html"); PrintWriter out=response.getWriter(); Connection conn; Statement stmt; HttpSession hs=request.getSession(true); String str5=(hs.getAttribute("Qu1").toString()); int i1=Integer.parseInt(str5); try { Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/chaitanya","root",""); System.out.println("connection successful"); stmt=conn.createStatement(); stmt.executeUpdate("insert into result values('"+str+"',"+i1+")"); } catch(SQLException e1) { } catch(ClassNotFoundException e1) { } out.println("<html>"); out.println("<head>"); out.println("<img src=\"C:\\Users\\pankaj\\Downloads\\images\\icon1.jpg\">"); out.println("</img>"); out.println("<h2>data added succesfully</h2>"); out.println("</head>"); out.println("<body bgcolor\"skyblue\">"); //out.println("<br>"); out.println("<a href=\"http://localhost:8080/ExaminationSoftware/HOME.html\" >"); out.println("back</a>"); out.println("</body>"); out.println("</html>"); }
2
private static boolean isAlnumUline(char ch){ if(ch > 'a' && ch < 'z' || ch > 'A' && ch < 'Z' || ch > '0' && ch < '9' || ch == '_'){ return true; } return false; }
7
public String formatOrganization_name(String value) { String[] delimiterlist = {" ", "-", "_", "'", "."}; String[] abbreviationlist = {"ag", "bvba", "cv", "cvba", "cvoa", "esv", "nv", "pvba", "vzw"}; boolean first = true; boolean afterdelimiter = false; int index = 0; String destination = ""; String token = ""; try { // Replace illegal characters value = value.replaceAll(" & ", " en "); value = value.replaceAll("& ", "en "); value = value.replaceAll(" &", " en"); value = value.replaceAll("&", " en "); value = value.replaceAll(" / ", " of "); value = value.replaceAll("/ ", "of "); value = value.replaceAll(" /", " of"); value = value.replaceAll("/", " of "); value = value.replaceAll("\\\\", ""); value = value.replaceAll("<", ""); value = value.replaceAll(">", ""); char[] sourcevalue = new char[value.length()]; value = value.toLowerCase(); value.getChars(0, value.length(), sourcevalue, 0); for (char c : sourcevalue) { // Begin with a capital if (first) { destination = destination.concat(String.valueOf(c).toUpperCase()); first = false; } else { // Capital after delimiter if (afterdelimiter) { destination = destination.concat(String.valueOf(c).toUpperCase()); } else { destination = destination.concat(String.valueOf(c).toLowerCase()); } } // Check for delimiter, next character will be in uppercase afterdelimiter = false; for (String delimiter : delimiterlist) { if (String.valueOf(c).equals(delimiter)) { afterdelimiter = true; } } } // Check for abbreviations that should be in uppercase for (String abbreviation : abbreviationlist) { token = " ".concat(abbreviation); if (destination.toLowerCase().endsWith(token)) { index = destination.toLowerCase().indexOf(token); destination = destination.substring(0, index).concat(token.toUpperCase()).concat(destination.substring(index + token.length())); } else { token = abbreviation.concat(" "); if (destination.toLowerCase().startsWith(token)) { destination = destination.substring(0, index).concat(token.toUpperCase()).concat(destination.substring(index + token.length())); } } } destination = destination.replaceAll(" En ", " en "); destination = destination.replaceAll(" Of ", " of "); //this.organization_name = destination.trim(); return destination.trim(); } catch (Exception e) { Logger.getLogger(Contact.class.getName()).log(Level.SEVERE, null, e); return ""; } }
9
private void drawNode(No no, Graphics g) { g.drawRoundRect(no.getX(), no.getY(), no.computeSize(), hNo, 25, 25); if (no==busca){ int pos=0; for(int i=0 ; i < no.getN() ; i++){ if(no.getChave().get(i)==keyBusca) pos=i; } if (pos==0) g.drawOval(no.getX(), no.getY(), 25, 25); else g.drawOval(no.getX()+pos*(lEntreChaves+lNumero), no.getY(), 25, 25); } for (int i = 0; i < no.getN(); i++) { int atual = no.getChave().get(i); int x = no.getX() + i * (lNumero + lEntreChaves) + 5; g.drawString(Integer.toString(atual), x, no.getY() + 15); } if (!no.isFolha()) { for (int i = 0; i < no.getN() + 1; i++) { No filho = no.getFilho().get(i); g.drawLine(no.getX() + (i * 25) + 3, no.getY() + 7 * hNo / 8, filho.getX() + (filho.computeSize() / 2), filho.getY()); drawNode(filho, g); } } //busca=null; //keyBusca=0; }
7
public void plot(ArrayList<DatasetPattern> dataset,ArrayList<Cluster> clusters){ XYSeriesCollection datasetCollection = new XYSeriesCollection(); for (int i = 0; i < clusters.size(); i++) { Cluster c = clusters.get(i); if(!c.getIsActive()) continue; ArrayList<DenseRegion> regions = c.getRegions(); int totalNumberOfPoints = 0; for (int j = 0; j < regions.size(); j++) { totalNumberOfPoints+= regions.get(j).getPoints().size(); } if(totalNumberOfPoints < 50) continue; XYSeries series = new XYSeries(i); for (int j = 0; j < regions.size(); j++) { DenseRegion r = regions.get(j); ArrayList<Integer> points = r.getPoints(); for (int k = 0; k < points.size(); k++) { DatasetPattern p = dataset.get(points.get(k)); series.add(p.getFeatureVector().get(0), p.getFeatureVector().get(1)); } } datasetCollection.addSeries(series); } JFreeChart chart = ChartFactory.createScatterPlot("Clusters", "X", "Y", datasetCollection, PlotOrientation.VERTICAL, true, true, false); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); setContentPane(chartPanel); }
6
public boolean match(String pattern) { Queue<Entry<String, NfaNode>> queue = new LinkedList<>(); queue.addAll(start.getAllTransitions()); if (finalStates.contains(start) || epsilonTransitionsToFinal(start)) queue.add(createEntry("~", start)); Entry<String, NfaNode> entry = null; for (int i = 0; i < pattern.length(); i++) { Set<Entry<String, NfaNode>> toAdd = new HashSet<>(); char c = pattern.charAt(i); while (!queue.isEmpty()) { entry = queue.poll(); if (entry.getKey().contains(EPSILON)) queue.addAll(entry.getValue().getAllTransitions()); if (entry.getKey().charAt(0) == c) { toAdd.addAll(entry.getValue().getAllTransitions()); if (i == pattern.length()-1 && (finalStates.contains(entry.getValue()) || epsilonTransitionsToFinal(entry.getValue()))) return true; } } queue.addAll(toAdd); } return false; }
9
private static String formatTime(long time){ // Given time in seconds. int sec = (int)(time / Framework.milisecInNanosec / 1000); // Given time in minutes and seconds. int min = sec / 60; sec = sec - (min * 60); String minString, secString; if(min <= 9) minString = "0" + Integer.toString(min); else minString = "" + Integer.toString(min); if(sec <= 9) secString = "0" + Integer.toString(sec); else secString = "" + Integer.toString(sec); return minString + ":" + secString; }
2