Search in sources :

Example 56 with Stream

use of java.util.stream.Stream in project android by JetBrains.

the class NlUsageTrackerManager method logRenderResult.

@Override
public void logRenderResult(@Nullable NlModel.ChangeType trigger, @NotNull RenderResult result, long totalRenderTimeMs) {
    // Renders are a quite common event so we sample them
    if (!shouldLog(LOG_RENDER_PERCENT)) {
        return;
    }
    logStudioEvent(LayoutEditorEvent.LayoutEditorEventType.RENDER, (event) -> {
        LayoutEditorRenderResult.Builder builder = LayoutEditorRenderResult.newBuilder().setResultCode(result.getRenderResult().getStatus().ordinal()).setTotalRenderTimeMs(totalRenderTimeMs);
        if (trigger != null) {
            switch(trigger) {
                case RESOURCE_EDIT:
                case RESOURCE_CHANGED:
                    builder.setTrigger(LayoutEditorRenderResult.Trigger.RESOURCE_CHANGE);
                    break;
                case EDIT:
                case ADD_COMPONENTS:
                case DELETE:
                case DND_COMMIT:
                case DND_END:
                case DROP:
                case RESIZE_END:
                case RESIZE_COMMIT:
                    builder.setTrigger(LayoutEditorRenderResult.Trigger.EDIT);
                    break;
                case REQUEST_RENDER:
                    builder.setTrigger(LayoutEditorRenderResult.Trigger.USER);
                    break;
                case BUILD:
                    builder.setTrigger(LayoutEditorRenderResult.Trigger.BUILD);
                    break;
                case CONFIGURATION_CHANGE:
                case UPDATE_HIERARCHY:
                    break;
            }
        }
        builder.setComponentCount((int) result.getRootViews().stream().flatMap(s -> Stream.concat(s.getChildren().stream(), Stream.of(s))).count());
        RenderErrorModel errorModel = RenderErrorModelFactory.createErrorModel(result, null);
        builder.setTotalIssueCount(errorModel.getSize());
        if (errorModel.getSize() > 0) {
            int errorCount = 0;
            int fidelityWarningCount = 0;
            for (RenderErrorModel.Issue issue : errorModel.getIssues()) {
                if (HighlightSeverity.ERROR.equals(issue.getSeverity())) {
                    errorCount++;
                } else if (issue.getSummary().startsWith("Layout fid")) {
                    fidelityWarningCount++;
                }
            }
            builder.setErrorCount(errorCount).setFidelityWarningCount(fidelityWarningCount);
        }
        event.setRenderResult(builder.build());
    });
}
Also used : RenderResult(com.android.tools.idea.rendering.RenderResult) UIUtil(com.intellij.util.ui.UIUtil) RenderErrorModelFactory(com.android.tools.idea.rendering.RenderErrorModelFactory) DesignSurface(com.android.tools.idea.uibuilder.surface.DesignSurface) java.util.concurrent(java.util.concurrent) HighlightSeverity(com.intellij.lang.annotation.HighlightSeverity) com.google.wireless.android.sdk.stats(com.google.wireless.android.sdk.stats) Random(java.util.Random) NlModel(com.android.tools.idea.uibuilder.model.NlModel) UsageTracker(com.android.tools.analytics.UsageTracker) SystemInfo(com.intellij.openapi.util.SystemInfo) State(com.android.sdklib.devices.State) Consumer(java.util.function.Consumer) VisibleForTesting(com.android.annotations.VisibleForTesting) Nullable(org.jetbrains.annotations.Nullable) Stream(java.util.stream.Stream) CacheBuilder(com.google.common.cache.CacheBuilder) Cache(com.google.common.cache.Cache) NotNull(org.jetbrains.annotations.NotNull) WeakReference(java.lang.ref.WeakReference) Configuration(com.android.tools.idea.configurations.Configuration) RenderErrorModel(com.android.tools.idea.rendering.errors.ui.RenderErrorModel) RenderErrorModel(com.android.tools.idea.rendering.errors.ui.RenderErrorModel)

Example 57 with Stream

use of java.util.stream.Stream in project RecurrentComplex by Ivorforce.

the class TransformerNaturalAir method transform.

