@Override @SuppressWarnings("ConstantConditions") protected void doVisitField( @Nullable VariableElement oldField, @Nullable VariableElement newField) { if (!shouldCheck(oldField, newField)) { return; } Predicate<VariableElement> isNotEnumConstant = v -> v.getKind() != ElementKind.ENUM_CONSTANT; List<? extends VariableElement> fields = ElementFilter.fieldsIn(oldField.getEnclosingElement().getEnclosedElements()); fields.removeIf(isNotEnumConstant); int oldIdx = fields.indexOf(oldField); fields = ElementFilter.fieldsIn(newField.getEnclosingElement().getEnclosedElements()); fields.removeIf(isNotEnumConstant); int newIdx = fields.indexOf(newField); if (newIdx != oldIdx) { pushActive(oldField, newField, oldIdx, newIdx); } }
/* (non-Javadoc) * @see de.codesourcery.javr.assembler.parser.LexerIf#setIgnoreWhitespace(boolean) */ public void setIgnoreWhitespace(boolean ignoreWhitespace) { if (DEBUG) { System.out.println( "setIgnoreWhitespace(): ignore=" + this.ignoreWhitespace + " => ignore=" + ignoreWhitespace); } if (this.ignoreWhitespace == ignoreWhitespace) { return; } if (this.ignoreWhitespace && !ignoreWhitespace) { // change: ignore whitespace -> do not ignore if (!tokens.isEmpty()) { int offset = tokens.get(0).offset; if (DEBUG) { System.out.println("current token: " + tokens.get(0)); } tokens.clear(); scanner.setOffset(offset); parseTokens(); } } else { // change: do not ignore whitespace -> ignore whitespace tokens.removeIf(tok -> tok.is(TokenType.WHITESPACE)); } this.ignoreWhitespace = ignoreWhitespace; }
/** * Exercise 2 * * <p>Remove the words that have odd lengths from the list. */ private void exercise2() { List<String> list = new ArrayList<>(Arrays.asList("alpha", "bravo", "charlie", "delta", "echo", "foxtrot")); /* YOUR CODE HERE */ list.removeIf(w -> w.length() % 2 != 0); list.forEach(System.out::println); }
static void collectionTest() { // removeIf Collection<String> c = new HashSet<>(); c.add("Content 1"); c.add("Content 2"); c.add("Content 3"); c.add("Content 4"); c.removeIf(s -> s.contains("2")); System.out.println("removeIf : " + c); /// 基本操作 List<Integer> list = new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)); list.removeIf(a -> a % 3 == 0); System.out.println("a % 3 == 0 " + list); // OR 操作 Predicate<Integer> predicate2 = a -> a % 3 == 0; Predicate<Integer> predicate3 = a -> a % 5 == 0; list = new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)); list.removeIf(predicate2.or(predicate3)); System.out.println("a % 3 == 0 or a % 5 == 0 " + list); // AND 操作 predicate2 = a -> a % 3 == 0; predicate3 = a -> a % 5 == 0; list = new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)); list.removeIf(predicate2.and(predicate3)); System.out.println("a % 3 == 0 and a % 5 == 0 " + list); List<String> stringList = Arrays.asList("a", "b"); stringList.forEach(System.out::println); stringList = Arrays.asList("a", "b", "c"); stringList.replaceAll(String::toUpperCase); System.out.println(stringList); // [A, B, C] stringList = Arrays.asList("a", "b", "c"); stringList.sort(String::compareTo); Map<String, Integer> map = new HashMap<>(); map.put("A", 10); map.put("B", 20); map.put("C", 30); map.forEach((k, v) -> System.out.println("Item : " + k + " Count : " + v)); System.out.println(map.getOrDefault("D", 40)); // => 40 }
/** * Add the given history to the entry (uses AutocompleteMenuUpdater if non-null). * * @param entry */ public void updateHistory(final String entry) { if (updater != null) updater.updateHistory(entry); else { // add entry to top of menu items (for the particular autocomplete menu instance) // (Currently, there are two instances of this class in the editor: one for the inline editor, // one for the palette) final List<MenuItem> items = menu.getItems(); // remove entry if present, to avoid duplication items.removeIf((item) -> item.getText().equals(entry)); items.add(0, createMenuItem(entry)); } }
public void removeIf(Predicate<Entity> pred) { entityList.removeIf( e -> { if (pred.test(e)) { e.destroy(); return true; } return false; }); }
public static void main(String[] args) { List<String> strings = new ArrayList<>(); Collections.addAll(strings, "Java", "7", "FTW"); strings.forEach(x -> System.out.print(x + " ")); // Will output: Java 8 FTW System.out.println("\nLets update to Java 8 :) ..."); strings.replaceAll(x -> x == "7" ? "8" : x); // similar to something we'll see later... strings.forEach(x -> System.out.print(x + " ")); // Will output: Java 8 WAT System.out.println("\nNow lets remove the version..."); strings.removeIf(x -> x == "8"); strings.forEach(x -> System.out.print(x + " ")); // Will output: Java 8 WAT }
public void modtagContainer(Container container) { int i = 0; if (lister.isEmpty()) { lister.add(new ArrayList<Container>()); } else if (!receiveBeforePickup) { for (List<Container> l : lister) { l.removeIf(e -> e.getPickupDate().isEqual(container.getDateOfArrival())); } removeEmptyListe(); } while (!checkList(container, lister.get(i))) { lister.add(new ArrayList<Container>()); placed = checkList(container, lister.get(i++)); } removeEmptyListe(); if (receiveBeforePickup) { for (List<Container> l : lister) { l.removeIf(e -> e.getPickupDate().isEqual(container.getDateOfArrival())); } removeEmptyListe(); } getMaxAntalContainer(); getMaxAntalPlace(); }
public static void testPredicate(){ List<Integer> strList=new ArrayList<Integer>(); strList.add(5); strList.add(1001); strList.add(1002); final Predicate< Integer> filter=new Predicate<Integer>() { @Override public boolean test(Integer t) { if(t>4){ return true; }else{ return false; } } }; strList.removeIf(filter); System.out.println(strList.size()+strList.toString()); }
@SubscribeEvent public void checkingameGUI(TickEvent.RenderTickEvent e) { boolean b = mc.ingameGUI instanceof SAOIngameGUI; if (mc.ingameGUI != null && SAOOption.DEFAULT_UI.getValue() == b) mc.ingameGUI = b ? new GuiIngameForge(mc) : new SAOIngameGUI(mc); deadHandlers.forEach( ent -> { final boolean deadStart = (ent.deathTime == 1); final boolean deadExactly = (ent.deathTime >= 18); if (deadStart) { ent.deathTime++; SAOSound.playAtEntity(ent, SAOSound.PARTICLES_DEATH); } if (deadExactly) { StaticRenderer.doSpawnDeathParticles(mc, ent); ent.setDead(); } }); deadHandlers.removeIf(ent -> ent.isDead); }
public static void runGame(String filename, int port, int rounds, int time) throws IOException, InterruptedException, ExecutionException { final World world; int users = 0; try { WorldParser wp = new WorldParser(); world = wp.parse(filename); users = world.getNumberOfSpawnpoints(); } catch (FileNotFoundException e) { logger.error("Map file not found: '" + filename + "'."); return; } Message info = new InfoMessage(time, rounds, filename, users); logger.info("Starting graphics server."); GraphicsServer graphics = new GraphicsServer(info, port + 10); graphics.start(); logger.info("Waiting for clients to connect."); ServerSocket socket = new ServerSocket(port); List<Player> players = new ArrayList<>(); for (int i = 0; i < users; i++) { Socket client = socket.accept(); Connection conn = new Connection(client); new Thread(conn).start(); conn.sendMessage(info); players.add(new Player(conn)); } logger.info("All clients connected."); logger.info("Setting spawnpoints."); Collections.shuffle(players); Queue<Vector2d> spawnpoints = world.getSpawnpoints(); for (Player player : players) { player.setSpawn(spawnpoints.poll()); } logger.info("Sending initial game state."); Message state0 = new GameStateMessage(0, world, players); players.stream().peek(p -> p.send(state0)); graphics.sendToAll(state0); logger.info("Recieved loadout from all."); logger.info("Starting game."); for (int round = 1; round <= rounds; round++) { for (Player player : players) { logger.info("Starting player '" + player.getName() + "' turn."); logger.info("Clearing all messages from player queue."); player.clear(); logger.info("Sending first round to all."); Message state = new GameStateMessage(round, world, players); players.stream().forEach(p -> p.send(state)); graphics.sendToAll(state); if (player.isDead()) { logger.info(player.getName() + " is dead. Respawning..."); player.respawn(); } else { List<ActionMessage> actions = new ArrayList<>(); Instant stop = Instant.now().plus(time, MILLIS); for (int a = 0; a < 3; a++) { logger.info("Waiting for action " + a + "."); long timeout = Math.max(0, MILLIS.between(Instant.now(), stop)); ActionMessage action = player.next(timeout, MILLISECONDS); if (action == null) { logger.debug( "==> Player '" + player.getName() + "' timed out in round " + round + "."); break; } try { logger.info("Performing action."); action.performAction(player, world); actions.add(action); logger.info("Successful message: " + action.toString()); players.stream().forEach(p -> p.send(action)); } catch (ProtocolException e) { logger.debug(e.getMessage()); player.send(new ErrorMessage(e)); } } logger.info("Waiting to complete round."); Thread.sleep(Math.max(0, MILLIS.between(Instant.now(), stop))); player.send(new EndTurnMessage()); logger.info("Sending actions to graphics."); for (Message m : actions) { graphics.sendToAll(m); } } } Collections.rotate(players, 1); } players.sort(comparing(Player::score)); Collections.reverse(players); players.removeIf(p -> p.score() < players.get(0).score()); String winner; if (players.size() > 1) { winner = String.format( "A %d-way tie between: %s", players.size(), String.join(", ", players.toArray(new String[players.size()]))); } else { winner = String.format("The winner is ", players.get(0)); } logger.info("Winner: " + winner); Message message = new GameFinishedMessage(winner); players.stream().forEach(p -> p.send(message)); graphics.sendToAll(message); socket.close(); }
@Test public void removeIfTest() { list.removeIf(x -> x.startsWith("A")); assertEquals(list, Collections.singletonList("YNDX")); }
@Override public CorfuDBView getNewView(CorfuDBView oldView, NetworkException e) { /* it's null, don't change anything */ if (e == null) { return oldView; } /* Is the exception for a Logging Unit? */ if (e.protocol instanceof IWriteOnceLogUnit) { /* Okay, so was it a read or a write? */ if (e.write) { /* in the case of a write, find the segment belonging to the protocol, and remove that protocol from the segment. */ CorfuDBView newView = (CorfuDBView) Serializer.copyShallow(oldView); for (CorfuDBViewSegment segment : newView.getSegments()) { for (List<IServerProtocol> nodeList : segment.getGroups()) { if (nodeList.size() > 1) { nodeList.removeIf(n -> n.getFullString().equals(e.protocol.getFullString())); } } } log.info("Reconfiguring all nodes in view to new epoch " + oldView.getEpoch() + 1); newView.moveAllToNewEpoch(oldView.getEpoch() + 1); return newView; } /* for reads, we don't do anything, for now... */ log.warn("Reconfigure due to read, ignoring"); return oldView; } else if (e.protocol instanceof ISimpleSequencer) { if (oldView.getSequencers().size() <= 1) { log.warn( "Request reconfiguration of sequencers but there is no fail-over available! [available sequencers=" + oldView.getSequencers().size() + "]"); return oldView; } else { CorfuDBView newView = (CorfuDBView) Serializer.copyShallow(oldView); newView.moveAllToNewEpoch(oldView.getEpoch() + 1); /* Interrogate each log unit to figure out last issued token */ long last = -1; for (CorfuDBViewSegment segment : newView.getSegments()) { int groupNum = 1; for (List<IServerProtocol> nodeList : segment.getGroups()) { for (IServerProtocol n : nodeList) { try { last = Long.max( last, ((IWriteOnceLogUnit) n).highestAddress() * segment.getGroups().size() + groupNum); } catch (NetworkException ne) { } } groupNum++; } } log.warn( "Removing sequencer " + e.protocol.getFullString() + " from configuration, discover last sequence was " + last); newView.getSequencers().removeIf(n -> n.getFullString().equals(e.protocol.getFullString())); try { ((ISimpleSequencer) newView.getSequencers().get(0)).recover(last); } catch (Exception ex) { log.warn("Tried to install recovered sequence from sequencer, but failed", e); } return newView; } } else { log.warn("Request reconfiguration for protocol we don't know how to reconfigure", e.protocol); return (CorfuDBView) Serializer.copyShallow(oldView); } }
/** * Puts the given lesson plans into classrooms based on the distance the member fo staff will have * to travel between each lesson. * * @param lessonPlans The lessonPlans to be put into classrooms. * @param classrooms The classrooms to put lessons plans into. * @param distances The distances between the classrooms. * @return The list of lessonPlans after they have been put into classrooms. */ private boolean putLessonPlansIntoClassrooms( List<LessonPlan> lessonPlans, List<Classroom> classrooms, List<Distance> distances) { // Create a week of periods for this subject List<List<LessonPlan>> week = new ArrayList<>(); for (int i = 0; i < 5; i++) { week.add(new ArrayList<>()); } lessonPlans .stream() .forEach(lessonPlan -> week.get(lessonPlan.period.day.id - 1).add(lessonPlan)); List<Period> periods; // Iterate through each day for (int dayNo = 0; dayNo < week.size(); dayNo++) { // Get the periods of this day try { periods = daoManager .getPeriodDao() .getAllByDay( daoManager .getDayDao() .getById(dayNo + 1) .orElseThrow( () -> new IllegalStateException("Failed to find periods in a day"))); // The above exception should never be thrown periods.sort((o1, o2) -> o1.startTime.getHour() - o2.startTime.getHour()); } catch (DataAccessException e) { DataExceptionHandler.handleJavaFx(e, "period", false); return false; } catch (DataConnectionException e) { DataExceptionHandler.handleJavaFx(e, null, true); return false; } // Get this days lessons and randomly allocate the first period List<LessonPlan> day = week.get(dayNo); List<LessonPlan> firstPeriod = new ArrayList<>(); day.forEach( lessonPlan -> { if (lessonPlan.period.startTime.equals(LocalTime.of(9, 10))) { firstPeriod.add(lessonPlan); } }); classrooms .stream() .forEach( classroom -> { for (LessonPlan lessonPlan : firstPeriod) { if (lessonPlan.classroom.id == -1) { lessonPlan.classroom = classroom; break; } } }); // Store the first period in the timetabled list firstPeriod.forEach( lessonPlan -> { int index = lessonPlans.indexOf(lessonPlan); lessonPlans.set(index, lessonPlan); }); List<LessonPlan> previousPeriod = new ArrayList<>(firstPeriod); // Iterate through the other periods for (int periodNo = 1; periodNo < 5; periodNo++) { List<LessonPlan> period = new ArrayList<>(); for (LessonPlan lessonPlan : day) { if (lessonPlan.period.equals(periods.get(periodNo - 1))) { period.add(lessonPlan); } } // Timetable lessons where the staff member had a lesson previously for (LessonPlan lessonPlan : period) { Staff staff = lessonPlan.staff; Optional<LessonPlan> previousLesson = previousPeriod.stream().filter(lesson -> lesson.staff.equals(staff)).findFirst(); if (previousLesson.isPresent()) { Optional<LessonPlan> planOptional = period .stream() .filter(plan -> plan.classroom.equals(previousLesson.get().classroom)) .findFirst(); if (planOptional.isPresent()) { List<Distance> availableRooms = distances .stream() .filter( distance -> distance.startRoom.equals(planOptional.get().classroom) || distance.endRoom.equals(planOptional.get().classroom)) .collect(Collectors.toList()); availableRooms.removeIf( distance -> { boolean remove = false; for (LessonPlan plan : period) { if (plan.classroom.equals(distance.startRoom) || plan.classroom.equals(distance.endRoom)) { remove = true; } } return remove; }); availableRooms.sort((o1, o2) -> o1.distance - o2.distance); Distance nextTrip = availableRooms.get(0); if (nextTrip.startRoom.equals(planOptional.get().classroom)) { lessonPlan.classroom = nextTrip.endRoom; } else if (nextTrip.endRoom.equals(planOptional.get().classroom)) { lessonPlan.classroom = nextTrip.startRoom; } else { assert false : "The new classroom should be one from the shortest distance!"; } } else { lessonPlan.classroom = previousLesson.get().classroom; } } } // Timetable the remaining lessons randomly for (LessonPlan lessonPlan : period) { if (lessonPlan.classroom != null) { List<Classroom> availableRooms = new ArrayList<>(); availableRooms.addAll(classrooms); availableRooms.removeIf( classroom -> { boolean remove = false; for (LessonPlan plan : period) { if (classroom.equals(plan.classroom)) { remove = true; } } return remove; }); lessonPlan.classroom = availableRooms.get(0); } } previousPeriod = period; } } return true; }
@Override public void onEnable() { MineCloud.environmentSetup(); mongo = MineCloud.instance().mongo(); redis = MineCloud.instance().redis(); redis.addChannel( SimpleRedisChannel.create("server-start-notif", redis) .addCallback( (message) -> getProxy() .getScheduler() .schedule( this, () -> { if (message.type() != MessageType.BINARY) { return; } try { MessageInputStream stream = message.contents(); Server server = mongo.repositoryBy(Server.class).findFirst(stream.readString()); addServer(server); } catch (IOException ignored) { } }, 1, TimeUnit.SECONDS))); redis.addChannel( SimpleRedisChannel.create("server-shutdown-notif", redis) .addCallback( (message) -> { if (message.type() != MessageType.BINARY) { return; } MessageInputStream stream = message.contents(); removeServer(stream.readString()); })); redis.addChannel( SimpleRedisChannel.create("teleport", redis) .addCallback( (message) -> { if (message.type() != MessageType.BINARY) { return; } MessageInputStream stream = message.contents(); ProxiedPlayer player = getProxy().getPlayer(stream.readString()); if (player == null) { return; } String name = stream.readString(); ServerInfo info = getProxy().getServerInfo(name); if (info == null) { ServerRepository repository = mongo.repositoryBy(Server.class); Server server = repository.findOne("_id", name); if (server != null) { addServer(server); info = getProxy().getServerInfo(name); } } player.connect(info); })); redis.addChannel( SimpleRedisChannel.create("teleport-type", redis) .addCallback( (message) -> { if (message.type() != MessageType.BINARY) { return; } MessageInputStream stream = message.contents(); ProxiedPlayer player = getProxy().getPlayer(stream.readString()); if (player == null) { return; } ServerType type = mongo.repositoryBy(ServerType.class).findFirst(stream.readString()); if (type == null) { getLogger() .log(Level.SEVERE, "Received teleport message with invalid server type"); return; } ServerRepository repository = mongo.repositoryBy(Server.class); List<Server> servers = repository .find( repository .createQuery() .field("network") .equal(bungee().network()) .field("type") .equal(type) .field("port") .notEqual(-1) .field("ramUsage") .notEqual(-1)) .asList(); Collections.sort( servers, (a, b) -> a.onlinePlayers().size() - b.onlinePlayers().size()); Server server = servers.get(0); ServerInfo info = getProxy().getServerInfo(server.name()); if (info == null) { getLogger() .warning("Cannot find " + server.name() + " in ServerInfo store, adding."); addServer(server); info = getProxy().getServerInfo(server.name()); } player.connect(info); })); getProxy() .getScheduler() .schedule( this, () -> getProxy() .getScheduler() .runAsync( this, () -> { Bungee bungee = bungee(); if (bungee != null) { return; } getLogger().info("Bungee removed from database, going down..."); getProxy().stop(); // bye bye }), 2, 2, TimeUnit.SECONDS); BungeeType type = bungee().type(); File nContainer = new File("nplugins/"); nContainer.mkdirs(); type.plugins() .forEach( (plugin) -> { String version = plugin.version(); PluginType pluginType = plugin.type(); File pluginsContainer = new File("/mnt/minecloud/plugins/", pluginType.name() + "/" + version); List<File> plugins = new ArrayList<>(); getLogger().info("Loading " + pluginType.name() + "..."); if (validateFolder(pluginsContainer, pluginType, version)) return; for (File f : pluginsContainer.listFiles()) { if (f.isDirectory()) continue; // ignore directories File pl = new File(nContainer, f.getName()); try { Files.copy(f, pl); } catch (IOException ex) { getLogger() .log( Level.SEVERE, "Could not load " + pluginType.name() + ", printing stacktrace..."); ex.printStackTrace(); return; } plugins.add(pl); } File configs = new File( "/mnt/minecloud/configs/", pluginType.name() + "/" + (plugin.config() == null ? version : plugin.config())); File configContainer = new File(nContainer, pluginType.name()); if (!validateFolder(configs, pluginType, version)) copyFolder(configs, configContainer); }); getProxy() .getScheduler() .schedule( this, () -> { ServerRepository repository = mongo.repositoryBy(Server.class); List<Server> servers = repository .find(repository.createQuery().field("network").equal(bungee().network())) .asList(); servers.removeIf((s) -> s.port() == -1); servers.forEach(this::addServer); getProxy().setReconnectHandler(new ReconnectHandler(this)); getProxy().getPluginManager().registerListener(this, new MineCloudListener(this)); // release plugin manager lock try { Field f = PluginManager.class.getDeclaredField("toLoad"); f.setAccessible(true); f.set(getProxy().getPluginManager(), new HashMap<>()); } catch (NoSuchFieldException | IllegalAccessException ignored) { } getProxy().getPluginManager().detectPlugins(nContainer); getProxy().getPluginManager().loadPlugins(); getProxy() .getPluginManager() .getPlugins() .stream() .filter((p) -> !p.getDescription().getName().equals("MineCloud-Bungee")) .forEach(Plugin::onEnable); }, 0, TimeUnit.SECONDS); }
private void verificarCondiciones() { inscripciones.removeIf(inscripcion -> inscripcion.noVerificaLaCondicion(this)); }