List of usage examples for org.apache.commons.lang3.tuple MutablePair getLeft
@Override
public L getLeft()
From source file:AIR.Common.xml.XmlReader.java
private boolean traverseNextSibling() throws IOException { /*/* w w w.j a v a2s .c om*/ * if (_file.available () == 0) { return false; } */ if (_stack.size() == 0) return false; MutablePair<Content, Integer> currentTop = _stack.pop(); if (_stack.size() != 0) { MutablePair<Content, Integer> topElement = _stack.peek(); // We already went into topElement's children and so there is no // need to check if it of type element. Element topElementNode = (Element) topElement.getLeft(); int nextChild = topElement.getRight() + 1; if (topElementNode.getChildren().size() > nextChild) { topElement.setRight(nextChild); Element nextTraversalNode = topElementNode.getChildren().get(nextChild); _stack.push(new MutablePair<Content, Integer>(nextTraversalNode, -1)); return true; } } // else put the previous top back on the top. _stack.push(currentTop); return false; }
From source file:hu.mta.sztaki.lpds.cloud.simulator.DeferredEvent.java
/** * Allows constructing objects that will receive an eventAction() call from * Timed after delay ticks.//w w w .j a v a 2s .c o m * * @param delay * the number of ticks that should pass before this deferred * event object's eventAction() will be called. */ public DeferredEvent(final long delay) { if (delay <= 0) { eventArrival = Timed.getFireCount(); eventAction(); received = true; return; } eventArrival = Timed.calcTimeJump(delay); MutablePair<Integer, DeferredEvent[]> simultaneousReceiverPairs = toSweep.get(eventArrival); if (simultaneousReceiverPairs == null) { simultaneousReceiverPairs = new MutablePair<Integer, DeferredEvent[]>(0, new DeferredEvent[5]); toSweep.put(eventArrival, simultaneousReceiverPairs); } int len = simultaneousReceiverPairs.getLeft(); DeferredEvent[] simultaneousReceivers = simultaneousReceiverPairs.getRight(); if (len == simultaneousReceivers.length) { DeferredEvent[] temp = new DeferredEvent[simultaneousReceivers.length * 2]; System.arraycopy(simultaneousReceivers, 0, temp, 0, len); simultaneousReceivers = temp; simultaneousReceiverPairs.setRight(temp); } simultaneousReceivers[len++] = this; simultaneousReceiverPairs.setLeft(len); if (!dispatcherSingleton.isSubscribed() || dispatcherSingleton.getNextEvent() > eventArrival) { dispatcherSingleton.updateDispatcher(); } }
From source file:io.cloudslang.lang.compiler.caching.CachedPrecompileServiceImplTest.java
@Test public void testCacheValueSuccess() { String myPath = "aaa"; ExecutableModellingResult executableModellingResult = mock(ExecutableModellingResult.class); SlangSource slangSource = mock(SlangSource.class); final MutablePair<CacheValue, Boolean> pair = new MutablePair<>(); doAnswer(new Answer() { @Override/* w ww.jav a 2 s . c o m*/ public Object answer(InvocationOnMock invocation) throws Throwable { pair.setLeft((CacheValue) invocation.getArguments()[1]); return null; } }).when(cache).put(anyString(), any(CacheValue.class)); // Tested call cachedPrecompileServiceImpl.cacheValue(myPath, executableModellingResult, slangSource); verify(cache).put(eq(myPath), same(pair.getLeft())); }
From source file:bwem.map.MapInitializerImpl.java
@Override public void replaceAreaIds(final WalkPosition p, final AreaId newAreaId) { final MiniTile origin = ((TerrainDataInitializer) getData()).getMiniTile_(p, CheckMode.NO_CHECK); final AreaId oldAreaId = origin.getAreaId(); ((MiniTileImpl) origin).replaceAreaId(newAreaId); List<WalkPosition> toSearch = new ArrayList<>(); toSearch.add(p);//from w w w . j av a 2s . c om while (!toSearch.isEmpty()) { final WalkPosition current = toSearch.remove(toSearch.size() - 1); final WalkPosition[] deltas = { new WalkPosition(0, -1), new WalkPosition(-1, 0), new WalkPosition(+1, 0), new WalkPosition(0, +1) }; for (final WalkPosition delta : deltas) { final WalkPosition next = current.add(delta); if (getData().getMapData().isValid(next)) { final MiniTile miniTile = ((TerrainDataInitializer) getData()).getMiniTile_(next, CheckMode.NO_CHECK); if (miniTile.getAreaId().equals(oldAreaId)) { toSearch.add(next); ((MiniTileImpl) miniTile).replaceAreaId(newAreaId); } } } } // also replaces references of oldAreaId by newAreaId in getRawFrontier: if (newAreaId.intValue() > 0) { for (final MutablePair<MutablePair<AreaId, AreaId>, WalkPosition> f : super.rawFrontier) { if (f.getLeft().getLeft().equals(oldAreaId)) { f.getLeft().setLeft(newAreaId); } if (f.getLeft().getRight().equals(oldAreaId)) { f.getLeft().setRight(newAreaId); } } } }
From source file:bwem.map.MapInitializerImpl.java
@Override public Altitude setAltitudesAndGetUpdatedHighestAltitude(final Altitude currentHighestAltitude, final TerrainData terrainData, final List<MutablePair<WalkPosition, Altitude>> deltasByAscendingAltitude, final List<MutablePair<WalkPosition, Altitude>> activeSeaSideList, final int altitudeScale) { Altitude updatedHighestAltitude = currentHighestAltitude; for (final MutablePair<WalkPosition, Altitude> deltaAltitude : deltasByAscendingAltitude) { final WalkPosition d = deltaAltitude.getLeft(); final Altitude altitude = deltaAltitude.getRight(); for (int i = 0; i < activeSeaSideList.size(); ++i) { final MutablePair<WalkPosition, Altitude> current = activeSeaSideList.get(i); if (altitude.intValue() - current.getRight().intValue() >= 2 * altitudeScale) { // optimization : once a seaside miniTile verifies this condition, // we can throw it away as it will not generate min altitudes anymore Utils.fastErase(activeSeaSideList, i--); } else { final WalkPosition[] deltas = { new WalkPosition(d.getX(), d.getY()), new WalkPosition(-d.getX(), d.getY()), new WalkPosition(d.getX(), -d.getY()), new WalkPosition(-d.getX(), -d.getY()), new WalkPosition(d.getY(), d.getX()), new WalkPosition(-d.getY(), d.getX()), new WalkPosition(d.getY(), -d.getX()), new WalkPosition(-d.getY(), -d.getX()) }; for (final WalkPosition delta : deltas) { final WalkPosition w = current.getLeft().add(delta); if (terrainData.getMapData().isValid(w)) { final MiniTile miniTile = ((TerrainDataInitializer) terrainData).getMiniTile_(w, CheckMode.NO_CHECK); if (((MiniTileImpl) miniTile).isAltitudeMissing()) { if (updatedHighestAltitude != null && updatedHighestAltitude.intValue() > altitude.intValue()) { throw new IllegalStateException(); }// w w w .j a va 2 s .co m updatedHighestAltitude = altitude; current.setRight(altitude); ((MiniTileImpl) miniTile).setAltitude(altitude); } } } } } } return updatedHighestAltitude; }
From source file:bwem.map.MapInitializerImpl.java
@Override public List<TempAreaInfo> computeTempAreas( final List<MutablePair<WalkPosition, MiniTile>> miniTilesByDescendingAltitude) { final List<TempAreaInfo> tempAreaList = new ArrayList<>(); tempAreaList.add(new TempAreaInfo()); // tempAreaList[0] left unused, as AreaIds are > 0 for (final MutablePair<WalkPosition, MiniTile> current : miniTilesByDescendingAltitude) { final WalkPosition pos = new WalkPosition(current.getLeft().getX(), current.getLeft().getY()); final MiniTile cur = current.getRight(); final MutablePair<AreaId, AreaId> neighboringAreas = findNeighboringAreas(pos); if (neighboringAreas.getLeft() == null) { // no neighboring area : creates of a new area tempAreaList.add(new TempAreaInfo(new AreaId(tempAreaList.size()), cur, pos)); } else if (neighboringAreas.getRight() == null) { // one neighboring area : adds cur to the existing area tempAreaList.get(neighboringAreas.getLeft().intValue()).add(cur); } else { // two neighboring areas : adds cur to one of them & possible merging AreaId smaller = neighboringAreas.getLeft(); AreaId bigger = neighboringAreas.getRight(); if (tempAreaList.get(smaller.intValue()).getSize() > tempAreaList.get(bigger.intValue()) .getSize()) {/*from ww w. ja v a 2 s. com*/ AreaId smallerTmp = smaller; smaller = bigger; bigger = smallerTmp; } // Condition for the neighboring areas to merge: // any_of(StartingLocations().begin(), StartingLocations().end(), [&pos](const TilePosition & startingLoc) // { return dist(TilePosition(pos), startingLoc + TilePosition(2, 1)) <= 3;}) boolean cppAlgorithmStdAnyOf = getData().getMapData().getStartingLocations().stream() .anyMatch(startingLoc -> BwemExt.dist(pos.toTilePosition(), startingLoc.add(new TilePosition(2, 1))) <= 3.0); final int curAltitude = cur.getAltitude().intValue(); final int biggerHighestAltitude = tempAreaList.get(bigger.intValue()).getHighestAltitude() .intValue(); final int smallerHighestAltitude = tempAreaList.get(smaller.intValue()).getHighestAltitude() .intValue(); if ((tempAreaList.get(smaller.intValue()).getSize() < 80) || (smallerHighestAltitude < 80) || ((double) curAltitude / (double) biggerHighestAltitude >= 0.90) || ((double) curAltitude / (double) smallerHighestAltitude >= 0.90) || cppAlgorithmStdAnyOf) { // adds cur to the absorbing area: tempAreaList.get(bigger.intValue()).add(cur); // merges the two neighboring areas: replaceAreaIds(tempAreaList.get(smaller.intValue()).getWalkPositionWithHighestAltitude(), bigger); tempAreaList.get(bigger.intValue()).merge(tempAreaList.get(smaller.intValue())); } else { // no merge : cur starts or continues the frontier between the two neighboring areas // adds cur to the chosen Area: tempAreaList.get(chooseNeighboringArea(smaller, bigger).intValue()).add(cur); super.rawFrontier.add(new MutablePair<>(neighboringAreas, pos)); } } } // Remove from the frontier obsolete positions rawFrontier.removeIf(f -> f.getLeft().getLeft().equals(f.getLeft().getRight())); return tempAreaList; }
From source file:com.replaymod.replaystudio.filter.SquashFilter.java
@Override public void onEnd(PacketStream stream, long timestamp) { List<PacketData> result = new ArrayList<>(); result.addAll(unhandled);//from w w w.j av a 2s.co m result.addAll(currentWorld); result.addAll(currentWindow); result.addAll(closeWindows); result.addAll(mainInventoryChanges.values()); if (mainInventory != null) { result.add(mainInventory); } if (joinGame != null) { ServerJoinGamePacket org = (ServerJoinGamePacket) joinGame.getPacket(); Packet packet = new ServerJoinGamePacket(org.getEntityId(), org.getHardcore(), gameMode, dimension, difficulty, org.getMaxPlayers(), worldType, reducedDebugInfo); result.add(new PacketData(joinGame.getTime(), packet)); } else if (respawn != null) { Packet packet = new ServerRespawnPacket(dimension, difficulty, gameMode, worldType); result.add(new PacketData(respawn.getTime(), packet)); } else { if (difficulty != null) { result.add(new PacketData(lastTimestamp, new ServerDifficultyPacket(difficulty))); } if (gameMode != null) { Packet packet = new ServerNotifyClientPacket(ClientNotification.CHANGE_GAMEMODE, gameMode); result.add(new PacketData(lastTimestamp, packet)); } } if (experience != null) { result.add(new PacketData(lastTimestamp, experience)); } if (abilities != null) { result.add(new PacketData(lastTimestamp, abilities)); } for (Map.Entry<Integer, Entity> e : entities.entrySet()) { Entity entity = e.getValue(); FOR_PACKETS: for (PacketData data : entity.packets) { Packet packet = data.getPacket(); Integer id = PacketUtils.getEntityId(packet); if (id == -1) { // Multiple entities List<Integer> allIds = PacketUtils.getEntityIds(packet); for (int i : allIds) { if (!entities.containsKey(i)) { // Other entity doesn't exist continue FOR_PACKETS; } } } result.add(data); } if (entity.loc != null) { result.add(new PacketData(entity.lastTimestamp, entity.loc.toServerEntityTeleportPacket(e.getKey(), entity.onGround))); } while (entity.dx != 0 && entity.dy != 0 && entity.dz != 0) { long mx = within(entity.dx, POS_MIN, POS_MAX); long my = within(entity.dy, POS_MIN, POS_MAX); long mz = within(entity.dz, POS_MIN, POS_MAX); entity.dx -= mx; entity.dy -= my; entity.dz -= mz; ServerEntityPositionPacket p = new ServerEntityPositionPacket(e.getKey(), mx / 32d, my / 32d, mz / 32d, entity.onGround); result.add(new PacketData(entity.lastTimestamp, p)); } if (entity.yaw != null && entity.pitch != null) { ServerEntityRotationPacket p = new ServerEntityRotationPacket(e.getKey(), entity.yaw, entity.pitch, entity.onGround); result.add(new PacketData(entity.lastTimestamp, p)); } } for (Map.Entry<Long, Long> e : unloadedChunks.entrySet()) { int x = ChunkData.longToX(e.getKey()); int z = ChunkData.longToZ(e.getKey()); result.add(new PacketData(e.getValue(), new ServerChunkDataPacket(x, z))); } for (ChunkData chunk : chunks.values()) { Packet packet = new ServerChunkDataPacket(chunk.x, chunk.z, chunk.changes, chunk.biomeData); result.add(new PacketData(chunk.firstAppearance, packet)); for (Map<Short, MutablePair<Long, BlockChangeRecord>> e : chunk.blockChanges) { if (e != null) { for (MutablePair<Long, BlockChangeRecord> pair : e.values()) { result.add(new PacketData(pair.getLeft(), new ServerBlockChangePacket(pair.getRight()))); } } } } Collections.sort(result, (e1, e2) -> Long.compare(e1.getTime(), e2.getTime())); for (PacketData data : result) { add(stream, timestamp, data.getPacket()); } for (Team team : teams.values()) { String[] added = team.added.toArray(new String[team.added.size()]); String[] removed = team.added.toArray(new String[team.removed.size()]); if (team.status == Team.Status.CREATED) { add(stream, timestamp, new ServerTeamPacket(team.name, team.displayName, team.prefix, team.suffix, team.friendlyFire, team.seeingFriendlyInvisibles, team.nameTagVisibility, team.color, added)); } else if (team.status == Team.Status.UPDATED) { if (team.color != null) { add(stream, timestamp, new ServerTeamPacket(team.name, team.displayName, team.prefix, team.suffix, team.friendlyFire, team.seeingFriendlyInvisibles, team.nameTagVisibility, team.color)); } if (added.length > 0) { add(stream, timestamp, new ServerTeamPacket(team.name, TeamAction.ADD_PLAYER, added)); } if (removed.length > 0) { add(stream, timestamp, new ServerTeamPacket(team.name, TeamAction.REMOVE_PLAYER, removed)); } } else if (team.status == Team.Status.REMOVED) { add(stream, timestamp, new ServerTeamPacket(team.name)); } } for (ServerMapDataPacket packet : maps.values()) { add(stream, timestamp, packet); } }
From source file:bwem.Graph.java
private java.util.Map<MutablePair<AreaId, AreaId>, List<WalkPosition>> createRawFrontierByAreaPairMap( final List<MutablePair<MutablePair<AreaId, AreaId>, WalkPosition>> rawFrontier) { final java.util.Map<MutablePair<AreaId, AreaId>, List<WalkPosition>> rawFrontierByAreaPair = new HashMap<>(); for (final MutablePair<MutablePair<AreaId, AreaId>, WalkPosition> raw : rawFrontier) { int a = raw.getLeft().getLeft().intValue(); int b = raw.getLeft().getRight().intValue(); if (a > b) { final int a_tmp = a; a = b;/* ww w. ja v a 2 s .com*/ b = a_tmp; } // bwem_assert(a <= b); if (!(a <= b)) { throw new IllegalStateException(); } // bwem_assert((a >= 1) && (b <= areasCount())); if (!((a >= 1) && (b <= getAreaCount()))) { throw new IllegalStateException(); } final MutablePair<AreaId, AreaId> key = new MutablePair<>(new AreaId(a), new AreaId(b)); rawFrontierByAreaPair.computeIfAbsent(key, mp -> new ArrayList<>()).add(raw.getRight()); } return rawFrontierByAreaPair; }
From source file:bwem.map.MapImpl.java
public MutablePair<AreaId, AreaId> findNeighboringAreas(final WalkPosition p) { final MutablePair<AreaId, AreaId> result = new MutablePair<>(null, null); final WalkPosition[] deltas = { new WalkPosition(0, -1), new WalkPosition(-1, 0), new WalkPosition(+1, 0), new WalkPosition(0, +1) }; for (final WalkPosition delta : deltas) { if (getData().getMapData().isValid(p.add(delta))) { final AreaId areaId = getData().getMiniTile(p.add(delta), CheckMode.NO_CHECK).getAreaId(); if (areaId.intValue() > 0) { if (result.getLeft() == null) { result.setLeft(areaId); } else if (!result.getLeft().equals(areaId)) { if (result.getRight() == null || ((areaId.intValue() < result.getRight().intValue()))) { result.setRight(areaId); }//from www.ja va 2 s.c o m } } } } return result; }
From source file:bwem.Graph.java
public void createChokePoints(final List<StaticBuilding> staticBuildings, final List<Mineral> minerals, final List<MutablePair<MutablePair<AreaId, AreaId>, WalkPosition>> rawFrontier) { Index newIndex = new Index(0); final List<Neutral> blockingNeutrals = new ArrayList<>(); for (final StaticBuilding s : staticBuildings) { if (s.isBlocking()) { blockingNeutrals.add(s);/*from ww w . j a v a2s.c o m*/ } } for (final Mineral m : minerals) { if (m.isBlocking()) { blockingNeutrals.add(m); } } //Note: pseudoChokePointsToCreate is only used for pre-allocating the GetChokePoints array size. // This number will highly likely be very small. There is no reason to set a minimum size. // int pseudoChokePointsToCreate = 0; // for (final Neutral blockingNeutral : blockingNeutrals) { // if (blockingNeutral.getNextStacked() == null) { // ++pseudoChokePointsToCreate; // } // } // 1) size the matrix initializeChokePointsMatrix(this.chokePointsMatrix, getAreaCount()); // 2) Dispatch the global raw frontier between all the relevant pairs of areas: final java.util.Map<MutablePair<AreaId, AreaId>, List<WalkPosition>> rawFrontierByAreaPair = createRawFrontierByAreaPairMap( rawFrontier); // 3) For each pair of areas (A, B): for (final java.util.Map.Entry<MutablePair<AreaId, AreaId>, List<WalkPosition>> entry : rawFrontierByAreaPair .entrySet()) { MutablePair<AreaId, AreaId> rawleft = entry.getKey(); final List<WalkPosition> rawFrontierAB = entry.getValue(); // Because our dispatching preserved order, // and because Map::m_RawFrontier was populated in descending order of the altitude (see Map::computeAreas), // we know that rawFrontierAB is also ordered the same way, but let's check it: { final List<Altitude> altitudes = new ArrayList<>(); for (final WalkPosition w : rawFrontierAB) { altitudes.add(getMap().getData().getMiniTile(w).getAltitude()); } // Check if the altitudes array is sorted in descending order. // bwem_assert(is_sorted(altitudes.rbegin(), altitudes.rend())); for (int i = 1; i < altitudes.size(); ++i) { final int prev = altitudes.get(i - 1).intValue(); final int curr = altitudes.get(i).intValue(); if (prev < curr) { throw new IllegalStateException(); } } } // 3.1) Use that information to efficiently cluster rawFrontierAB in one or several chokepoints. // Each cluster will be populated starting with the center of a chokepoint (max altitude) // and finishing with the ends (min altitude). final int clusterMinDist = (int) Math.sqrt(BwemExt.lake_max_miniTiles); final List<List<WalkPosition>> clusters = new ArrayList<>(); for (final WalkPosition w : rawFrontierAB) { boolean added = false; for (final List<WalkPosition> cluster : clusters) { final int distToFront = BwemExt.queenWiseDist(cluster.get(0), w); final int distToBack = BwemExt.queenWiseDist(cluster.get(cluster.size() - 1), w); if (Math.min(distToFront, distToBack) <= clusterMinDist) { if (distToFront < distToBack) { cluster.add(0, w); } else { cluster.add(w); } added = true; break; } } if (!added) { final List<WalkPosition> list = new ArrayList<>(); list.add(w); clusters.add(list); } } // 3.2) Create one Chokepoint for each cluster: final AreaId a = rawleft.getLeft(); final AreaId b = rawleft.getRight(); // getChokePoints(a, b).reserve(clusters.size() + pseudoChokePointsToCreate); for (final List<WalkPosition> cluster : clusters) { getChokePoints(a, b).add(new ChokePointImpl(this, newIndex, getArea(a), getArea(b), cluster)); newIndex = newIndex.add(1); } } // 4) Create one Chokepoint for each pair of blocked areas, for each blocking Neutral: for (final Neutral blockingNeutral : blockingNeutrals) { if (blockingNeutral.getNextStacked() == null) { // in the case where several neutrals are stacked, we only consider the top final List<Area> blockedAreas = blockingNeutral.getBlockedAreas(); for (final Area blockedAreaA : blockedAreas) for (final Area blockedAreaB : blockedAreas) { if (blockedAreaB.equals(blockedAreaA)) { break; // breaks symmetry } final WalkPosition center = getMap().breadthFirstSearch( blockingNeutral.getCenter().toWalkPosition(), // findCond args -> { Object ttile = args[0]; if (!(ttile instanceof MiniTile)) { throw new IllegalArgumentException(); } MiniTile miniTile = (MiniTile) ttile; return miniTile.isWalkable(); }, // visitCond args -> true); final List<WalkPosition> list = new ArrayList<>(); list.add(center); getChokePoints(blockedAreaA, blockedAreaB).add(new ChokePointImpl(this, newIndex, blockedAreaA, blockedAreaB, list, blockingNeutral)); newIndex = newIndex.add(1); } } } // 5) Set the references to the freshly created Chokepoints: for (int loopA = 1; loopA <= getAreaCount(); ++loopA) for (int loopB = 1; loopB < loopA; ++loopB) { final AreaId a = new AreaId(loopA); final AreaId b = new AreaId(loopB); if (!getChokePoints(a, b).isEmpty()) { ((AreaInitializer) getArea(a)).addChokePoints(getArea(b), getChokePoints(a, b)); ((AreaInitializer) getArea(b)).addChokePoints(getArea(a), getChokePoints(a, b)); this.chokePoints.addAll(getChokePoints(a, b)); } } }