text
stringlengths
14
410k
label
int32
0
9
public boolean swiftRight(int idUser, boolean pickup) { int passengers = 0; int i = 0, j = 0; Action a; Action n = new Action(idUser, pickup); for (i = 0; i < size(); ++i) { //Encontrar la acción a = get(i); if (a.idUser == idUser && a.isPickup == pickup) break; else if (a.isPickup) ++passengers; else --passengers; } for (j = i+1; j < size()-1; --j) { //Encontrar una posición válida a = get(j); if (a.idUser == idUser) break; else if (a.isPickup) ++passengers; else --passengers; if (passengers < 3) { add(j+1, n); remove(i); return true; } } return false; }
8
private void loadObjects(){ FileReader reader = null; try{ String path = "D:\\SpringProjects\\TheGreyWolves\\FishingBoat\\msmunchen.obj"; if(unit!= null){ if(unit.getType()==TYPE.DESTROER){ path = "D:\\SpringProjects\\TheGreyWolves\\WICK40\\Wick40.obj"; }else if(unit.getType()==TYPE.SUBMARINE){ path = "D:\\SpringProjects\\TheGreyWolves\\U48\\U48.obj"; } } File file = new File(path); reader = new FileReader(file); ObjectFile f = new ObjectFile (); f.setFlags (ObjectFile.RESIZE | ObjectFile.TRIANGULATE | ObjectFile.STRIPIFY); temp = f.load (reader); reader.close(); }catch(Exception e){ System.out.println("Something is not working"); e.printStackTrace(); }finally{ if(reader!=null) try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
6
@Override public void run() { //Novo scanner usando o teclado como entrada Scanner scanner = new Scanner(System.in); try{ while(true){ if(stop) break; //operação bloqueante, travar até ser digitado algo e apertado enter String line = scanner.nextLine(); //limpa o que está no buffer oos.flush(); MessageType type = CommandUtil.getType(line); //verificar se é o /quit if(type == MessageType.command && CommandUtil.getCommand(line) == Command.quit){ listener.close(); } //manda a nova mensagem para o socket oos.writeObject(new Message(username, line, type)); } oos.close(); }catch(IOException e){ e.printStackTrace(); } }
5
public static String read(String filename) { try { BufferedReader br = new BufferedReader(new FileReader(filename)); String inputLine; StringBuffer sb = new StringBuffer(); while ((inputLine = br.readLine()) != null) { sb.append(inputLine + "\n"); } br.close(); return sb.toString(); } catch (IOException e) { System.out.println(filename + " is not ready"); return NOTYET_STRING; } }
2
private String valida(HttpServletRequest request, Notas notas) { String error = null; String idnota = request.getParameter("idnota"); String idalumno = request.getParameter("idalumno"); String nota = request.getParameter("nota"); Integer idnotax = null; if (idnota != null) { try { idnotax = Integer.valueOf(idnota); } catch (NumberFormatException e) { error = "ID de Nota incorrecto"; } } Integer idalumnox = null; if (error == null) { try { idalumnox = Integer.valueOf(idalumno); } catch (NumberFormatException e) { error = "ID de Alumno incorrecto"; } } Integer notax = null; if (error == null) { try { notax = Integer.valueOf(nota); if ((notax < 0) || (notax > 20)) { error = "Nota de estar entre [0, 20]"; } } catch (NumberFormatException e) { error = "Nota de Alumno incorrecta"; } } if (error == null) { notas.setIdnota(idnotax); notas.setIdalumno(idalumnox); notas.setNota(notax); } return error; }
9
public static boolean index(char[] cs,char[] cl){ if(cs==null||cl==null){ return false; } if(cl.length!=cs.length){ return false; } boolean res= false; for(int i=0;i<cl.length;i++){ for(int j=0;j<cs.length;j++){ } } return res; }
5
public LigneMarqueur compare ( Ligne comparant){ LigneMarqueur liMarq = new LigneMarqueur(taille); // On déclare une liste de marqueurs correspondant à la ligne boolean[] existeTab = new boolean[taille]; // Ce tableau mettra true si la case correspondant à cet indice est présente. Ce tableau permet de ne pas compter plusieurs fois for(int i=0; i < taille; i++){ // Initialise le tableaux existeTab[i] = false; } liMarq.initialise(); for (int i=0; i < taille; i++){ // On test d'abord si les pions sont bien placés if ( ligne[i] == comparant.ligne[i] ){ liMarq.setMarq(i, 1);// Si la pièce est bien placée et de bonne couleur on met à 1 existeTab[i] = true; } } // On regarde les éléments existant et mal placés for(int i=0; i < taille; i++){ if(liMarq.getMarq(i) != 1){ // Si la pièce n'est pas déjà bien placée for(int j=0; j < taille && liMarq.getMarq(i) != 2; j++){ // Tant que le tableau n'est pas fini et qu'on a pas trouvé cette couleur dans le tableau if(comparant.ligne[i] == ligne[j] && existeTab[j] == false){ // Si une couleur est la même dans les 2 lignes et qu'elle n'a pas déjà été donné existeTab[j] = true; liMarq.setMarq(i, 2); // On dit que la pièce existe mais mal placée } } } } return liMarq; }
9
public CycAssertion readAssertion() throws IOException { CycList formula = null; Object formulaObject = null; CycAssertion cycAssertion = null; formulaObject = readObject(); if (formulaObject.toString().equals("NIL")) { // bypass invalid assertion mt readObject(); cycAssertion = CycObjectFactory.INVALID_ASSERTION; isInvalidObject = true; } else { try { formula = (CycList) formulaObject; CycObject mt = (CycObject) readObject(); cycAssertion = new CycAssertion(formula, mt); } catch (ClassCastException e) { System.err.println("formulaObject " + formulaObject.toString() + "(" + formulaObject.getClass().getName() + ")"); } } if (trace == API_TRACE_DETAILED) { debugNote("readAssertion: " + cycAssertion.toString()); } return cycAssertion; }
3
public static void main(String[] args) { w = new Worker(); }
0
public final void start(String[] args, boolean startProcess) { ArgumentList argumentList = new ArgumentList(args); // Ist der Parameter vorhanden if (argumentList.hasArgument("-gui") == false) { final String errorString = "Der Parameter -gui= wurde nicht angegeben"; JOptionPane.showMessageDialog(null, errorString, "Parameter -gui= fehlt", JOptionPane.ERROR_MESSAGE); // Es macht keinen Sinn weiterzumachen return; } // Wurde eine Klasse angegeben ? Falls ja, wird diese Ausgelesen if (argumentList.hasArgument("-prozessname") == false) { // Der Prozessname wurde nicht angegeben final String errorString = "Der Parameter -prozessname= wurde nicht angegeben"; JOptionPane.showMessageDialog(null, errorString, "Parameter -prozessname= fehlt", JOptionPane.ERROR_MESSAGE); // Es macht keinen Sinn weiterzumachen return; } _className = argumentList.fetchArgument("-prozessname=").asString(); // WorkingDirecotry auslesen File workingDirectory = null; if (argumentList.hasArgument("-arbeitsverzeichnis")) { // Es wurde ein Arbeitsverzeichnis angegeben workingDirectory = new File(argumentList.fetchArgument("-arbeitsverzeichnis").asString()); } // Soll die Oberfläche angezeigt werden (dies wird so gemacht da ein if (argumentList.fetchArgument("-gui=").booleanValue())) // zwar funktioniert hat, aber das Argument nicht aus der Liste entfernt wurde ! final boolean showGUI = argumentList.fetchArgument("-gui=").booleanValue(); // Es wurden alle Daten ausgelesen, die benötigt werden um einen Prozess zu starten. // Da beim rausfiltern der Argumente die ursprüngeliche Argumenteliste verändert wurde (es gibt // nun Einträge die <code>null</code> sind, wird diese Liste bereinigt. _modifiedArgumentlist = cleanedArgumentArray(args); if (showGUI) { // Die Oberfläche soll angezeigt werden if (startProcess) { // Den Prozess starten try { processScript(_modifiedArgumentlist, null, workingDirectory); } catch (IOException e) { e.printStackTrace(); } showGUI(); } else { // Es soll nur die GUI angezeigt werden, der Prozess wird nicht gestartet showGUI(); } } else { // Die Oberfläche soll nicht angezeigt werden if (startProcess) { // Der Prozess soll sofort gestartet werden try { processScript(_modifiedArgumentlist, null, workingDirectory); } catch (IOException e) { e.printStackTrace(); } } else { final String infoMessage = "Es soll keine Oberfläche angezeigt werden und der in den Parametern " + "festgelegte Prozess wird nicht gestartet. Es besteht keine Möglichkeit den Prozess nachträglich " + "zu starten ! Bitte starten Sie den Prozess direkt, falls sie keine GUI sehen möchten."; JOptionPane.showMessageDialog(null, infoMessage, "Prozess wird auf Wunsch des Benutzers nicht gestartet", JOptionPane.INFORMATION_MESSAGE); } } }
8
protected static boolean reportError(final Electronics me, final Software controlI, final MOB mob, final String literalMessage, final String controlMessage) { if((mob!=null) && (mob.location()==CMLib.map().roomLocation(me)) && (literalMessage!=null)) mob.tell(literalMessage); if(controlMessage!=null) { if(controlI!=null) controlI.addScreenMessage(controlMessage); else if((mob!=null)&&(me!=null)) mob.tell(CMLib.lang().L("A panel on @x1 reports '@x2'.",me.name(mob),controlMessage)); } return false; }
7
public static Rectangle2D parseNormalisedRectangle(PDFObject obj) throws IOException { if (obj != null) { if (obj.getType() == PDFObject.ARRAY) { PDFObject bounds[] = obj.getArray(); if (bounds.length == 4) { final double x0 = bounds[0].getDoubleValue(); final double y0 = bounds[1].getDoubleValue(); final double x1 = bounds[2].getDoubleValue(); final double y1 = bounds[3].getDoubleValue(); final double minX; final double maxY; final double maxX; final double minY; if (x0 < x1) { minX = x0; maxX = x1; } else { minX = x1; maxX = x0; } if (y0 < y1) { minY = y0; maxY = y1; } else { minY = y1; maxY = y0; } return new Rectangle2D.Double(minX, minY, Math.abs(maxX - minX), Math.abs(maxY - minY)); } else { throw new PDFParseException("Rectangle definition didn't have 4 elements"); } } else { throw new PDFParseException("Rectangle definition not an array"); } } else { throw new PDFParseException("Rectangle not present"); } }
5
private int ensurePositiveCoordinate(int i, int dimension) { int iPositive = i; if (iPositive == 0) { iPositive += dimension; } return iPositive; }
1
@Override public int awardPoints(boolean[] sv,int objectSize) { if(objectSize>sv.length){ for (boolean b : sv) { if(!b) return 0; //If any part is free of the object } return 1; } else{ //Tracker should catch it int c = 0; for (boolean b : sv) { if(b) c++; } return c == objectSize ? 1 : 0; } }
6
public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) { this.plugin = plugin; this.type = type; this.announce = announce; this.file = file; this.id = id; this.updateFolder = plugin.getServer().getUpdateFolder(); final File pluginFile = plugin.getDataFolder().getParentFile(); final File updaterFile = new File(pluginFile, "Updater"); final File updaterConfigFile = new File(updaterFile, "config.yml"); if (!updaterFile.exists()) { updaterFile.mkdir(); } if (!updaterConfigFile.exists()) { try { updaterConfigFile.createNewFile(); } catch (final IOException e) { plugin.getLogger().severe( "The updater could not create a configuration in " + updaterFile.getAbsolutePath()); e.printStackTrace(); } } this.config = YamlConfiguration.loadConfiguration(updaterConfigFile); this.config .options() .header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n' + "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n' + "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration."); this.config.addDefault("api-key", "PUT_API_KEY_HERE"); this.config.addDefault("disable", false); if (this.config.get("api-key", null) == null) { this.config.options().copyDefaults(true); try { this.config.save(updaterConfigFile); } catch (final IOException e) { plugin.getLogger().severe( "The updater could not save the configuration in " + updaterFile.getAbsolutePath()); e.printStackTrace(); } } if (this.config.getBoolean("disable")) { this.result = UpdateResult.DISABLED; return; } String key = this.config.getString("api-key"); if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) { key = null; } this.apiKey = key; try { this.url = new URL(Updater.HOST + Updater.QUERY + id); } catch (final MalformedURLException e) { plugin.getLogger().severe( "The project ID provided for updating, " + id + " is invalid."); this.result = UpdateResult.FAIL_BADID; e.printStackTrace(); } this.thread = new Thread(new UpdateRunnable()); this.thread.start(); }
9
@EventHandler public void onPlayerMove(PlayerMoveEvent event) { //HyperPVP.checkWorlds(); /*if (event.getPlayer().getWorld() == HyperPVP.getDefaultWorld()) { int max = 66; // 500 int least = -65; // -500 if (event.getTo().getX() > max || event.getTo().getX() < least) { moveBack("You can't fly any further.", event); } if (event.getTo().getZ() > max || event.getTo().getZ() < least) { moveBack("You can't fly any further.", event); } }*/ if (!HyperPVP.isCycling()) { for (Region region : HyperPVP.getMap().getRegions(RegionType.MAP)) { if (!region.hasLocation(event.getTo()) && event.getTo().getWorld() == HyperPVP.getMap().getWorld()) { moveBack(region.getAlert(), event); } } } /*if (HyperPVP.getGameSessions().containsKey(event.getPlayer().getName())) { Session session = HyperPVP.getSession(event.getPlayer()); for (Region region : HyperPVP.getMap().getRegions(RegionType.TEAM)) { if (!region.getTeamWhitelist().contains(session.getTeam().getColor())) { if (region.hasLocation(event.getTo())) { moveBack(region.getAlert(), event); } } else { if (region.hasLocation(event.getTo())) { event.getPlayer().setFireTicks(0); } } } }*/ }
4
private static void testSuite(){ /* TESTS x [5,7,4,3,6,9] x [1,7,5,6,9] x [3,7,5,2,6] x [1,7,5,4,6,9] x [1,2,3,4,5] x [5,4,3,2,1] x [2,3,1,7,9,5,8] x [2,3,1,7,5] x [1,9,7,10] x [4,1,3,2] x [7,1,6,3,2] x [7,9,6,10,5,8] */ int[] hand = new int[]{1,26,27,28,29,30,31,2}; Player[] players = new Player[]{ new PlayerConsole(), new PlayerConsole() }; Game g = Game.create(players, hand.length, 1, false); Rack r = players[0].rack; r.deal(hand); //Score metrics testing System.out.println("MaxCard = "+g.card_count); System.out.println("Points = "+r.scorePoints(false)); System.out.println("RackDE = "+r.scoreRackDE(g.dist_flat, null)); System.out.println("RackDE' = "+r.scoreRackDE(g.dist_flat, g.dist_skew)); ArrayList<Rack.LUS> lus = r.getLUS(false); for (Rack.LUS l: lus){ System.out.println(Arrays.toString(l.cards)); System.out.println("\tDensityCenter = "+r.scoreDensityCenter(l, null)); //* System.out.println("\tClumpDE = "+r.scoreClumpDE(l, g.dist_flat, null)); System.out.println("\tClumpDE' = "+r.scoreClumpDE(l, g.dist_flat, g.dist_skew)); System.out.println("\tDensity0 = "+r.scoreDensityAdjacent(l, null, 0)); System.out.println("\tDensity0' = "+r.scoreDensityAdjacent(l, g.dist_skew, 0)); System.out.println("\tDensity1 = "+r.scoreDensityAdjacent(l, null, 1)); System.out.println("\tDensity1' = "+r.scoreDensityAdjacent(l, g.dist_skew, 1)); //* System.out.println("\tProbReal = "+r.scoreProbability(l, null, false, true, 0)); System.out.println("\tProbReal' = "+r.scoreProbability(l, g.dist_skew, false, true, 0)); System.out.println("\tProbAvg = "+r.scoreProbability(l, null, true, true, 0)); System.out.println("\tProbAvg' = "+r.scoreProbability(l, g.dist_skew, true, true, 0)); //*/ } }
1
public int queryReservation(String bookingID) { // id[0] = resID, [1] = reservID, [2] = trans ID int[] id = parseBookingID(bookingID); if (id == null) { return GridSimTags.AR_STATUS_ERROR_INVALID_BOOKING_ID; } // search from the list first ARObject obj = searchBooking(id[0], id[1]); if (obj == null) { return GridSimTags.AR_STATUS_ERROR_INVALID_BOOKING_ID; } // if a reservation hasn't been committed else if (!obj.hasCommitted()) { return GridSimTags.AR_STATUS_NOT_COMMITTED; } // if the reservation status is one of the final states, then no need // to enquiry a resource int status = obj.getStatus(); // if a reservation has been committed, then need to ask a resource id[2] = incrementID(); // transaction id id[3] = super.get_id(); // send to grid resource to query about the reservation id super.send(super.output, 0.0, GridSimTags.SEND_AR_QUERY, new IO_data(id, SIZE_ARRAY, id[0]) ); // waiting for a response from the GridResource FilterResult tag = new FilterResult(id[2], GridSimTags.RETURN_AR_QUERY_STATUS); // only look for this type of ack for same reservation ID Sim_event ev = new Sim_event(); super.sim_get_next(tag, ev); // get the result back from GridResource or AllocPolicy object try { int[] array = (int[]) ev.get_data(); // [0] = trans ID, [1] = result status = array[1]; } catch (Exception e) { status = GridSimTags.AR_STATUS_ERROR; } obj.setStatus(status); // put the latest status return status; }
4
public void setBtn_Std_Fontcolor(int[] fontcolor) { if ((fontcolor == null) || (fontcolor.length != 4)) { this.buttonStdFontColor = UIFontInits.STDBUTTON.getColor(); } else { this.buttonStdFontColor = fontcolor; } somethingChanged(); }
2
public static ModuleSystemCollection parse(InputStream inputStream) throws SAXException, IOException, ParserConfigurationException{ Document doc = XmlUtil.loadDocument(inputStream); if(doc != null){ Element root = doc.getDocumentElement(); if(root != null && root.getNodeName().equalsIgnoreCase("ipower") && root.hasChildNodes()){ ModuleSystemCollection systems = new ModuleSystemCollection(); NodeList nodes = root.getChildNodes(); for(int i = 0; i < nodes.getLength();i++){ Node n = nodes.item(i); if(n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("system")){ ModuleSystem ms = parseToModuleSystem((Element)n); if(ms != null){ systems.add(ms); } } } return (systems.size() > 0 ? systems : null); } } return null; }
9
@Override public void onCommand(CommandSender sender, Command cmd, String label, String[] arguments) throws ConsoleOnlyException, InsufficientPermissionException, NotEnoughArgumentsException, PlayerOnlyException, TooManyArgumentsException { if(arguments[0].equalsIgnoreCase("reload")) { sender.sendMessage(ChunkyTransactions.getInstance().getMessage().formatMessageForChat("Reloading")); ChunkyTransactions.getInstance().setConfigration(new ConfigurationManager()); } else if(arguments[0].equalsIgnoreCase("help")) { if(arguments.length == 1) { sender.sendMessage(ChunkyTransactions.getInstance().getMessage().formatMessageForChat("Syntax: <Command Name> : <Command> : <Help>")); sender.sendMessage(ChunkyTransactions.getInstance().getMessage().formatMessageForChat("To get more info about a command do /" + this.getCommand() + " help <command you wnat to know more about>")); for(BaseCommand command : ChunkyTransactions.getInstance().getCommandManager().getCommands()) { sender.sendMessage(ChunkyTransactions.getInstance().getMessage().formatMessageForChat(command.getName() + " : " + command.getCommand() + " : " + command.getHelp())); } } if(arguments.length == 2) { sender.sendMessage(ChunkyTransactions.getInstance().getMessage().formatMessageForChat("Looking up command: " + arguments[1])); try { BaseCommand requestedCommand = ChunkyTransactions.getInstance().getCommandManager().getCommand(arguments[1], sender.getName()); sender.sendMessage(ChunkyTransactions.getInstance().getMessage().formatMessageForChat("Name: " + requestedCommand.getName())); sender.sendMessage(ChunkyTransactions.getInstance().getMessage().formatMessageForChat("Command: " + requestedCommand.getCommand())); sender.sendMessage(ChunkyTransactions.getInstance().getMessage().formatMessageForChat("Help: " + requestedCommand.getHelp())); sender.sendMessage(ChunkyTransactions.getInstance().getMessage().formatMessageForChat("Usage: " + requestedCommand.getUsage())); sender.sendMessage(ChunkyTransactions.getInstance().getMessage().formatMessageForChat("Permission: " + requestedCommand.getPermission())); } catch (UnknownCommandException e) { sender.sendMessage(ChunkyTransactions.getInstance().getMessage().formatErrorForChat("I'm sorry but the requested command: " + arguments[1] + " does not exist!")); if(ChunkyTransactions.getInstance().getConfiguration().isDebug()) { ChunkyTransactions.getInstance().getMessage().spitError(e); } } } } }
7
public String getCurrentPuzzle() { String currentPuzzle = ""; for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) { if(entries[i][j].isEditable()) { currentPuzzle = currentPuzzle + "E "; } else { currentPuzzle = currentPuzzle + "N "; } if(entries[i][j].getText().equals("")) { currentPuzzle = currentPuzzle + "0 "; } else { currentPuzzle = currentPuzzle + entries[i][j].getText() + " "; } } } System.out.println("Current Puzzle is" + currentPuzzle); return currentPuzzle; }
4
public static boolean setTime (int i_timeTick) { if (i_timeTick == m_start[m_curTime]) return false; if ((m_curTime == -1) || (i_timeTick > m_start[m_curTime])) { while ((m_curTime + 1 < m_nbMoves) && (i_timeTick >= m_start[m_curTime + 1])) { m_curTime++; m_label[m_curTime].move(m_angle[m_curTime]); } } else { while ((m_curTime >= 0) && (i_timeTick < m_start[m_curTime])) { if (m_prev[m_curTime] != 0) m_label[m_prev[m_curTime]].move(m_angle[m_prev[m_curTime]]); m_curTime--; } } return true; }
8
@Override public void keyReleased(KeyEvent e) { if (!view.getNameTextField().getText().equals("")){ boolean unique=true; String visibility = (String) view.getVisibilityComboBox().getSelectedItem(); Visibility visi; if (visibility.equals("private")) visi= Visibility.PRIVATE; else if (visibility.equals("protected")) visi =Visibility.PROTECTED; else if (visibility.equals("default")) visi = Visibility.DEFAULT; else visi = Visibility.PUBLIC; Method newMethod = new Method(view.getNameTextField().getText(), (String) view.getReturnTypeComboBox().getSelectedItem(), visi, view.parameterValid()); for (int i=0; i<view.getModel().getObjectUmlAtIndex(view.getIndex()).methodeListSize(); i++){ if (view.getModel().getObjectUmlAtIndex(view.getIndex()).getMehodAt(i).equals(newMethod)){ unique=false; } } if (unique){ model.setWarning(""); view.getOkButton().setEnabled(true); } else { model.setWarning("This method already exist"); view.getOkButton().setEnabled(false); } if(view.getNameTextField().getText().charAt(0)>='A'&&view.getNameTextField().getText().charAt(0)<='Z'){ model.setWarning("Method Name begin with a lower case"); } } else { model.setWarning("Method name is empty"); view.getOkButton().setEnabled(false); } }
9
private void bash(String cmd, File cwd) { if (System.getProperty("os.name").startsWith("Windows")) { println("only works with Unix-shell!"); return; } try { println("Path: " + cwd.getAbsolutePath()); println(cmd); ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd); if (cwd != null) { pb.directory(cwd); } pb.redirectErrorStream(true); Process pr = pb.start(); BufferedReader input = new BufferedReader(new InputStreamReader( pr.getInputStream())); String line = null; while ((line = input.readLine()) != null) { println(line); } int exitVal = pr.waitFor(); if (exitVal != 0) { throw new Error("Failure while executing bash command '" + cmd + "'. Return code = " + exitVal); } } catch (Exception e) { throw new Error("Could not execute bash command '" + cmd + "'.", e); } }
5
private void addNode4everyone(Node n) { if (n.getType() == NodeType.INPUT) { if (!inNodes.contains(n)) { inNodes.add(n); } } else if (n.getType() == NodeType.HIDDEN) { if (!hiddenNodes.contains(n)) { hiddenNodes.add(n); } } else if (n.getType() == NodeType.OUTPUT) { if (!outNodes.contains(n)) { outNodes.add(n); } } }
6
private void paramCompare(Method aMethod, ExprList exprList) { // Se o metodo nao tiver parametros E nao houver parametros a serem passados // simplesmente retorno if (aMethod.getParamList().getSize() == 0 && exprList == null) { return; } // SEM - comparando o NUMERO de parametros passados vs. parametros // que o metodo espera if ((aMethod.getParamList().getSize() == 0 && exprList == null) || (aMethod.getParamList().getSize() != exprList.getSize())) { error.show("Param count mismatch"); } // SEM - comparando o TIPO dos parametros for (int i = 0; i < exprList.getSize(); i++) { Variable expParam = aMethod.getParamList().get(i); Expr pasParam = exprList.getElement(i); // verifico se os parametros sao do mesmo tipo ou se tem a mesma heranca if ((pasParam.getType() instanceof ClassDec) && !((ClassDec) pasParam.getType()).isChildOf(expParam.getType().getName())) { error.show("Param type mismatch: '" + expParam.getType().getName() + "' expected. '" + pasParam.getType().getName() + "' given."); } } }
8
private static <T extends Comparable<? super T>> int partition(ArrayList<T> list, int start, int end){ int pivPos = bestPivotStrategy(list,start,end); T pivot = list.get(pivPos); normalSwap(list, start, pivPos); int left = start+1; int right = end; while(true){ while(left <= right) if(list.get(left).compareTo(pivot) < 0){ left++; } else{ break; } while(right > left){ if(list.get(right).compareTo(pivot) > 0) right--; else break; } if(left >= right) break; normalSwap(list, left, right); } list.set(start, list.get(left-1)); list.set(left-1, pivot); return left-1; }
7
public Participant(String id, String name, InetAddress addr, String textColor) { this.id = id; this.name = name; this.addr = addr; this.textColor = textColor; lastSignal = System.currentTimeMillis(); }
0
@SuppressWarnings("unchecked") // guarded by typeToken.equals() call public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { boolean matches = exactType != null ? exactType.equals(type) || matchRawType && exactType.getType() == type.getRawType() : hierarchyType.isAssignableFrom(type.getRawType()); return matches ? new TreeTypeAdapter<T>((JsonSerializer<T>) serializer, (JsonDeserializer<T>) deserializer, gson, type, this) : null; }
4
private void userHelp (ArrayList < String > command) { String topic; if (command.size () > 1) { topic = command.get (1); } else { topic = ""; } System.out.println (""); if (topic.equals ("")) { System.out. print ("alarm on|off..............turns audible alarm on/off\n"); System.out. print ("analyze...................analyze a game in progress\n"); System.out. print ("annotate..................annotate game [help].\n"); System.out.print ("back n....................undo n moves\n"); System.out. print ("bench.....................runs performance benchmark.\n"); System.out.print ("black.....................sets black to move.\n"); System.out.print ("display...................displays the board\n"); System.out. print ("display <n>...............sets display options [help]\n"); System.out. print ("edit......................edit board position. [help]\n"); System.out.print ("end.......................terminates program.\n"); System.out. print ("exit......................restores STDIN to keyboard.\n"); System.out. print ("go........................initiates search (same as move).\n"); System.out.print ("help [command]............displays help.\n"); System.out.print ("history...................display game moves.\n"); System.out. print ("info......................displays program settings.\n"); System.out. print ("input <filename>..........sets STDIN to <filename>.\n"); System.out.print ("log on|off................turn logging on/off.\n"); System.out.print ("more...\n"); NeutronUtil.getInput (); System.out. print ("move......................initiates search (same as go).\n"); System.out. print ("name......................sets opponent's name.\n"); System.out. print ("new.......................initialize and start new game.\n"); System.out. print ("noise n...................no status until n nodes searched.\n"); System.out. print ("perf.[long]...............times the move generator/make_move.\n"); System.out. print ("perft.....................tests the move generator/make_move.\n"); System.out. print ("ponder on|off.............toggle pondering off/on.\n"); System.out. print ("read <filename>...........read moves in [from <filename>].\n"); System.out. print ("reada <filename>..........read moves in [from <filename>].\n"); System.out. print (" (appends to current game history.)\n"); System.out. print ("reset n...................reset game to move n.\n"); System.out.print ("save <filename>.......saves game.\n"); System.out. print ("score.....................print evaluation of position.\n"); System.out. print ("sd n......................sets absolute search depth.\n"); System.out. print ("show book.................toggle book statistics.\n"); System.out. print ("st n......................sets absolute search time.\n"); System.out. print ("test <file> [N]...........test a suite of problems. [help]\n"); System.out. print ("time......................time controls. [help]\n"); System.out. print ("trace n...................display search tree below depth n.\n"); System.out.print ("white.....................sets white to move.\n"); System.out.println (); return; } if (topic.equals ("analyze")) { System.out.print ("analyze:\n"); System.out. print ("the analyze command puts GnuTrax into a mode where it will\n"); System.out. print ("search forever in the current position. When a move is\n"); System.out. print ("entered, GnuTrax will make that move, switch sides, and\n"); System.out. print ("again compute, printing analysis as it searches. You can\n"); System.out. print ("back up a move by entering \"back\" or you can back up\n"); System.out. print ("several moves by entering \"back <n>\". Note that <n> is\n"); System.out. print ("the number of moves, counting each player's move as one.\n"); System.out.println (); return; } if (topic.equals ("annotate")) { System.out.print ("annotate:\n"); System.out. print ("annotate <filename> <b|w|bw> <moves> <margin> <time> [n]\n"); System.out. print ("where <filename> is the input file with game moves, while the\n"); System.out. print ("output will be written to filename.can. b/w/bw indicates\n"); System.out. print ("whether to annotate only the white side (w), the black side (b)\n"); System.out. print ("or both (bw). <moves> indicates which moves to annotate. A single\n"); System.out. print ("value says start at the indicated move and go through the\n"); System.out. print ("entire game. A range (20-30) annotates the given range only.\n"); System.out. print ("<margin> is the difference between the search value for the\n"); System.out. print ("move played in the game, and the best move GnuTrax found,\n"); System.out. print ("before a comment is generated. <time> is the time limit per\n"); System.out. print ("move in seconds. If the optional \"<n>\" is appended, this\n"); System.out. print ("produces <n> best moves/scores/PV's, rather than just\n"); System.out. print ("the very best move. It won't display any move that is worse\n"); System.out. print ("than the actual game move played, but you can use \"-<n>\" to\n"); System.out. print ("force GnuTrax to produce <n> PV's regardless of how bad they get.\n"); System.out.println (); return; } if (topic.equals ("display")) { System.out.print ("display:\n"); System.out. print ("display changes -> display variation when it changes.\n"); System.out. print ("display extstats -> display search extension statistics.\n"); System.out. print ("display hashstats -> display search hashing statistics.\n"); System.out. print ("display movenum -> display move numbers in PV.\n"); System.out. print ("display moves -> display moves as they are searched.\n"); System.out. print ("display stats -> display basic search statistics.\n"); System.out.print ("display time -> display time for moves.\n"); System.out. print ("display variation -> display variation at end of iteration.\n"); System.out.println (); return; } if (topic.equals ("edit")) { System.out.println ("edit help: not ready yet."); return; } if (topic.equals ("test")) { System.out.println ("test help: not ready yet."); return; } if (topic.equals ("time")) { System.out.print ("time:\n"); System.out. print ("time is used to set the basic search timing controls. The general\n"); System.out.print ("form of the command is as follows:\n"); System.out.println (); System.out. print (" time nmoves/ntime/[nmoves/ntime]/[increment]\n"); System.out.println (); System.out. print ("nmoves/ntime represents a traditional first time control when\n"); System.out. print ("nmoves is an integer representing the number of moves and ntime\n"); System.out. print ("is the total time allowed for these moves. The [optional]\n"); System.out. print ("nmoves/ntime is a traditional secondary time control. Increment\n"); System.out. print ("is a feature which emulates the fischer clock where <increment>\n"); System.out. print ("is added to the time left after each move is made.\n"); System.out.println (); System.out. print ("as an alternative, nmoves can be \"sd\" which represents a sudden\n"); System.out. print ("death time control of the remainder of the game played in ntime.\n"); System.out. print ("The optional secondary time control can be a sudden-death time\n"); System.out.print ("control, as in the following example:\n"); System.out.println (); System.out.print (" time 60/30/sd/30\n"); System.out.println (); System.out. print ("this sets 60 moves in 30 minutes, then game in 30 additional\n"); System.out.print ("minutes. An increment can be added if desired.\n"); System.out.println (); return; } System.out.println ("No help found on topic:"); }
8
@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 Proveedores)) { return false; } Proveedores other = (Proveedores) object; if ((this.idproveedores == null && other.idproveedores != null) || (this.idproveedores != null && !this.idproveedores.equals(other.idproveedores))) { return false; } return true; }
5
public static boolean RectWithRect(float x1, float y1, float w1, float h1, float x2, float y2, float w2, float h2) { if (x1 > x2+w2 || x1+w1 < x2 || y1 > y2+h2 || y1+h1 < y2) return false; return true; }
4
public String trim() { int i = 0; boolean test = true; for(int j = 0; j < this.number.length(); j++) { if(this.number.charAt(j) != '0' && this.number.charAt(j) != '\0') { test = false; break; } } if(test) { return new String(new CharNode('0')); } for(; i < this.number.length() - 1; i++) { if(this.number.charAt(i) != '0') { return this.number.substring(i); } } return this.number; }
6
public static void main(String[] args) throws InterruptedException { if (args[0].equals("full") || args[0].equals("more")) { BookBuilder bb; if (args[0].equals("full")) { try { ComputationController.launchComputation(args[1], properties.getReduceOutput()); } catch (Exception e) { logger.fatal("Computation Exception"); e.printStackTrace(); System.exit(1); } } try { bb = new BookBuilder( ComputationController.listFilesForFolder(new File( properties.getReduceOutput()))); String para = bb.buildBook(); if (args[0].equals("full")) { FileWriterHelper.writeToFile(para, args[2]); } else if (args[0].equals("more")) { FileWriterHelper.writeToFile(para, args[1]); } } catch (Exception e) { logger.fatal("Processing Exception"); e.printStackTrace(); System.exit(1); } } else logger.fatal("Bad Parameters."); }
7
public static void fillKnapsack(double totalValue, double bagMaxWeight, double itemArray[][], double unitValue[], int itemNumber[], DecimalFormat df){ double[] originalWeight = {itemArray[1][0], itemArray[1][1], itemArray[1][2], itemArray[1][3]}; int limit = 0; for(int i=0; i<4; i++){ while((itemArray[1][i]) != 0){ if(limit<bagMaxWeight){ totalValue += unitValue[i]; itemArray[1][i]--; limit++; } else{ break;//Avoid infinite loop if there is no room left in bag } } } //Prints the percentage of items taken by knapsack and the optimal total value it can hold for(int y=0; y<4; y++) System.out.println("Knapsack took %"+df.format(100*((1-itemArray[1][y]/originalWeight[y])))+" of item " + itemNumber[y]); System.out.println("\nTotal value knapsack can hold: $" + df.format(totalValue)); }
4
public int getScore(Owner owner){ if (owner==Owner.Neutral) return -1; int Score = 0; City tempCity; Iterator<City> CityIterator = iterator(); while(CityIterator.hasNext()){ tempCity = CityIterator.next(); if (tempCity.getOwner() == owner) Score++; else if (tempCity.getOwner() == Owner.Neutral) { if(isCutOffBy(tempCity, owner)) Score++; } } return Score; }
5
protected void paintCenteredText(Graphics2D g2, String s, Rectangle rect, double fontHeight, Color color) { g2 = (Graphics2D) g2.create(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setPaint(color); Rectangle2D bounds = null; LineMetrics lm = null; boolean done = false; // shrink font in increments of sqrt(2)/2 until string fits while (!done) { g2.setFont(new Font("SansSerif", Font.BOLD, (int) (fontHeight * rect.height))); FontRenderContext frc = g2.getFontRenderContext(); bounds = g2.getFont().getStringBounds(s, frc); if (bounds.getWidth() > rect.getWidth()) fontHeight = fontHeight * Math.sqrt(2) / 2; else { done = true; lm = g2.getFont().getLineMetrics(s, frc); } } float centerX = rect.x + rect.width / 2; float centerY = rect.y + rect.height / 2; float leftX = centerX - (float) bounds.getWidth() / 2; float baselineY = centerY - lm.getHeight() / 2 + lm.getAscent(); g2.drawString(s, leftX, baselineY); g2.dispose(); }
2
public boolean containsOffset(int offset){ int b = start.getOffset(); int e = end.getOffset(); if ( b<e && offset >= b && offset < e ) return true; return false; }
3
public boolean remove(DataRow row) { if(!checkUser()) { return false; } boolean result; row = addIdentifyingParameters(row); DataRow removed = new DataRow(row.getTableName() + row.getName()); removed.setTableName("removedData"); removed.addAttribute("tableName", row.tableName); removed.addAttribute("objectName", row.getAttribute("name").getValue()); removed = addIdentifyingParameters(removed); try { result = local.remove(row); local.insert(removed); if(server.checkConnection()) { result = result && server.remove(row); server.insert(removed); } } catch(Exception e) { ErrorDialog errorDialog = new ErrorDialog(true, "Błąd operacji w bazie danych: \n" + e.getMessage(), "DatabaseManager", "remove(DataRow row)", "row"); errorDialog.setVisible(true); result = false; } return result; }
4
public static boolean isValidResult(Option[] options){ return isSuccessResult(options) || isFailureResult(options) || (isStoppedResult(options)); }
2
public static void longestName(Scanner scanner, int number) { String[] strings = new String[number]; int maxLength = 0; for (int i = 0; i < number; i++) { System.out.print("Name #" + (i + 1) + ": "); strings[i] = scanner.nextLine(); if (maxLength < strings[i].length()) { maxLength = strings[i].length(); } System.out.println(); } int arraySize = 0; for (int i = 0; i < strings.length; i++) { if (strings[i].length() >= maxLength) { arraySize++; } } int[] stringLoc = new int[arraySize]; int temp = 0; for (int i = 0; i < strings.length; i++) { if (strings[i].length() >= maxLength) { stringLoc[temp] = i; temp++; } } String longest = strings[stringLoc[0]].substring(0, 1).toUpperCase() + strings[stringLoc[0]].substring(1).toLowerCase(); System.out.println("The longest name is: " + longest); if (stringLoc.length > 1) { System.out.println("With a tie."); } }
7
public Object getValueAt(int row, int column) { switch(column) { case 0 : return rowHeadings[row]; case 1 : switch (row) { case 0 : return statement.getSourceFile().getName(); case 1 : return statement.getLineNo(); case 2 : return statement.getClass().getSimpleName(); case 3 : return statement.toString(); case 4 : return statement.getSourceCode(); default : return null; } default : return null; } }
7
private void drawFans(Graphics2D g) { List<Fan> fans = model.getFans(); if (fans.isEmpty()) return; Stroke oldStroke = g.getStroke(); Color oldColor = g.getColor(); Symbol.FanIcon fanIcon = new Symbol.FanIcon(Color.GRAY, Color.BLACK, false); synchronized (fans) { for (Fan f : fans) { if (f.isVisible()) { Rectangle2D r = f.getShape().getBounds2D(); int x = convertPointToPixelX((float) r.getX()); int y = convertPointToPixelY((float) r.getY()); int w = convertLengthToPixelX((float) r.getWidth()); int h = convertLengthToPixelY((float) r.getHeight()); fanIcon.setIconWidth(w); fanIcon.setIconHeight(h); fanIcon.setAngle(f.getAngle()); fanIcon.setSpeed(f.getSpeed()); fanIcon.setRotation(fanRotationSpeedScaleFactor * f.getSpeed() * model.getTime()); fanIcon.setStroke(moderateStroke); fanIcon.setBorderColor(f == selectedManipulable ? Color.YELLOW : Color.BLACK); fanIcon.paintIcon(this, g, x, y); Shape s = f.getShape(); if (s instanceof Rectangle2D.Float) { Rectangle2D.Float r2 = (Rectangle2D.Float) s; x = convertPointToPixelX(r2.x); y = convertPointToPixelY(r2.y); w = convertLengthToPixelX(r2.width); h = convertLengthToPixelY(r2.height); String label = f.getLabel(); if (label != null) drawLabelWithLineBreaks(g, label, x + 0.5f * w, y + 0.5f * h, w < h * 0.25f); if (selectedManipulable == f) { g.setStroke(longDashed); g.drawRect(x, y, w, h); } } } } } g.setStroke(oldStroke); g.setColor(oldColor); }
7
public static int[] selectionSort(int[] array) { if(array == null || array.length <= 1) { return array; } for(int i = 0; i < array.length; i++) { int min = array[i]; int index = i; for(int j = i; j < array.length; j++) { if(array[j] < min) { min = array[j]; index = j; } } int temp = array[i]; array[i] = array[index]; array[index] = temp; } return array; }
5
public synchronized void addLobby(GameSettings gs, ClientThread ct) { Packet answer = null; if(gs == null || ct == null) { answer = Packet.getServerErrorPacket(); } else { lastID++; Lobby l = new Lobby(lastID, gs, this); lobbies.put(lastID, l); l.addPlayer(ct); ct.gameID = new Integer(lastID); answer = new Packet(Packet.PACKET_CODES.GAME_CREATED_CODE); answer.setData(ct.gameID); } try { ct.sendToClient(answer); } catch(Exception e) {} }
3
public static String StrFill(String fillStr ,String oldStr ,int length ,String place) { StringBuffer sb = new StringBuffer(); if("right".equals(place)){ sb.append(oldStr); } for(int i=0; i < (length - oldStr.length());i++){ sb.append(fillStr); } if("left".equals(place)){ sb.append(oldStr); } return sb.toString(); }
3
public static <T extends Comparable<T>> BasicNode<T> getParentNodeOrNull( BasicNode<T> root, T valueToSearch) { if (null == root || null == valueToSearch) { throw new IllegalArgumentException("Root or value to be inserted can not be null."); } if (root.getValue().equals(valueToSearch)) { return null; } Queue<BasicNode<T>> nodes = new LinkedList<BasicNode<T>>(); nodes.add(root); //TODO(anupam): Implement using InOrder traversal as the nodes in next level are added to the // queue even if the current level has the node to be searched. while (!nodes.isEmpty()) { BasicNode<T> node = nodes.poll(); if (node.hasLeft()) { if (node.getLeft().getValue().equals(valueToSearch)) { return node; } nodes.add(node.getLeft()); } if (node.hasRight()) { if (node.getRight().getValue().equals(valueToSearch)) { return node; } nodes.add(node.getRight()); } } return null; }
8
@Override public void focusGained(FocusEvent e) { if(e.getSource()==joinIP && getJoinIP().equals("localhost")) { joinIP.setText(""); } else if (e.getSource()==hostPort && getJoinPort() == 1234) { hostPort.setText(""); } else if (e.getSource()==joinPort && getJoinPort() == 1234) { joinPort.setText(""); } else if (e.getSource()==name && getUsername().equals("Anonymous")) { name.setText(""); } }
8
private static String bindParamIntoQuery(String query, Object parameter) { try { String paramAsJson = convertParameter(parameter); return query.replaceFirst(TOKEN, getMatcherWithEscapedDollar(paramAsJson)); } catch (RuntimeException e) { return handleInvalidBinding(query, parameter, e); } }
1
public static boolean GetKeyDown(int keyCode) { return GetKey(keyCode) && !m_lastKeys[keyCode]; }
1
public static void main(String[] args) throws IOException { int count_success = 0; int count_failure = 0; String bucket = getBucket(); Collection<MyTask> collection = new ArrayList<MyTask>(); for (int i = 0; i < NUM_TASKS; i++) { String uniqueKey = "file-" + UUID.randomUUID(); MyTask myTask = new MyTask(bucket, uniqueKey); collection.add(myTask); } long startTime = System.currentTimeMillis(); try { List<Future<Boolean>> list = executorPool.invokeAll(collection); for (Future<Boolean> fut : list) { if(fut.get()) { count_success++; } else { count_failure++; } } } catch (Exception e) { e.printStackTrace(); } finally { long elapsedTime = (System.currentTimeMillis() - startTime); System.out.println("TOTAL SUCCESS - " + count_success); System.out.println("TOTAL FAILURE - " + count_failure); System.out.println("Total time - " + elapsedTime + " ms"); executorPool.shutdown(); } }
4
static public String generalizeWildcard(String s) { if (s==null) return "*"; int ix=s.length()-1; if(ix<=1) return "*"; while(ix>0 && s.charAt(ix)=='*') ix--; // skip any * fields starting from the end return s.substring(0, ix)+"*"; }
4
@Override public boolean handleLogLevelCommand(String providedCommandLine, PrintStream outputStream, IServerStatusInterface targetServerInterface) { boolean retVal = false; String[] commParts = GenericUtilities.splitBySpace(providedCommandLine); if(commParts != null && commParts.length == 2) { String toSetLev = commParts[1]; if(toSetLev.equals("v") || toSetLev.equals("verbose")) { targetServerInterface.setVerboseLogLevel(); retVal = true; } else if(toSetLev.equals("n") || toSetLev.equals("normal")) { targetServerInterface.setNormalLogLevel(); retVal = true; } } return retVal; }
6
@Override public boolean isActive(){ if (context == 0) { context = -1; try { if (getAppletContext() != null) context = 1; }catch(Exception e){/**/} } if (context == -1) return active; return super.isActive(); }
4
public int changeAce(){ if ((cardValue==11)&&(rank.equalsIgnoreCase("Ace"))) cardValue=1; return cardValue; }
2
public Klus zoekKlus(int id){ Klus antw = null; for(Klus k: alleKlussen){ if(k.getKlusNummer()==id){ antw = k; break; } } return antw; }
2
public void clearGrid() { for (int x = 0; x < 4; x++) { for (int y = 0; y < 4; y++) { grid[x][y] = 0; } } }
2
@Override public void newbie() { log.debug("newbie"); }
0
private int[] getResList() { Object[] resList = super.getLocalResourceList(); int resourceID[] = null; // if we have any resource if ((resList != null) && (resList.length != 0)) { resourceID = new int[resList.length]; for (int x = 0; x < resList.length; x++) { // Resource list contains list of resource IDs resourceID[x] = ((Integer) resList[x]).intValue(); if (trace_flag == true) { System.out.println(super.get_name() + ": resource[" + x + "] = " + resourceID[x]); } } } return resourceID; }
4
public String multiply(String num1, String num2) { if(num1.equals("0") || num2.equals("0") )return "0"; int R = 200; int[] mul = new int[R]; int k = R-1, min = Integer.MAX_VALUE; //multi for(int i = num2.length()-1; i >= 0; i--){ int a = num2.charAt(i) - '0'; int s = 0; int t = k; for(int j = num1.length()-1; j >= 0; j--){ int b = num1.charAt(j) - '0'; int tmp = (mul[t] + s + a*b)%10; s = (mul[t] + s + a*b) / 10; mul[t--] = tmp; } if(s!=0) mul[t--] = s; if(t+1 < min) min = t+1; // System.out.println(Arrays.toString(mul)); k--; } //reverse // System.out.println(min); StringBuilder sb = new StringBuilder(); for(int i = min; i<=R-1; i++) { sb.append(mul[i]); } return sb.toString(); }
7
public The5zigModUser(String player) { this.player = player; }
0
public static int pointInArray(Point p, ArrayList<PathNode> array) { for (int c = 0; c < array.size(); c++) { if (p.equals(array.get(c).getLocation())) { return c; } } return -1; }
2
public float getProcessStatus() { if (isComplete) return 100f; if (process == 0) return 0; return process / (build_time * 1.0f); }
2
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Point3 other = (Point3) obj; if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x)) return false; if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y)) return false; if (Float.floatToIntBits(z) != Float.floatToIntBits(other.z)) return false; return true; }
6
public IntervalManager(List<Interval> inters) { intervals = new ArrayList<Interval>(); intervals.addAll(inters); endPoints = new ArrayList<Endpoint>(); for (int i = 0; i < intervals.size(); ++i) { Endpoint endPoint = new Endpoint(); endPoint.type = Endpoint.Type.BEGIN; endPoint.value = intervals.get(i).end[0].value; endPoint.index = i; endPoints.add(2*i, endPoint); endPoint = new Endpoint(); endPoint.type = Endpoint.Type.END; endPoint.value = intervals.get(i).end[1].value; endPoint.index = i; endPoints.add(2*i + 1, endPoint); } /* for (int i = 0; i < endPoints.size(); i++) { System.out.print(endPoints.get(i).toString() + ","); System.out.println(); } */ Collections.sort(endPoints); /* for (int i = 0; i < endPoints.size(); i++) { System.out.print(endPoints.get(i).toString() + ","); System.out.println(); } */ lookUp = new ArrayList<Integer>(); for (int j = 0; j < endPoints.size(); j++) { lookUp.add(null); } for (int j = 0; j < endPoints.size(); ++j) { lookUp.set(2*endPoints.get(j).index + endPoints.get(j).type.ordinal(), new Integer(j)); } /* for (int i = 0; i < endPoints.size(); i++) { System.out.print(lookUp.get(i).toString() + ","); System.out.println(); } */ Set<Integer> active = new LinkedHashSet<Integer>(); overLaps = new LinkedHashSet<Pair>(); for (int i = 0; i < endPoints.size(); ++i) { Endpoint endpoint = new Endpoint(endPoints.get(i)); Integer index = new Integer(endpoint.index); if (endpoint.type.ordinal() == Endpoint.Type.BEGIN.ordinal()) { Iterator<Integer> iterator = active.iterator(); while (iterator.hasNext()) { Integer activeIndex = iterator.next(); if (activeIndex < index) { overLaps.add(new Pair(activeIndex, index)); } else { overLaps.add(new Pair(index, activeIndex)); } } active.add(new Integer(index)); } else { active.remove(new Integer(index)); } } }
7
@Override public boolean canSeek() { return this.mAudioInputStream.markSupported() && this.mFrameSize != AudioSystem.NOT_SPECIFIED && this.mFrameLength != AudioSystem.NOT_SPECIFIED && !this.mClosed; }
3
@Override public void run() { Player player1 = new Player(2000, 0); Player dealer = new Player(0, 1); int exit = 0; int totalPlayer = 0; int totalDealer = 0; int moneyBefore = 0; ArrayList<Card> initialPlayerHand; ArrayList<Card> initialDealerHand; Scanner sc = new Scanner(System.in); for (int k = 0; k < iterations; k++) { try { Thread.sleep(retraso); } catch (InterruptedException ex) { Logger.getLogger(ProjectFrame.class.getName()).log(Level.SEVERE, null, ex); } exit = 0; while (exit == 0) { moneyAll = player1.getMoney(); try { bj = 0; for (int i = 0; i < 2; i++) { player1.getHand().add(deck.getCard()); dealer.getHand().add(deck.getCard()); } System.out.println("Initial Table: "); printHand(player1, dealer, 0); initialPlayerHand = player1.getHand(); initialDealerHand = player1.getHand(); System.out.println("Initial Table uncovered (Still covered for player)"); printHand(player1, dealer, 1); totalPlayer = play(player1, dealer, this.strategy); makeBet(player1, amount); if (totalPlayer > 21) { totalDealer = Card.sumaCartas(dealer.getHand()); } else { totalDealer = play(dealer, player1, 0); } System.out.println("Final Table: "); printHand(player1, dealer, 1); moneyBefore = player1.getMoney(); printResult(totalPlayer, totalDealer, player1); System.out.println("Blackjack = " + bj); System.out.println("Player´s Money Before: " + moneyBefore); System.out.println("Winnings: " + (player1.getMoney() - moneyBefore)); System.out.println("Player´s Money: " + player1.getMoney()); System.out.println("Deck Size: " + deck.getCards().size()); System.out.println("DeckYard Size: " + deck.getDeckYard().size()); System.out.println("________________________________________________________"); System.out.println(); handValues.add(totalPlayer); player1.getHand().clear(); dealer.getHand().clear(); totalGames++; } catch (java.lang.IndexOutOfBoundsException e) { bet = 0; deck.shuffDeck(); player1.getHand().clear(); dealer.getHand().clear(); this.log.append("Iteraccion Numero: ").append(k + 1).append("\n"); this.log.append("Dinero del jugador: ").append(moneyAll).append("\n"); this.log.append("Player Wins: ").append(playerWins).append("\n"); this.log.append("Dealer Wins: ").append(dealerWins).append("\n"); this.log.append("Draws: ").append(draws).append("\n"); this.log.append("Juegos Hasta el Momento: ").append(totalGames).append("\n"); this.log.append("Porcentaje Volado: ").append(((double) blowUpTimes / (double) totalGames) * 100).append("\n"); this.log.append("Porcentaje Wins: ").append(((double) playerWins / (double) totalGames) * 100).append("\n"); if (handValues.size() > 0) { this.log.append("Mano promedio: ").append(arrayAverage(handValues)).append("\n\n\n"); } double percentaje = ((double) (k + 1) / (double) iterations) * 100; pj.setLogSimulation3(log.toString()); pj.setProgressBar3((int) percentaje); insertPieChart(0); insertPieChart(1); insertBarChart(); insertLineChart(k + 1); exit = 1; } } } if (bet != 0) { moneyAll += bet; } System.out.println("Resultados Finales: "); System.out.println("Dinero: " + moneyAll); System.out.println("Veces Volado: " + blowUpTimes); System.out.println("Player Wins: " + playerWins); System.out.println("Dealer Wins: " + dealerWins); System.out.println("Draws: " + draws); System.out.println("Juegos Totales: " + totalGames); if (handValues.size() > 0) { System.out.println("Mano promedio: " + arrayAverage(handValues)); } System.out.println("Porcentaje volado: " + ((double) blowUpTimes / (double) totalGames) * 100); System.out.println("Porcentaje Wins: " + ((double) playerWins / (double) totalGames) * 100); }
9
@Override public void updateBiblio(Bibliothecaire bibliothecaire) throws Exception { if (bibliothecaire == null) { throw new NullPointerException("Bibliothecaire null !"); } if (bibliothecaire.getNom().equals("")) { throw new Exception("Veuillez renseigner le nom du bibliothécaire !"); } if (bibliothecaire.getPrenom().equals("")) { throw new Exception("Veuillez renseigner le prénom du bibliothécaire!"); } if((bibliothecaire.getId() != MetierServiceFactory.getBibliotheque().getBibliothecaireConnecte().getId()) && (!MetierServiceFactory.getBibliotheque().isSuperAdminConnected())) { throw new Exception("Vous n'êtes pas autorisé à modifier ce bibliothécaire !"); } Bibliothecaire byLogin = this.getByLogin(bibliothecaire.getLogin()); if(byLogin != null) { if(bibliothecaire.getId() != byLogin.getId()) { throw new Exception("Ce login est déjà pris !"); } } Bibliothecaire byId = this.getBiblioById(bibliothecaire.getId()); if (byId == null) { throw new Exception("Ce bibliothécaire n'existe pas !"); } adherentPhysiqueService.updateBiblio(bibliothecaire); }
8
@EventHandler public void onProxyPing(ProxyPingEvent e) { PendingConnection c = e.getConnection(); ListenerInfo l = c.getListener(); if (config != null) { Profile profile = config.findProfile(this, c, l); if (profile != null) { ServerPing response = e.getResponse(); Favicon icon = profile.getFavicon(this); Protocol protocol = profile.getProtocol(this, c); String user = userData.getPlayer(c.getAddress().getAddress().getHostAddress()); String motd = null; if (user != null) { motd = profile.getDynamicMotd(user); } if (motd == null) { motd = profile.getStaticMotd(); } Players players = profile.getPlayers(this); if (icon != null) { response.setFavicon(icon); } if (protocol != null) { response.setVersion(protocol); } if (motd != null) { response.setDescription(motd); } if (players != null) { response.setPlayers(players); } } } }
8
@Override protected List<ResourceFile> prepareResourceFiles(List<ResourceFile> list) { if (isInPreEnv) { // 预发布脚本 List<ResourceFile> preFiles = new ArrayList<ResourceFile>(); // 其他脚本 List<ResourceFile> otherFiles = new ArrayList<ResourceFile>(); // 分类 for (ResourceFile file : list) { if (PRE_ENV_EXTENSION.equals(file.getExtension())) { preFiles.add(file); } else { otherFiles.add(file); } } // 把预发布脚本合并到正式脚本 for (ResourceFile preFile : preFiles) { boolean existed = false; for (ResourceFile file : otherFiles) { // 存在这个文件,就用预发布文件的内容替换到正式文件 if (preFile.getName().equals(file.getName() + "." + file.getExtension())) { file.setContent(preFile.getContent()); existed = true; continue; } } // 如果不存在就新加这个文件 if (!existed) { String name = preFile.getName(); preFile.setName(StringUtils.substringBeforeLast(name, ".")); preFile.setExtension(StringUtils.substringAfterLast(name, ".")); otherFiles.add(preFile); } } return otherFiles; } else { return list; } }
7
public YamlPermissionConsole(ConfigurationSection config) { super("console", config); }
0
public int uncompress(InputStream in, OutputStream out) throws IOException { try { BitInputStream bis = new BitInputStream(in); //compressed file BitOutputStream bos = new BitOutputStream(out); int bitMagic = bis.readBits(IHuffConstants.BITS_PER_INT); if(bitMagic == IHuffConstants.MAGIC_NUMBER) { int bitHeader = bis.readBits(IHuffConstants.BITS_PER_INT); //IF STANDARD COUNT FORMAT if(bitHeader == IHuffConstants.STORE_COUNTS) { PriorityQueue<TreeNode> q = new PriorityQueue<TreeNode>(in, bis, false); ArrayList<TreeNode> arr = q.arr(); //get array of frequencies for(TreeNode tn: arr){ //add freq's from array to priority queue q.add(tn); } HuffTree temp = new HuffTree(); huffTree = temp.createHuffTree(q); //huffman tree m = temp.travelTree(huffTree); //creates map bis = q.getBitInputStream(); Uncompress u = new Uncompress(huffTree); u.uncompressSCF(bis, bos); showString("DECOMPRESSING: Codes for values in file: \n"); for(int i : m.keySet()) { if(i != 256) showString(i + "\t" + m.get(i) + "\t\t" + (char) i); } showString("Bits Written: " + u.getBitsWritten()); return u.getBitsWritten(); } //IF STANDARD TREE FORMAT if(bitHeader == IHuffConstants.STORE_TREE) { Uncompress u = new Uncompress(huffTree); u.uncompressSTF(bis, bos); showString("DECOMPRESSING: Codes for values in file: \n"); HashMap<Integer, String> STFmap = u.getMap(); for(int i : STFmap.keySet()) { if(i != 256) showString(i + "\t" + STFmap.get(i) + "\t\t" + (char) i); } showString("Bits Written: " + u.getBitsWritten()); return u.getBitsWritten(); } bis.close(); } //end of if magic num } //end of try catch(Exception e) { e.printStackTrace(); //debugging, print stack trace throw new IOException("uncompress not implemented"); } return 0; }
9
public static void sort(int[] randomSet) { int i = 0; int m = 0; while(i < randomSet.length) { int j = i + 1; m = randomSet[i]; while(j < randomSet.length) { if(randomSet[j] < randomSet[i]) { m = randomSet[i]; randomSet[i] = randomSet[j]; randomSet[j] = m; } j++; } System.out.println("Efter " + (i + 1) + " iterationer " + Arrays.toString(randomSet)); i++; } System.out.println("Efter sortering: " + Arrays.toString(randomSet)); }
3
@Override public void mouseEntered(MouseEvent e) {}
0
private void fixsize() { if (res.get() != null) { Tex tex = res.get().layer(Resource.imgc).tex(); sz = tex.sz().add(shoff); } else { sz = new Coord(30, 30); } }
1
public static Object loadData(File inputFile) { Object returnValue = null; try { if (inputFile.exists()) { if (inputFile.isFile()) { ObjectInputStream readIn = new ObjectInputStream(new FileInputStream(inputFile)); returnValue = readIn.readObject(); readIn.close(); } else { System.err.println(inputFile + " is a directory."); } } else { System.err.println("File " + inputFile + " does not exist."); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return returnValue; }
4
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(ViewChargeSale.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewChargeSale.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewChargeSale.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewChargeSale.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ViewChargeSale().setVisible(true); } }); }
6
final void method3773(int i, Interface11 interface11) { try { anInt7617++; if (i != -1) aString7845 = null; if (((OpenGlToolkit) this).aBoolean7815) { method3782(interface11, 327685); method3751(interface11, i ^ ~0x4f); } else { if (anInt7746 >= 3) throw new RuntimeException(); if ((anInt7746 ^ 0xffffffff) <= -1) anInterface11Array7743[anInt7746].method48(-76); anInterface11_7745 = anInterface11_7740 = anInterface11Array7743[++anInt7746] = interface11; anInterface11_7745.method46(-11762); } } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("qo.JB(" + i + ',' + (interface11 != null ? "{...}" : "null") + ')')); } }
6
public void setLatitude( double latitude ) { this.latitude = latitude; }
0
protected void loadModules() { ConcurrentHashMap<String, String> inputProperties = configuration.filter("eva.modules"); Iterator it = inputProperties.entrySet().iterator(); while (it.hasNext()) { Map.Entry property = (Map.Entry) it.next(); String key = (String) property.getKey(); String val = (String) property.getValue(); try { System.out.printf("Loading module: [%s]\n", val); IModule module = (IModule) ClassLoader.load(val); System.out.printf("Booting module: [%s]\n", val); module.boot(); modules.put(key, module); } catch (Exception e) { System.err.printf("Unable to load class: [%s]\n", val); e.printStackTrace(); } it.remove(); // avoids a ConcurrentModificationException } }
2
@Override public void init() { Label dakror = new Label(Display.getWidth() / 2 - 768 / 2, Display.getHeight() / 2 - 384 / 2, 768, 384, ""); dakror.setTexture("/graphics/logo/dakror.png"); content.add(dakror); Label ichmed = new Label(Display.getWidth() / 2 - 768 / 2, Display.getHeight() / 2 - 384 / 2, 768, 384, "Ichmed"); // just a placeholder ichmed.font = ichmed.font.deriveFont(55f); ichmed.setVisible(false); content.add(ichmed); alpha = 0; if (CFG.INTERNET) { try { downloader = new ZipAssistant(); // if (MediaAssistant.needMediaUpdate("natives")) downloader.addDownload(new URL("http://dakror.de/vloxlands/GAMECONTENT/natives.zip"), new File(CFG.DIR, "natives"), true); if (downloader.hasDownloads()) { download = new ProgressBar(Display.getWidth() / 2, Display.getHeight() - 40, Display.getWidth() - 40, 0, true); content.add(download); downloader.start(); update = true; } } catch (Exception e) { e.printStackTrace(); } } else update = false; }
3
public double[] compareCollection(Collection otherCollection) { int similarSongCount = 0; HashMap<String, Artist> other = otherCollection.getArtists(); Set<String> keySet = other.keySet(); Iterator i = keySet.iterator(); while(i.hasNext()) { String tmpName = (String)i.next(); if(artists.containsKey(tmpName)) { Artist tmpArtist = artists.get(tmpName); similarSongCount += tmpArtist.compareArtist(other.get(tmpName)); } } double[] returnArray = new double[2]; returnArray[0] = similarSongCount; returnArray[1] = (double)similarSongCount / songCount; return returnArray; }
2
@Transactional public Experiences GetAllExperiencesWithSharedEventsAndUsersMoodEvent(String username) { Experiences exps = getExperiences(username); Experiences sharedExps = new Experiences(); User user = getUser(username); for (Experience experience : exps.getExperiences()) { if (experience.isShared() && experience.hasMember(user)) { for (Event event : experience.getEvents()) { if ((event.getClassName().equals("MoodEvent") && !event.getCreator().equals(username)) || !event.isShared()) { experience.getEvents().remove(event); } } sharedExps.getExperiences().add(experience); } } return sharedExps; }
7
public void checkCollision() { for (OperateShape shape : shapes) { if (shape instanceof Circle) { for (OperateShape checkShape : shapes) { event = new CollisionEvent(); if (checkShape instanceof Circle) { } else if (checkShape instanceof Block) { } else if (checkShape instanceof Bar) { } if (isCollision) { event.addTarget(checkShape); event.addTarget(shape); notifyEvent(event); isCollision = false; } } } } }
7
public void discoverWeb(String root) { //BFS algorithm is implemented below this.queue.add(root); this.discoveredWebsiteList.add(root); while (!queue.isEmpty()) { String v = this.queue.remove(); String rowHtml = readURL(v); // read the html content of the newly found website String regexp = "https://(\\w+\\.)*(\\w+)"; // reg exp for url pattern starting with https:// Pattern pattern = Pattern.compile(regexp); Matcher matcher = pattern.matcher(rowHtml); // search for pattern in the html content while( matcher.find() ){ String w = matcher.group(); //group() -> Returns the input subsequence matched by the previous match. if( !discoveredWebsiteList.contains(w) ){ discoveredWebsiteList.add(w); System.out.println("Website found with URL: " + w); queue.add(w); } } websitesProcessedFromQueue++; if (websitesProcessedFromQueue == 10) { break; // stop condition: stop after processing children of first 10 websites from queue } } }
4
private double getEntropy(List<Example> exampleCollection) { double positiveExampleCount = 0; double negativeExampleCount = 0; double q; for (Example e : exampleCollection) { if (e.getWinner() == 1) { positiveExampleCount++; } else { negativeExampleCount++; } } if (!((positiveExampleCount + negativeExampleCount) == 0)) { q = positiveExampleCount / (positiveExampleCount + negativeExampleCount); } else { q = 1; } // make q not zero but very small for the sake of correctly carrying out // logarithmic calculations if (q == 0) { q = 0.01; } else if (q == 1) { q = 0.99; } double entropy = -(q * (Math.log(q) / Math.log(2)) + (1 - q) * (Math.log(1 - q) / Math.log(2))); return entropy; }
5
@Override public void paintComponent(Graphics g){ super.paintComponent(g); if(nodes.get(0) == null) { return; } Graphics2D g2 = (Graphics2D)g; g2.setColor(Color.blue); int x = 0; int y = 0; double xs = (double)(this.getWidth()-b-(nodes.get(0).r*nodeScaling)); double ys = (double)(this.getHeight()-b-(nodes.get(0).r*nodeScaling)-noticeBorder); g2.setColor(Color.black); g2.fillRect(0, 0, this.getWidth(), this.getHeight()); g2.setColor(Color.blue); drawNode s; drawNode d; RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHints(rh); g2.setColor(Color.white); if(!ignoreLinks) { for(drawLink L : links.values()) { g2.setColor(L.color); s = nodes.get(L.sid); d = nodes.get(L.eid); if(s != null && d != null) { g2.drawLine((int)((s.x*xs)+(s.r*nodeScaling)/2d), (int)((s.y*ys)+(s.r*nodeScaling)/2d),(int)((d.x*xs)+(d.r*nodeScaling)/2d),(int)((d.y*ys)+(d.r*nodeScaling)/2d)); } } } for(drawNode N : nodes.values()) { g2.setColor(N.color); g2.fill(new Ellipse2D.Double(N.x*xs,N.y*ys, N.r*nodeScaling, N.r*nodeScaling)); g2.setColor(Color.black); g2.draw(new Ellipse2D.Double(N.x*xs,N.y*ys, N.r*nodeScaling, N.r*nodeScaling)); } if(showInfoForNode != -1 && nodeInfo.containsKey(showInfoForNode)) { drawNode N = nodes.get(showInfoForNode); x = (int)(N.x*xs + N.r*nodeScaling) + 3; y = (int)(N.y*ys); CTB.flipShift = (int)(N.r*nodeScaling)+5; CTB.draw(g2, x, y, this.getWidth(), this.getHeight(), nodeInfo.get(showInfoForNode)); } g2.setColor(Color.white); g2.setFont(new Font("Arial",Font.PLAIN,10)); g2.drawString("Ruud van de Bovenkamp - NAS", b, this.getHeight()-b); doneDrawing = true; }
8
private boolean withinBounds(String direction) { ArrayList<Integer> neighbours = new ArrayList<Integer>(getNeighbours(location, size)); int check = 0; boolean ret = false; if(direction.equals("up")){ check = location - size; if(neighbours.contains(check)){ ret = true; } } if(direction.equals("down")){ check = location + size; if(neighbours.contains(check)){ ret = true; } } if(direction.equals("left")){ check = location - 1; if(neighbours.contains(check)){ ret = true; } } if(direction.equals("right")){ check = location + 1; if(neighbours.contains(check)){ ret = true; } } return ret; }
8
public static List<List<Integer>> combine(int n, int k) { if (0 == k || k > n) return null; if (k == n) { List<List<Integer>> res = new ArrayList<List<Integer>>(); List<Integer> l = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) { l.add(i); } res.add(l); return res; } List<List<Integer>> stack = new ArrayList<List<Integer>>(); List<List<Integer>> res = new ArrayList<List<Integer>>(); for (int i = 1; i <= n; i++ ) { List<Integer> l = new ArrayList<Integer>(); l.add(i); stack.add(l); } while (0 != stack.size()) { List<Integer> f = stack.remove(0); if (k == f.size()) res.add(f); else { for (int i = f.get(f.size() - 1) + 1; i <= n; i++) { List<Integer> next = new ArrayList<Integer>(); next.addAll(f); next.add(i); stack.add(next); } } } return res; }
8
@Override public boolean shouldReact(Message message) { if(message.text.equals("counter get")) return true; try { getNum(message.text.replaceAll(" ", "")); return true; } catch(NumberFormatException ex) { return false; } }
2
private static void test2_3() throws FileNotFoundException { String test1 = "new game\n"+"examine\n"+"quit\n"+"yes\n"; HashMap<Integer, String> output = new HashMap<Integer, String>(); boolean passed = true; try { in = new ByteArrayInputStream(test1.getBytes()); System.setIn(in); out = new PrintStream("testing.txt"); System.setOut(out); Game.main(null); } catch (ExitException se) { } catch (Exception e) { System.setOut(stdout); System.out.println("Error: "); e.printStackTrace(); passed = false; } finally { System.setOut(stdout); @SuppressWarnings("resource") Scanner sc = new Scanner(new File("testing.txt")); ArrayList<String> testOutput = new ArrayList<String>(); while (sc.hasNextLine()) { testOutput.add(sc.nextLine()); } output.put(testOutput.size() - 3, ">> SYSTEM: could not identify a direct object in your input."); output.put(testOutput.size() - 2, ">> Are you sure you want to quit? (y/n)"); output.put(testOutput.size() - 1, ">>"); if (passed) { for (Map.Entry<Integer, String> entry : output.entrySet()) { if (!testOutput.get(entry.getKey()) .equals(entry.getValue())) { passed = false; System.out.println("test2_3 failed: Line " + entry.getKey()); System.out.println("\tExpected: " + entry.getValue()); System.out.println("\tReceived: " + testOutput.get(entry.getKey())); } } if (passed) { System.out.println("test2_3 passed"); } } else { System.out.println("test2_3 failed: error"); } } }
7
public boolean connectServer(int port, String hostIp, String name) { // 连接服务器 try { socket = new Socket(hostIp, port);// 根据端口号和服务器ip建立连接 writer = new PrintWriter(socket.getOutputStream()); reader = new BufferedReader(new InputStreamReader(socket .getInputStream())); // 发送客户端用户基本信息(用户名和ip地址) sendMessage(name + "@" + socket.getLocalAddress().toString()); // 开启接收消息的线程 messageThread = new MessageThread(reader, textArea); isConnected = true;// 已经连接上了 messageThread.start(); return true; } catch (Exception e) { textArea.append("port:" + port + " IP:" + hostIp + " 的伺服器連線失敗QQ" + "\r\n"); isConnected = false;// 未连接上 return false; } }
1
private void checkStudents(Group newGroup, Group oldGroup) throws ServerException { if (log.isDebugEnabled()) log.debug("Method call. Arguments: " + newGroup + " " + oldGroup); for (Student oldStudent : oldGroup.getStudents()) { int j = 0; for (Student newStudent : newGroup.getStudents()) { if (!oldStudent.equals(newStudent) && oldStudent.getId() == newStudent.getId()) { updateStudentInDB(newStudent); break; } if (oldStudent.equals(newStudent)) { break; } j++; } if (j == newGroup.getStudents().size()) { removeStudentFromDB(oldStudent); } } for (Student newStudent : newGroup.getStudents()) { checkStudentForNew(newStudent, oldGroup); } }
8
public void salvar(String grupo, String nome, String numTelefone) { telefoneDAO = new TelefoneDAO(); setTelefone(telefone); if (this.telefone.getCodtelefone() == null) { try { telefoneDAO.busca(numTelefone); JOptionPane.showMessageDialog(null, "Telefone já existe\n", "Alerta", JOptionPane.ERROR_MESSAGE); txt_telefone.requestFocus(); } catch (NoResultException ex) { try { telefoneDAO.salvar(telefone); JOptionPane.showMessageDialog(null, "Telefone salvo com sucesso!"); limpaCampos(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro ao Salvar Telefone\n", "Alerta", JOptionPane.ERROR_MESSAGE); txt_contato.requestFocus(); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro ao Buscar Telefone " + numTelefone); limpaCampos(); } } else { try { telefoneDAO.salvar(telefone); JOptionPane.showMessageDialog(null, "Contato Alterado com sucesso!"); limpaCampos(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Telefone já Cadastrado\n", "Alerta", JOptionPane.ERROR_MESSAGE); txt_contato.requestFocus(); } } }
5
private BSTNode<T> recAdd(T element, BSTNode<T> tree) { if (tree == null) // insert new element here tree = new BSTNode<T>(element); else if (element.compareTo(tree.getInfo()) <= 0) // Add in left subtree tree.setLeft(recAdd(element, tree.getLeft())); else // Add in right subtree tree.setRight(recAdd(element, tree.getRight())); return tree; }
2
@Override public void process_term (int linger_) { if (timer_started) { io_object.cancel_timer (reconnect_timer_id); timer_started = false; } if (handle_valid) { io_object.rm_fd (handle); handle_valid = false; } if (handle != null) close (); super.process_term (linger_); }
3
public Icon getIcon() { if (tile == null) { return null; } else if (!tile.isFaceUp()) { return ICON_FACE_DOWN; } else if (tile instanceof Bear) { return ICON_BEAR; } else if (tile instanceof Duck) { return ICON_DUCK; } else if (tile instanceof Fox) { return ICON_FOX; } else if (tile instanceof Hunter) { // Hunter's icon depends on direction return getHunterIcon((Hunter) tile); } else if (tile instanceof Lumberjack) { return ICON_LUMBERJACK; } else if (tile instanceof Pheasant) { return ICON_PHEASANT; } else if (tile instanceof Tree) { return ICON_TREE; } else { throw new IllegalStateException( "Unknown tile class " + tile.getClass().getName()); } }
9
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if((msg.amITarget(affected)) &&(mobs.contains(msg.source()))) { if((msg.targetMinor()==CMMsg.TYP_BUY) ||(msg.targetMinor()==CMMsg.TYP_BID) ||(msg.targetMinor()==CMMsg.TYP_SELL) ||(msg.targetMinor()==CMMsg.TYP_LIST) ||(msg.targetMinor()==CMMsg.TYP_VALUE) ||(msg.targetMinor()==CMMsg.TYP_VIEW)) { msg.source().tell(L("@x1 looks unwilling to do business with you.",affected.name())); return false; } } return super.okMessage(myHost,msg); }
8
public final String getMethodName(int identifier) { String mname = methods[identifier].getName(); int j = ClassMetaobject.methodPrefixLen; for (;;) { char c = mname.charAt(j++); if (c < '0' || '9' < c) break; } return mname.substring(j); }
3