@Override
public void transform(InstanceData instanceData, Phase phase, StructureSpawnContext context, IvWorldData worldData, RunTransformer transformer) {
    super.transform(instanceData, phase, context, worldData, transformer);
    if (phase == Phase.AFTER) {
        WorldServer world = context.environment.world;
        IvBlockCollection blockCollection = worldData.blockCollection;
        int[] areaSize = new int[] { blockCollection.width, blockCollection.height, blockCollection.length };
        BlockPos lowerCoord = StructureBoundingBoxes.min(context.boundingBox);
        // Remove dying foliage
        HashSet<BlockPos> check = instanceData.cloud.keySet().stream().flatMap(pos -> new BlockArea(pos.subtract(new Vec3i(2, 2, 2)), pos.add(new Vec3i(2, 2, 2))).stream()).filter(pos -> !instanceData.cloud.containsKey(pos)).map(pos -> context.transform.apply(pos, areaSize).add(lowerCoord)).collect(Collectors.toCollection(HashSet::new));
        Set<BlockPos> remove = new HashSet<>();
        HashSet<BlockPos> start = new HashSet<>();
        // Do each one separately, since each block needs to be connected to floor separately
        check.forEach(checking -> {
            start.add(checking);
            if (visitRecursively(start, (changed, pos) -> {
                IBlockState state = world.getBlockState(pos);
                boolean isFoliage = RCBlockLogic.isFoliage(state, world, pos);
                if (!RCBlockLogic.canStay(state, world, pos))
                    context.setBlock(pos, Blocks.AIR.getDefaultState(), 2);
                else if (!isFoliage && !state.getBlock().isReplaceable(world, pos))
                    return false;
                else if (isFoliage && remove.size() < MAX_TREE_SIZE && remove.add(pos))
                    neighbors(pos).forEach(changed::add);
                return true;
            })) {
                remove.forEach(pos -> context.setBlock(pos, Blocks.AIR.getDefaultState(), 2));
            }
            start.clear();
            remove.clear();
        });
    }
}
Also used : IvBlockCollection(ivorius.ivtoolkit.blocks.IvBlockCollection) BlockExpression(ivorius.reccomplex.utils.expression.BlockExpression) Blocks(net.minecraft.init.Blocks) StructureSpawnContext(ivorius.reccomplex.world.gen.feature.structure.context.StructureSpawnContext) BlockAreas(ivorius.ivtoolkit.blocks.BlockAreas) TableDataSource(ivorius.reccomplex.gui.table.datasource.TableDataSource) TableDataSourceBTNaturalAir(ivorius.reccomplex.gui.editstructure.transformers.TableDataSourceBTNaturalAir) Environment(ivorius.reccomplex.world.gen.feature.structure.Environment) StructureBoundingBoxes(ivorius.ivtoolkit.world.chunk.gen.StructureBoundingBoxes) HashSet(java.util.HashSet) BlockArea(ivorius.ivtoolkit.blocks.BlockArea) Vec3i(net.minecraft.util.math.Vec3i) RecurrentComplex(ivorius.reccomplex.RecurrentComplex) PositionedBlockExpression(ivorius.reccomplex.utils.expression.PositionedBlockExpression) WorldServer(net.minecraft.world.WorldServer) JsonUtils(ivorius.reccomplex.json.JsonUtils) Nullable(javax.annotation.Nullable) IvWorldData(ivorius.ivtoolkit.tools.IvWorldData) ExpressionCache(ivorius.reccomplex.utils.algebra.ExpressionCache) StructureLoadContext(ivorius.reccomplex.world.gen.feature.structure.context.StructureLoadContext) StructurePrepareContext(ivorius.reccomplex.world.gen.feature.structure.context.StructurePrepareContext) NBTBase(net.minecraft.nbt.NBTBase) Set(java.util.Set) BlockPos(net.minecraft.util.math.BlockPos) RCBlocks(ivorius.reccomplex.block.RCBlocks) Collectors(java.util.stream.Collectors) MCRegistry(ivorius.ivtoolkit.tools.MCRegistry) TableNavigator(ivorius.reccomplex.gui.table.TableNavigator) IBlockState(net.minecraft.block.state.IBlockState) Stream(java.util.stream.Stream) RCBlockLogic(ivorius.reccomplex.utils.RCBlockLogic) Type(java.lang.reflect.Type) TableDelegate(ivorius.reccomplex.gui.table.TableDelegate) com.google.gson(com.google.gson) BlockArea(ivorius.ivtoolkit.blocks.BlockArea) Vec3i(net.minecraft.util.math.Vec3i) IBlockState(net.minecraft.block.state.IBlockState) WorldServer(net.minecraft.world.WorldServer) BlockPos(net.minecraft.util.math.BlockPos) IvBlockCollection(ivorius.ivtoolkit.blocks.IvBlockCollection) HashSet(java.util.HashSet)

Example 58 with Stream

use of java.util.stream.Stream in project RecurrentComplex by Ivorforce.

the class CommandRetrogen method existingRegions.

public static Stream<Pair<Integer, Integer>> existingRegions(File worldDir) {
    File regionsDirectory = RCFiles.getValidatedFolder(new File(worldDir, "region"), false);
    if (regionsDirectory == null)
        return Stream.empty();
    String[] mcas = regionsDirectory.list(new FileSuffixFilter("mca"));
    if (mcas == null)
        throw new IllegalStateException();
    return Arrays.stream(mcas).map(s -> s.split("\\.")).filter(// Is region file
    p -> p.length == 4 && p[0].equals("r")).map(p -> Pair.of(Integer.parseInt(p[1]), Integer.parseInt(p[2]))).filter(// Has coords
    rfc -> rfc.getLeft() != null && rfc.getRight() != null);
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) Structure(ivorius.reccomplex.world.gen.feature.structure.Structure) ServerTranslations(ivorius.reccomplex.utils.ServerTranslations) Random(java.util.Random) IvStreams(ivorius.ivtoolkit.util.IvStreams) RCConfig(ivorius.reccomplex.RCConfig) RCExpect(ivorius.reccomplex.commands.parameters.RCExpect) CommandException(net.minecraft.command.CommandException) MinecraftServer(net.minecraft.server.MinecraftServer) Pair(org.apache.commons.lang3.tuple.Pair) RCFiles(ivorius.reccomplex.files.RCFiles) WorldServer(net.minecraft.world.WorldServer) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) RegionFileCache(net.minecraft.world.chunk.storage.RegionFileCache) World(net.minecraft.world.World) Predicate(java.util.function.Predicate) ChunkPos(net.minecraft.util.math.ChunkPos) CommandBase(net.minecraft.command.CommandBase) BlockPos(net.minecraft.util.math.BlockPos) File(java.io.File) FileSuffixFilter(ivorius.reccomplex.files.loading.FileSuffixFilter) List(java.util.List) Stream(java.util.stream.Stream) ICommandSender(net.minecraft.command.ICommandSender) WorldGenStructures(ivorius.reccomplex.world.gen.feature.WorldGenStructures) RCParameters(ivorius.reccomplex.commands.parameters.RCParameters) FileSuffixFilter(ivorius.reccomplex.files.loading.FileSuffixFilter) File(java.io.File)

Example 59 with Stream

use of java.util.stream.Stream in project jabref by JabRef.

the class CiteKeyBasedFileFinder method findFilesByExtension.

/**
     * Returns a list of all files in the given directories which have one of the given extension.
     */
public Set<Path> findFilesByExtension(List<Path> directories, List<String> extensions) {
    Objects.requireNonNull(extensions, "Extensions must not be null!");
    BiPredicate<Path, BasicFileAttributes> isFileWithCorrectExtension = (path, attributes) -> !Files.isDirectory(path) && extensions.contains(FileHelper.getFileExtension(path).orElse(""));
    Set<Path> result = new HashSet<>();
    for (Path directory : directories) {
        try (Stream<Path> files = Files.find(directory, Integer.MAX_VALUE, isFileWithCorrectExtension)) {
            result.addAll(files.collect(Collectors.toSet()));
        } catch (IOException e) {
            LOGGER.error("Problem in finding files", e);
        }
    }
    return result;
}
Also used : Files(java.nio.file.Files) BibEntry(org.jabref.model.entry.BibEntry) Set(java.util.Set) IOException(java.io.IOException) HashMap(java.util.HashMap) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) FileHelper(org.jabref.model.util.FileHelper) HashSet(java.util.HashSet) Objects(java.util.Objects) BiPredicate(java.util.function.BiPredicate) List(java.util.List) Stream(java.util.stream.Stream) Map(java.util.Map) Optional(java.util.Optional) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) Path(java.nio.file.Path) Path(java.nio.file.Path) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) HashSet(java.util.HashSet)

Example 60 with Stream

use of java.util.stream.Stream in project bitsquare by bitsquare.

the class TransactionsView method showStatisticsPopup.

private void showStatisticsPopup() {
    Map<Long, List<Coin>> map = new HashMap<>();
    Map<String, Tuple4<Date, Integer, Integer, Integer>> dataByDayMap = new HashMap<>();
    observableList.stream().forEach(item -> {
        Coin amountAsCoin = item.getAmountAsCoin();
        List<Coin> amounts;
        long key = amountAsCoin.getValue();
        if (!map.containsKey(key)) {
            amounts = new ArrayList<>();
            map.put(key, amounts);
        } else {
            amounts = map.get(key);
        }
        amounts.add(amountAsCoin);
        DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.US);
        String day = dateFormatter.format(item.getDate());
        if (!dataByDayMap.containsKey(day)) {
            int numOffers = 0;
            int numTrades = 0;
            if (amountAsCoin.compareTo(FeePolicy.getCreateOfferFee().subtract(FeePolicy.getFixedTxFeeForTrades())) == 0)
                numOffers++;
            else if (amountAsCoin.compareTo(FeePolicy.getTakeOfferFee().subtract(FeePolicy.getFixedTxFeeForTrades())) == 0)
                numTrades++;
            dataByDayMap.put(day, new Tuple4<>(item.getDate(), 1, numOffers, numTrades));
        } else {
            Tuple4<Date, Integer, Integer, Integer> tuple = dataByDayMap.get(day);
            int prev = tuple.second;
            int numOffers = tuple.third;
            int numTrades = tuple.forth;
            if (amountAsCoin.compareTo(FeePolicy.getCreateOfferFee().subtract(FeePolicy.getFixedTxFeeForTrades())) == 0)
                numOffers++;
            else if (amountAsCoin.compareTo(FeePolicy.getTakeOfferFee().subtract(FeePolicy.getFixedTxFeeForTrades())) == 0)
                numTrades++;
            dataByDayMap.put(day, new Tuple4<>(tuple.first, ++prev, numOffers, numTrades));
        }
    });
    StringBuilder stringBuilder = new StringBuilder();
    map.entrySet().stream().forEach(e -> {
        stringBuilder.append("No. of transactions for amount ").append(formatter.formatCoinWithCode(Coin.valueOf(e.getKey()))).append(": ").append(e.getValue().size()).append("\n");
    });
    List<Tuple4<String, Date, Integer, Tuple2<Integer, Integer>>> sortedDataByDayList = dataByDayMap.entrySet().stream().map(e -> {
        Tuple4<Date, Integer, Integer, Integer> data = e.getValue();
        return new Tuple4<>(e.getKey(), data.first, data.second, new Tuple2<>(data.third, data.forth));
    }).collect(Collectors.toList());
    sortedDataByDayList.sort((o1, o2) -> o2.second.compareTo(o1.second));
    StringBuilder transactionsByDayStringBuilder = new StringBuilder();
    StringBuilder offersStringBuilder = new StringBuilder();
    StringBuilder tradesStringBuilder = new StringBuilder();
    StringBuilder allStringBuilder = new StringBuilder();
    allStringBuilder.append("Date").append(";").append("Offers").append(";").append("Trades").append("\n");
    sortedDataByDayList.stream().forEach(tuple4 -> {
        offersStringBuilder.append(tuple4.forth.first).append(",");
        tradesStringBuilder.append(tuple4.forth.second).append(",");
        allStringBuilder.append(tuple4.first).append(";").append(tuple4.forth.first).append(";").append(tuple4.forth.second).append("\n");
        transactionsByDayStringBuilder.append("\n").append(tuple4.first).append(": ").append(tuple4.third).append(" (Offers: ").append(tuple4.forth.first).append(" / Trades: ").append(tuple4.forth.second).append(")");
    });
    String message = stringBuilder.toString() + "\nNo. of transactions by day:" + transactionsByDayStringBuilder.toString();
    new Popup().headLine("Statistical info").information(message).actionButtonText("Copy").onAction(() -> Utilities.copyToClipboard(message + "\n\nCSV (Offers):\n" + offersStringBuilder.toString() + "\n\nCSV (Trades):\n" + tradesStringBuilder.toString() + "\n\nCSV (all):\n" + allStringBuilder.toString())).show();
}
Also used : EventHandler(javafx.event.EventHandler) OpenOffer(io.bitsquare.trade.offer.OpenOffer) Scene(javafx.scene.Scene) Popup(io.bitsquare.gui.main.overlays.popups.Popup) java.util(java.util) javafx.scene.control(javafx.scene.control) AddressWithIconAndDirection(io.bitsquare.gui.components.AddressWithIconAndDirection) FXCollections(javafx.collections.FXCollections) DisputeManager(io.bitsquare.arbitration.DisputeManager) Trade(io.bitsquare.trade.Trade) CSVEntryConverter(com.googlecode.jcsv.writer.CSVEntryConverter) Tuple2(io.bitsquare.common.util.Tuple2) ActivatableView(io.bitsquare.gui.common.view.ActivatableView) VBox(javafx.scene.layout.VBox) Tradable(io.bitsquare.trade.Tradable) GUIUtil(io.bitsquare.gui.util.GUIUtil) KeyCombination(javafx.scene.input.KeyCombination) Inject(javax.inject.Inject) TradeManager(io.bitsquare.trade.TradeManager) FailedTradesManager(io.bitsquare.trade.failed.FailedTradesManager) ReadOnlyObjectWrapper(javafx.beans.property.ReadOnlyObjectWrapper) WalletService(io.bitsquare.btc.WalletService) TradeDetailsWindow(io.bitsquare.gui.main.overlays.windows.TradeDetailsWindow) FeePolicy(io.bitsquare.btc.FeePolicy) Callback(javafx.util.Callback) Nullable(javax.annotation.Nullable) DateFormat(java.text.DateFormat) BSFormatter(io.bitsquare.gui.util.BSFormatter) SortedList(javafx.collections.transformation.SortedList) KeyCode(javafx.scene.input.KeyCode) Utilities(io.bitsquare.common.util.Utilities) OfferDetailsWindow(io.bitsquare.gui.main.overlays.windows.OfferDetailsWindow) ClosedTradableManager(io.bitsquare.trade.closed.ClosedTradableManager) KeyEvent(javafx.scene.input.KeyEvent) Collectors(java.util.stream.Collectors) org.bitcoinj.core(org.bitcoinj.core) FXML(javafx.fxml.FXML) KeyCodeCombination(javafx.scene.input.KeyCodeCombination) Preferences(io.bitsquare.user.Preferences) HyperlinkWithIcon(io.bitsquare.gui.components.HyperlinkWithIcon) Script(org.bitcoinj.script.Script) Stream(java.util.stream.Stream) Stage(javafx.stage.Stage) Tuple4(io.bitsquare.common.util.Tuple4) OpenOfferManager(io.bitsquare.trade.offer.OpenOfferManager) ObservableList(javafx.collections.ObservableList) AwesomeIcon(de.jensd.fx.fontawesome.AwesomeIcon) FxmlView(io.bitsquare.gui.common.view.FxmlView) Tuple4(io.bitsquare.common.util.Tuple4) Tuple2(io.bitsquare.common.util.Tuple2) DateFormat(java.text.DateFormat) Popup(io.bitsquare.gui.main.overlays.popups.Popup) SortedList(javafx.collections.transformation.SortedList) ObservableList(javafx.collections.ObservableList)

Aggregations

Stream (java.util.stream.Stream)161 Collectors (java.util.stream.Collectors)98 List (java.util.List)89 ArrayList (java.util.ArrayList)66 Map (java.util.Map)66 Set (java.util.Set)59 IOException (java.io.IOException)58 Optional (java.util.Optional)45 Collections (java.util.Collections)43 HashMap (java.util.HashMap)43 Arrays (java.util.Arrays)33 HashSet (java.util.HashSet)33 File (java.io.File)32 Path (java.nio.file.Path)32 Function (java.util.function.Function)28 Logger (org.slf4j.Logger)26 LoggerFactory (org.slf4j.LoggerFactory)26 java.util (java.util)25 Predicate (java.util.function.Predicate)23 Objects (java.util.Objects)22