text:
package org.spongepowered.common.command.sponge;

import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.JoinConfiguration;
import net.kyori.adventure.text.LinearComponents;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.Style;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.format.TextDecoration;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.ResourceKey;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.adventure.SpongeComponents;
import org.spongepowered.api.command.Command;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.manager.CommandMapping;
import org.spongepowered.api.command.parameter.CommandContext;
import org.spongepowered.api.command.parameter.CommonParameters;
import org.spongepowered.api.command.parameter.Parameter;
import org.spongepowered.api.data.Keys;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.lifecycle.RefreshGameEvent;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.util.blockray.RayTrace;
import org.spongepowered.api.world.LocatableBlock;
import org.spongepowered.api.world.server.ServerLocation;
import org.spongepowered.api.world.server.ServerWorld;
import org.spongepowered.common.SpongeCommon;
import org.spongepowered.common.applaunch.config.core.SpongeConfigs;
import org.spongepowered.common.bridge.server.level.ServerLevelBridge;
import org.spongepowered.common.bridge.world.level.LevelBridge;
import org.spongepowered.common.config.SpongeGameConfigs;
import org.spongepowered.common.event.manager.SpongeEventManager;
import org.spongepowered.common.event.tracking.PhaseTracker;
import org.spongepowered.common.launch.Launch;
import org.spongepowered.plugin.PluginContainer;
import org.spongepowered.plugin.metadata.PluginMetadata;
import org.spongepowered.plugin.metadata.model.PluginContributor;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import javax.management.MBeanServer;

public class SpongeCommand {

    protected static final String INDENT = "    ";
    protected static final String LONG_INDENT = SpongeCommand.INDENT + SpongeCommand.INDENT;
    protected static final Component INDENT_COMPONENT = Component.text(SpongeCommand.INDENT);
    protected static final Component LONG_INDENT_COMPONENT = Component.text(SpongeCommand.LONG_INDENT);
    protected static final DecimalFormat THREE_DECIMAL_DIGITS_FORMATTER = new DecimalFormat("########0.000");

    protected static final TextColor GREEN = TextColor.color(0x42C742);
    protected static final TextColor MINT = TextColor.color(0x69A877);
    protected static final TextColor LIGHT_BLUE = TextColor.color(0x5EB3DA);
    protected static final TextColor YELLOW = TextColor.color(0xDEDE00);
    protected static final TextColor ORANGE = TextColor.color(0xE36504);
    protected static final TextColor RED = TextColor.color(0xC74242);

    private static final Component EMPTY = Component.text("Empty", TextColor.color(SpongeCommand.RED));

    private final Parameter.Key<PluginContainer> pluginContainerKey = Parameter.key("plugin", PluginContainer.class);
    private final Parameter.Key<CommandMapping> commandMappingKey = Parameter.key("command", CommandMapping.class);
    private final Parameter.Key<ServerWorld> worldKey = Parameter.key("world", ServerWorld.class);

    private @Nullable Component versionText = null;

    public Command.Parameterized createSpongeCommand() {
        // /sponge audit
        final Command.Parameterized auditCommand = Command.builder()
                .permission("sponge.command.audit")
                .shortDescription(Component.text("Audit mixin classes for implementation"))
                .executor(this::auditSubcommandExecutor)
                .build();

        // /sponge chunks
        final Command.Parameterized chunksCommand = this.chunksSubcommand();

        // /sponge heap
        final Command.Parameterized heapCommand = Command.builder()
                .permission("sponge.command.heap")
                .shortDescription(Component.text("Dump live JVM heap"))
                .executor(this::heapSubcommandExecutor)
                .build();

        // /sponge plugins
        final Command.Parameterized pluginsReloadCommand = Command.builder()
                .permission("sponge.command.plugins.refresh")
                .shortDescription(Component.text("Refreshes supported plugins, typically causing plugin configuration reloads."))
                .addParameter(Parameter.builder(PluginContainer.class)
                        .optional()
                        .addParser(new FilteredPluginContainerParameter())
                        .key(this.pluginContainerKey)
                        .build())
                .executor(this::pluginsRefreshSubcommandExecutor)
                .build();
        final Command.Parameterized pluginsListCommand = Command.builder()
                .permission("sponge.command.plugins.list")
                .shortDescription(Component.text("Lists all currently installed plugins."))
                .executor(this::pluginsListSubcommand)
                .build();
        final Command.Parameterized pluginsInfoCommand = Command.builder()
                .permission("sponge.command.plugins.info")
                .shortDescription(Component.text("Displays information about a specific plugin."))
                .addParameter(Parameter.plugin().key(this.pluginContainerKey).build())
                .executor(this::pluginsInfoSubcommand)
                .build();

        final Command.Parameterized pluginsCommand = Command.builder()
                .addChild(pluginsReloadCommand, "refresh")
                .addChild(pluginsListCommand, "list")
                .addChild(pluginsInfoCommand, "info")
                .build();

        // /sponge tps
        final Command.Parameterized tpsCommand = Command.builder()
                .permission("sponge.command.tps")
                .shortDescription(Component.text("Provides TPS (ticks per second) data for loaded worlds."))
                .executor(this::tpsExecutor)
                .build();

        // /sponge version
        final Command.Parameterized versionCommand = Command.builder()
                .permission("sponge.command.version")
                .shortDescription(Component.text("Display Sponge's current version"))
                .executor(this::versionExecutor)
                .build();

        // /sponge which
        final Command.Parameterized whichCommand = Command.builder()
                .permission("sponge.command.which")
                .addParameter(Parameter.builder(CommandMapping.class).key(this.commandMappingKey).addParser(new CommandAliasesParameter()).build())
                .shortDescription(Component.text("Find the plugin that owns a specific command"))
                .executor(this::whichExecutor)
                .build();

        // /sponge reload global|world [id]
        final Command.Parameterized reloadGlobalCommand = Command.builder()
            .permission("sponge.command.reload.global")
            .shortDescription(Component.text("Reload Sponge's common configuration"))
            .executor(this::reloadGlobalExecutor)
            .build();

        final Command.Parameterized reloadWorldCommand = Command.builder()
            .permission("sponge.command.reload.world")
            .addParameter(Parameter.world().key(this.worldKey).build())
            .shortDescription(Component.text("Reload Sponge's configuration for a single world"))
            .executor(this::reloadWorldExecutor)
            .build();

        final Command.Parameterized reloadCommand = Command.builder()
            .addChild(reloadGlobalCommand, "global")
            .addChild(reloadWorldCommand, "world")
            .build();

        final Command.Parameterized infoCommand = this.infoSubcommand();

        // /sponge
        final Command.Builder commandBuilder = Command.builder()
                .permission("sponge.command.root")
                .executor(this::rootCommand)
                .addChild(auditCommand, "audit")
                .addChild(chunksCommand, "chunks")
                .addChild(heapCommand, "heap")
                .addChild(pluginsCommand, "plugins")
                .addChild(tpsCommand, "tps")
                .addChild(versionCommand, "version")
                .addChild(whichCommand, "which")
                .addChild(reloadCommand, "reload")
                .addChild(infoCommand, "info")
            ;

        this.additionalActions(commandBuilder);
        return commandBuilder.build();
    }

    protected void additionalActions(final Command.Builder builder) {
        // no-op for vanilla, SF might like to add a /sponge mods command, for example.
    }

    private @NonNull CommandResult rootCommand(final CommandContext context) {
        final PluginContainer platformPlugin = Launch.instance().platformPlugin();
        final PluginContainer apiPlugin = Launch.instance().apiPlugin();
        final PluginContainer minecraftPlugin = Launch.instance().minecraftPlugin();

        context.sendMessage(Identity.nil(), Component.text().append(
                Component.text("SpongePowered", NamedTextColor.YELLOW, TextDecoration.BOLD).append(Component.space()),
                Component.text("Plugin Platform (running on Minecraft " + minecraftPlugin.metadata().version() + ")"),
                Component.newline(),
                Component.text(apiPlugin.metadata().name().get() + ": " + apiPlugin.metadata().version()),
                Component.newline(),
                Component.text(platformPlugin.metadata().name().get() + ": " + platformPlugin.metadata().version())
            ).build()
        );

        final Optional<Command.Parameterized> parameterized = context.executedCommand();
        if (parameterized.isPresent()) {
            final String subcommands = parameterized.get()
                    .subcommands()
                    .stream()
                    .filter(x -> x.command().canExecute(context.cause()))
                    .flatMap(x -> x.aliases().stream())
                    .collect(Collectors.joining(", "));
            if (!subcommands.isEmpty()) {
                context.sendMessage(Identity.nil(), Component.text().append(
                        Component.newline(),
                        Component.text("Available subcommands:"),
                        Component.newline(),
                        Component.text(subcommands)).build()
                );
            }
        }

        return CommandResult.success();
    }

    private @NonNull CommandResult auditSubcommandExecutor(final CommandContext context) {
        SpongeCommon.logger().info("Starting Mixin Audit");
        Launch.instance().auditMixins();
        return CommandResult.success();
    }

    private CompletableFuture<Component> userIdToComponent(final @Nullable UUID uuid) {
        if (uuid != null) {
            return Sponge.server().userManager().load(uuid).handleAsync((userOptional, throwable) -> {
                if (throwable != null) {
                    return SpongeCommand.EMPTY;
                }
                return userOptional.map(user ->
                        user.require(Keys.DISPLAY_NAME)
                            .color(TextColor.color(SpongeCommand.LIGHT_BLUE))
                            .hoverEvent(HoverEvent.showText(Component.text(user.uniqueId().toString())))).orElse(SpongeCommand.EMPTY);
            }, SpongeCommon.server());
        }
        return CompletableFuture.completedFuture(SpongeCommand.EMPTY);
    }

    private Command.Parameterized infoSubcommand() {
        final Command.Parameterized blockInfoAtCommand = Command.builder()
            .addParameter(CommonParameters.LOCATION_ONLINE_ONLY)
            .executor(context -> {
                final ServerLocation serverLocation = context.requireOne(CommonParameters.LOCATION_ONLINE_ONLY);
                final CompletableFuture<Component> creator = this.userIdToComponent(serverLocation.get(Keys.CREATOR).orElse(null));
                final CompletableFuture<Component> notifier = this.userIdToComponent(serverLocation.get(Keys.NOTIFIER).orElse(null));
                CompletableFuture.allOf(creator, notifier).thenAcceptAsync(x ->
                        context.sendMessage(Identity.nil(), Component.text()
                            .content("Block Info: ")
                            .color(TextColor.color(SpongeCommand.GREEN))
                            .append(Component.text(serverLocation.blockPosition().toString())
                                    .hoverEvent(ItemStack.builder().fromBlockState(serverLocation.block()).build().createSnapshot())
                            )
                            .append(Component.newline())
                            .append(Component.text("Creator: ", TextColor.color(SpongeCommand.MINT)))
                            .append(creator.join())
                            .append(Component.newline())
                            .append(Component.text("Notifier: ", TextColor.color(SpongeCommand.MINT)))
                            .append(notifier.join())
                            .build()), SpongeCommon.server());
                return CommandResult.success();
            })
            .build();

        final Command.Parameterized blockInfoLookingAt = Command.builder()
            .executor(context -> {
                if (!(context.cause().root() instanceof Player)) {
                    return CommandResult.error(Component.text("Player required", TextColor.color(SpongeCommand.RED)));
                }
                final Player player = (Player) context.cause().root();
                return RayTrace.block()
                    .sourceEyePosition(player)
                    .direction(player)
                    .select(RayTrace.nonAir())
                    .limit(10)
                    .execute()
                    .map(result -> {
                        final LocatableBlock locatableBlock = result.selectedObject();
                        final CompletableFuture<Component> creator = this.userIdToComponent(locatableBlock.world()
                                .get(locatableBlock.blockPosition(), Keys.CREATOR).orElse(null));
                        final CompletableFuture<Component> notifier = this.userIdToComponent(locatableBlock.world()
                                .get(locatableBlock.blockPosition(), Keys.CREATOR).orElse(null));
                        CompletableFuture.allOf(creator, notifier).thenAcceptAsync(x ->
                                context.sendMessage(Identity.nil(), Component.text()
                                    .content("Block Info: ")
                                    .color(TextColor.color(SpongeCommand.GREEN))
                                    .append(Component.text(locatableBlock.blockPosition().toString())
                                            .hoverEvent(ItemStack.builder().fromBlockState(locatableBlock.blockState()).build().createSnapshot())
                                    )
                                    .append(Component.newline())
                                    .append(Component.text("Creator: ", TextColor.color(SpongeCommand.MINT)))
                                    .append(creator.join())
                                    .append(Component.newline())
                                    .append(Component.text("Notifier: ", TextColor.color(SpongeCommand.MINT)))
                                    .append(notifier.join())
                                    .build()), SpongeCommon.server());
                        return CommandResult.success();
                    }).orElseGet(() -> CommandResult.error(Component.text("Failed to find any block in range", NamedTextColor.RED)));
            })
            .build();
        final Command.Parameterized entityLookingAt = Command.builder()
            .executor(context -> {
                if (!(context.cause().root() instanceof Player)) {
                    return CommandResult.error(Component.text("Player required", TextColor.color(SpongeCommand.RED)));
                }
                final Player player = (Player) context.cause().root();
                return RayTrace.entity()
                    .sourceEyePosition(player)
                    .direction(player)
                    .limit(10)
                    .execute()
                    .map(result -> {
                        final org.spongepowered.api.entity.Entity entity = result.selectedObject();
                        final CompletableFuture<Component> creator = this.userIdToComponent(entity.get(Keys.CREATOR).orElse(null));
                        final CompletableFuture<Component> notifier = this.userIdToComponent(entity.get(Keys.NOTIFIER).orElse(null));
                        CompletableFuture.allOf(creator, notifier).thenAcceptAsync(x ->
                                context.sendMessage(Identity.nil(), Component.text()
                                    .content("Entity Info: ")
                                    .color(TextColor.color(SpongeCommand.GREEN))
                                    .append(entity.type().asComponent().hoverEvent(entity))
                                    .append(Component.newline())
                                    .append(Component.text("Creator: ", TextColor.color(SpongeCommand.MINT)))
                                    .append(creator.join())
                                    .append(Component.newline())
                                    .append(Component.text("Notifier: ", TextColor.color(SpongeCommand.MINT)))
                                    .append(notifier.join())
                                    .build()), SpongeCommon.server());
                        return CommandResult.success();
                    }).orElseGet(() -> CommandResult.error(Component.text("Failed to find any block in range", NamedTextColor.RED)));
            })
            .build();
        return Command.builder()
            .addChild(blockInfoAtCommand, "blockAt")
            .addChild(blockInfoLookingAt, "block")
            .addChild(entityLookingAt, "entity")
            .permission("sponge.command.info")
            .build();
    }

    private Command.Parameterized chunksSubcommand() {
        final Command.Parameterized globalCommand = Command.builder()
                .executor(context -> {
                    for (final ServerWorld world : SpongeCommon.game().server().worldManager().worlds()) {
                        context.sendMessage(Identity.nil(), Component.text().content("World: ")
                                        .append(Component.text(world.key().toString(), NamedTextColor.GREEN))
                                        .append(Component.newline())
                                        .append(this.getChunksInfo(world))
                                        .build());
                    }
                    return CommandResult.success();
                })
                .build();
        final Command.Parameterized worldCommand = Command.builder()
                .addParameter(CommonParameters.WORLD)
                .executor(context -> {
                    final ServerWorld world = context.requireOne(CommonParameters.WORLD);
                    context.sendMessage(Identity.nil(), Component.text().content("World: ")
                            .append(Component.text(world.key().toString(), NamedTextColor.GREEN))
                            .append(Component.newline())
                            .append(this.getChunksInfo(world))
                            .build());
                    return CommandResult.success();
                })
                .build();
        final Parameter.Key<Boolean> dumpAllKey = Parameter.key("dumpAll", Boolean.class);
        final Command.Parameterized dumpCommand = Command.builder()
                .addParameter(Parameter.literal(Boolean.class, true, "all").optional().key(dumpAllKey).build())
                .executor(context -> {
                    final File file = new File(new File(new File("."), "chunk-dumps"),
                            "chunk-info-" + DateTimeFormatter.ofPattern("yyyy-MM-dd_HH.mm.ss").format(LocalDateTime.now()) + "-server.txt");
                    context.sendMessage(Identity.nil(), Component.text("Writing chunk info to: " + file.getAbsolutePath()));
                    // ChunkSaveHelper.writeChunks(file, context.hasAny(dumpAllKey));
                    context.sendMessage(Identity.nil(), Component.text("Chunk info complete"));
                    return CommandResult.success();
                })
                .build();
        return Command.builder()
                .addChild(globalCommand, "global")
                .addChild(worldCommand, "world")
                .addChild(dumpCommand, "dump")
                .permission("sponge.command.chunk")
                .build();
    }

    private @NonNull CommandResult heapSubcommandExecutor(final CommandContext context) {
        final File file = new File(new File(new File("."), "dumps"),
                "heap-dump-" + DateTimeFormatter.ofPattern("yyyy-MM-dd_HH.mm.ss").format(LocalDateTime.now()) + "-server.hprof");
        // src.sendMessage(Text.of("Writing JVM heap data to: ", file));
        SpongeCommon.logger().info("Writing JVM heap data to: {}", file.getAbsolutePath());
        try {
            if (file.getParentFile() != null) {
                file.getParentFile().mkdirs();
            }

            final Class<?> clazz = Class.forName("com.sun.management.HotSpotDiagnosticMXBean");
            final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
            final Object hotspotMBean = ManagementFactory.newPlatformMXBeanProxy(server, "com.sun.management:type=HotSpotDiagnostic", clazz);
            final Method m = clazz.getMethod("dumpHeap", String.class, boolean.class);
            m.invoke(hotspotMBean, file.getPath(), true);
        } catch (final Throwable t) {
            SpongeCommon.logger().fatal(MessageFormat.format("Could not write heap to {0}", file));
        }
        // src.sendMessage(Text.of("Heap dump complete"));
        SpongeCommon.logger().info("Heap dump complete");
        return CommandResult.success();
    }

    private @NonNull CommandResult pluginsListSubcommand(final CommandContext context) {
        final Collection<PluginContainer> plugins = Launch.instance().pluginManager().plugins();
        context.sendMessage(Identity.nil(), this.title("Plugins (" + plugins.size() + ")"));
        for (final PluginContainer specificContainer : plugins) {
            final PluginMetadata metadata = specificContainer.metadata();
            final TextComponent.Builder builder = Component.text();
            this.createShortContainerMeta(builder.append(SpongeCommand.INDENT_COMPONENT), metadata);
            builder.clickEvent(SpongeComponents.executeCallback(cause ->
                    cause.sendMessage(Identity.nil(), this.createContainerMeta(metadata))));
            context.sendMessage(Identity.nil(), builder.build());
        }

        return CommandResult.success();
    }

    private @NonNull CommandResult pluginsInfoSubcommand(final CommandContext context) {
        final PluginContainer pluginContainer = context.requireOne(this.pluginContainerKey);
        context.sendMessage(Identity.nil(), this.createContainerMeta(pluginContainer.metadata()));
        return CommandResult.success();
    }

    private @NonNull CommandResult pluginsRefreshSubcommandExecutor(final CommandContext context) {
        final Optional<PluginContainer> pluginContainer = context.one(this.pluginContainerKey);
        final RefreshGameEvent event = SpongeEventFactory.createRefreshGameEvent(
                PhaseTracker.getCauseStackManager().currentCause(),
                SpongeCommon.game()
        );
        if (pluginContainer.isPresent()) {
            // just send the reload event to that
            context.sendMessage(Identity.nil(), Component.text("Sending refresh event to " + pluginContainer.get().metadata().id() + ", please wait..."));
            ((SpongeEventManager) SpongeCommon.game().eventManager()).postToPlugin(event, pluginContainer.get());
        } else {
            context.sendMessage(Identity.nil(), Component.text("Sending refresh event to all plugins, please wait..."));
            SpongeCommon.game().eventManager().post(event);
        }

        context.sendMessage(Identity.nil(), Component.text("Completed plugin refresh."));
        return CommandResult.success();
    }

    private @NonNull CommandResult tpsExecutor(final CommandContext context) {
        if (SpongeCommon.game().isServerAvailable()) {
            final List<Component> tps = new ArrayList<>();
            for (final ServerWorld world : Sponge.server().worldManager().worlds()) {
                final TextComponent.Builder builder =
                  Component.text()
                    .append(Component.text(world.key().asString(), TextColor.color(0xC9C9C9)))
                    .append(Component.text(": "));
                tps.add(this.appendTickTime(((ServerLevelBridge) world).bridge$recentTickTimes(), builder).build());
            }

            tps.add(Component.newline());
            tps.add(this.appendTickTime(SpongeCommon.server().tickTimes, Component.text().content("Overall: ")).build());
            SpongeCommon.game().serviceProvider()
              .paginationService()
              .builder()
              .contents(tps)
              .title(Component.text("Ticks Per Second (TPS)", NamedTextColor.WHITE))
              .padding(Component.text("-", NamedTextColor.WHITE))
              .sendTo(context.cause().audience());
        } else {
            context.sendMessage(Identity.nil(), Component.text("Server is not running."));
        }

        return CommandResult.success();
    }

    private TextComponent.Builder appendTickTime(final long[] tickTimes, final TextComponent.Builder builder) {
        final double averageTickTime = Mth.average(tickTimes) * 1.0E-6D;
        final double tps = Math.min(1000.0 / (averageTickTime), 20);
        builder.append(Component.text(SpongeCommand.THREE_DECIMAL_DIGITS_FORMATTER.format(tps), this.tpsColor(tps)))
          .append(Component.text(" (", NamedTextColor.GRAY)
            .append(Component.text(SpongeCommand.THREE_DECIMAL_DIGITS_FORMATTER.format(averageTickTime), NamedTextColor.GRAY)
              .append(Component.text("ms avg"))
              .append(Component.text(")"))))
        ;
        return builder;
    }

    private TextColor tpsColor(final double tps) {
        if (tps >= 18) {
            return SpongeCommand.GREEN;
        } else if (tps >= 15) {
            return SpongeCommand.YELLOW;
        } else if (tps >= 10) {
            return SpongeCommand.ORANGE;
        } else {
            return SpongeCommand.RED;
        }
    }

    private @NonNull CommandResult versionExecutor(final CommandContext context) {
        if (this.versionText == null) {
            final PluginContainer platformPlugin = Launch.instance().platformPlugin();

            final TextComponent.Builder builder = Component.text()
                    .append(
                            Component.text(platformPlugin.metadata().name().get(), Style.style(NamedTextColor.YELLOW, TextDecoration.BOLD))
                    );

            final Component colon = Component.text(": ", NamedTextColor.GRAY);
            for (final PluginContainer container : Launch.instance().launcherPlugins()) {
                final PluginMetadata metadata = container.metadata();
                builder.append(
                        Component.newline(),
                        SpongeCommand.INDENT_COMPONENT,
                        Component.text(metadata.name().orElseGet(metadata::id), NamedTextColor.GRAY),
                        colon,
                        Component.text(container.metadata().version().toString())
                );
            }

            final String arch = System.getProperty("sun.arch.data.model");
            final String javaArch = arch != null ? arch + "-bit" : "UNKNOWN";

            final String javaVendor = System.getProperty("java.vendor");
            final String javaVersion = System.getProperty("java.version");
            final String osName = System.getProperty("os.name");
            final String osVersion = System.getProperty("os.version");
            final String osArch = System.getProperty("os.arch");

            builder.append(
                    Component.newline(),
                    SpongeCommand.INDENT_COMPONENT,
                    Component.text("JVM", NamedTextColor.GRAY),
                    colon,
                    Component.text(javaVersion + "/" + javaArch + " (" + javaVendor + ")"),
                    Component.newline(),
                    SpongeCommand.INDENT_COMPONENT,
                    Component.text("OS", NamedTextColor.GRAY),
                    colon,
                    Component.text(osName + "/" + osVersion + " (" + osArch + ")")
            );
            this.versionText = builder.build();
        }

        context.sendMessage(Identity.nil(), this.versionText);
        return CommandResult.success();
    }

    private @NonNull CommandResult whichExecutor(final CommandContext context) {
        final CommandMapping mapping = context.requireOne(this.commandMappingKey);
        context.sendMessage(Identity.nil(), Component.text().append(
                this.title("Aliases: "),
                Component.join(JoinConfiguration.separator(Component.text(", ")),
                    mapping.allAliases().stream().map(x -> Component.text(x, NamedTextColor.YELLOW)).collect(Collectors.toList())),
                Component.newline(),
                this.title("Owned by: "),
                this.hl(mapping.plugin().map(x -> x.metadata().name().orElseGet(() -> x.metadata().id())).orElse("unknown")))
                .build());
        return CommandResult.success();
    }

    private @NonNull CommandResult reloadGlobalExecutor(final CommandContext context) {
        SpongeConfigs.getCommon().reload()
            .whenComplete(($, error) -> {
                if (error != null) {
                    context.sendMessage(Identity.nil(), Component.text("Failed to reload global configuration. See the console for details.", NamedTextColor.RED));
                    SpongeCommon.logger().error("Failed to reload global configuration", error);
                } else {
                    context.sendMessage(Identity.nil(), Component.text("Successfully reloaded global configuration!", NamedTextColor.GREEN));
                }
            });
        return CommandResult.success();
    }

    private @NonNull CommandResult reloadWorldExecutor(final CommandContext context) {
        final ServerWorld target = context.requireOne(this.worldKey);
        final ResourceKey worldId = target.key();
        SpongeGameConfigs.getForWorld(target).reload()
            .whenComplete(($, error) -> {
            if (error != null) {
                context.sendMessage(Identity.nil(), Component.text(b ->
                    b.content("Failed to reload configuration for world ")
                        .append(Component.text(worldId.toString(), Style.style(TextDecoration.BOLD)))
                        .append(Component.text(". See the console for details."))
                        .color(NamedTextColor.RED)));
                SpongeCommon.logger().error("Failed to reload configuration of world '{}'", worldId, error);
            } else {
                context.sendMessage(Identity.nil(), Component.text("Successfully reloaded configuration for world ", NamedTextColor.GREEN)
                    .append(Component.text(worldId.toString(), Style.style(TextDecoration.BOLD)))
                    .append(Component.text("!")));
            }
        });
        return CommandResult.success();
    }

    // --

    protected Component getChunksInfo(final ServerWorld serverWorld) {
        if (((LevelBridge) serverWorld).bridge$isFake()) {
            return Component.text().append(Component.newline(), Component.text(serverWorld.key().asString() + " is a fake world")).build();
        }
        final ServerLevel serverLevel = (ServerLevel) serverWorld;
        final int entitiesToRemove = (int) serverWorld.entities().stream().filter(x -> ((Entity) x).removed).count();
        return LinearComponents.linear(
                this.key("Loaded chunks: "), this.value(serverLevel.getChunkSource().chunkMap.size()),
                Component.newline(),
                this.key("Entities: "), this.value(serverWorld.entities().size()),
                Component.newline(),
                this.key("Block Entities: "), this.value(serverWorld.blockEntities().size()),
                Component.newline(),
                this.key("Removed Entities:"), this.value(entitiesToRemove),
                Component.newline(),
                this.key("Removed Block Entities: "), this.value(((LevelBridge) serverLevel).bridge$blockEntitiesToUnload().size())
        );
    }

    protected Component key(final String text) {
        return Component.text(text, NamedTextColor.GOLD);
    }

    protected Component value(final int text) {
        return Component.text(text, NamedTextColor.GRAY);
    }

    private Component title(final String title) {
        return Component.text(title, NamedTextColor.GREEN);
    }

    private Component hl(final String toHighlight) {
        return Component.text(toHighlight, NamedTextColor.DARK_GREEN);
    }

    private void appendPluginMeta(final TextComponent.Builder builder, final String key, final String value) {
        this.appendPluginMeta(builder, key, Component.text(value));
    }

    private void appendPluginMeta(final TextComponent.Builder builder, final String key, final URL value) {
        final String url = value.toString();
        this.appendPluginMeta(builder, key, Component.text().content(url).clickEvent(ClickEvent.openUrl(url))
                .decoration(TextDecoration.UNDERLINED, true).build());
    }

    private void appendPluginMeta(final TextComponent.Builder builder, final String key, final Component value) {
        builder.append(Component.newline())
                .append()
                .append(SpongeCommand.INDENT_COMPONENT, this.title(key + ": "), value);
    }

    private void createShortContainerMeta(final TextComponent.Builder builder, final PluginMetadata pluginMetadata) {
        builder.append(this.title(pluginMetadata.name().orElse(pluginMetadata.id())));
        builder.append(Component.text(" v" + pluginMetadata.version()));
    }

    private Component createContainerMeta(final PluginMetadata pluginMetadata) {
        final TextComponent.Builder builder = Component.text();
        this.createShortContainerMeta(builder, pluginMetadata);

        this.appendPluginMeta(builder, "ID", pluginMetadata.id());
        pluginMetadata.description().ifPresent(x -> this.appendPluginMeta(builder, "Description", x));
        pluginMetadata.links().homepage().ifPresent(x -> this.appendPluginMeta(builder, "Homepage", x));
        pluginMetadata.links().issues().ifPresent(x -> this.appendPluginMeta(builder, "Issues", x));
        pluginMetadata.links().source().ifPresent(x -> this.appendPluginMeta(builder, "Source", x));
        final Collection<PluginContributor> contributors = pluginMetadata.contributors();
        if (!contributors.isEmpty()) {
            builder.append(Component.newline()).append(SpongeCommand.INDENT_COMPONENT).append(this.title("Contributors:"));
            for (final PluginContributor contributor : contributors) {
                builder.append(Component.newline()).append(SpongeCommand.LONG_INDENT_COMPONENT).append(Component.text(contributor.name()));
                contributor.description().ifPresent(x -> builder.append(Component.text(" (" + x + ")")));
            }
        }

        this.appendPluginMeta(builder, "Entrypoint", pluginMetadata.entrypoint());
        return builder.build();
    }

}


text:
var gulp = require('gulp');
var _ = require('lodash');
var requirejsOptimize = require('gulp-requirejs-optimize');
var less = require('gulp-less');
var watch = require('gulp-watch');
var webserver = require('gulp-webserver');
var path = require('path');
var Server = require('karma').Server;
var plumber = require('gulp-plumber');
var notify = require('gulp-notify');
var sourcemaps = require('gulp-sourcemaps');

// Plumb all streams through gulp-plumber for error handling
var _gulpsrc = gulp.src;
gulp.src = function() {
  return _gulpsrc.apply(gulp, arguments)
    .pipe(plumber({
      errorHandler: function(error) {
        notify.onError({
          title: 'Gulp Error',
          message: 'Error: <%= error.message %>',
          sound: 'Bottle'
        })(error);
        this.emit('end');
      }
    }));
};

gulp.task('default', ['build-styles', 'build-js']);

gulp.task('build-js', function () {
  var requireConfig = require(__dirname + '/public/app/config/require-config.js');

  // Minification of KnockoutJS requires us to use the production/pre-compiled version in the build
  // See: https://github.com/knockout/knockout/issues/1894
  if(_.isObject(requireConfig.paths) && _.isString(requireConfig.paths.knockout)) {
    requireConfig.paths.knockout = requireConfig.paths.knockout.replace(/.debug$/, '');
  }

  return gulp.src('public/app/main.js')
    .pipe(sourcemaps.init())
    .pipe(requirejsOptimize(
      _.extend(requireConfig, {
        include: [ 'requireLib', 'text' ],
        baseUrl: 'public/app/',
        name: 'main',
        out: 'app.js',
        // optimize: 'none', // uncomment this line to disable minification
        wrap: {
          start: '(function() {',
          end: '}());'
        }
      })
    ))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./public/build'));
});

gulp.task('build-styles', function () {
  var LessPluginAutoPrefix = require('less-plugin-autoprefix');
  var LessPluginCleanCSS = require('less-plugin-clean-css');
  var autoprefix = new LessPluginAutoPrefix({ browsers: [ 'last 2 versions', '> 5%', 'ie 9', 'ie 10'] });
  var cleancss = new LessPluginCleanCSS({ advanced: true });

  return gulp.src('./public/styles/app.less')
    .pipe(sourcemaps.init())
    .pipe(less({
      paths: [
        // base inclusion path for components
        path.join(__dirname, 'public', 'app', 'component')
      ],
      // cleancss bug is breaking the sourcemaps at the moment, hence it is disabled:
      // https://github.com/jakubpawlowicz/clean-css/issues/593
      plugins: [ autoprefix/*, cleancss*/ ]
     }))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./public/build'));
});

gulp.task('watch', ['watch-styles', 'watch-js']);

gulp.task('watch-and-test', ['watch-styles', 'watch-js', 'watch-tests']);

gulp.task('watch-styles', function() {
  gulp.watch(['public/styles/**/*.less', 'public/app/component/**/*.less'], ['build-styles']);
});

gulp.task('watch-js', function () {
  gulp.watch(['public/app/**/*.js', 'public/app/**/*.html'], ['build-js']);
});

gulp.task('watch-tests', function () {
  gulp.watch(['public/app/**/*.js', 'public/app/**/*.html'], ['tests']);
});

gulp.task('tests', function (done) {
  return new Server({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start();
});

gulp.task('webserver', function () {
  gulp.src('public')
    .pipe(webserver({
      host: '0.0.0.0',
      // host: 'localhost',
      fallback: 'index.html',
      livereload: false,
      port: 8000,
      open: true
    }));
});

redpajama_set_name: RedPajamaGithub


text:
package org.apache.spark.sql.catalyst

import scala.language.implicitConversions
import scala.util.parsing.combinator.lexical.StdLexical
import scala.util.parsing.combinator.syntactical.StandardTokenParsers
import scala.util.parsing.combinator.PackratParsers
import scala.util.parsing.input.CharArrayReader.EofCh

import org.apache.spark.sql.catalyst.plans.logical._

private[sql] abstract class AbstractSparkSQLParser
  extends StandardTokenParsers with PackratParsers {

  def parse(input: String): LogicalPlan = synchronized {
    // Initialize the Keywords.
    initLexical
    phrase(start)(new lexical.Scanner(input)) match {
      case Success(plan, _) => plan
      case failureOrError => sys.error(failureOrError.toString)
    }
  }
  /* One time initialization of lexical.This avoid reinitialization of  lexical in parse method */
  protected lazy val initLexical: Unit = lexical.initialize(reservedWords)

  protected case class Keyword(str: String) {
    def normalize: String = lexical.normalizeKeyword(str)
    def parser: Parser[String] = normalize
  }

  protected implicit def asParser(k: Keyword): Parser[String] = k.parser

  // By default, use Reflection to find the reserved words defined in the sub class.
  // NOTICE, Since the Keyword properties defined by sub class, we couldn't call this
  // method during the parent class instantiation, because the sub class instance
  // isn't created yet.
  protected lazy val reservedWords: Seq[String] =
    this
      .getClass
      .getMethods
      .filter(_.getReturnType == classOf[Keyword])
      .map(_.invoke(this).asInstanceOf[Keyword].normalize)

  // Set the keywords as empty by default, will change that later.
  override val lexical = new SqlLexical

  protected def start: Parser[LogicalPlan]

  // Returns the whole input string
  protected lazy val wholeInput: Parser[String] = new Parser[String] {
    def apply(in: Input): ParseResult[String] =
      Success(in.source.toString, in.drop(in.source.length()))
  }

  // Returns the rest of the input string that are not parsed yet
  protected lazy val restInput: Parser[String] = new Parser[String] {
    def apply(in: Input): ParseResult[String] =
      Success(
        in.source.subSequence(in.offset, in.source.length()).toString,
        in.drop(in.source.length()))
  }
}

class SqlLexical extends StdLexical {
  case class FloatLit(chars: String) extends Token {
    override def toString: String = chars
  }

  /* This is a work around to support the lazy setting */
  def initialize(keywords: Seq[String]): Unit = {
    reserved.clear()
    reserved ++= keywords
  }

  /* Normal the keyword string */
  def normalizeKeyword(str: String): String = str.toLowerCase

  delimiters += (
    "@", "*", "+", "-", "<", "=", "<>", "!=", "<=", ">=", ">", "/", "(", ")",
    ",", ";", "%", "{", "}", ":", "[", "]", ".", "&", "|", "^", "~", "<=>"
  )

  protected override def processIdent(name: String) = {
    val token = normalizeKeyword(name)
    if (reserved contains token) Keyword(token) else Identifier(name)
  }

  override lazy val token: Parser[Token] =
    ( identChar ~ (identChar | digit).* ^^
      { case first ~ rest => processIdent((first :: rest).mkString) }
    | digit.* ~ identChar ~ (identChar | digit).* ^^
      { case first ~ middle ~ rest => processIdent((first ++ (middle :: rest)).mkString) }
    | rep1(digit) ~ ('.' ~> digit.*).? ^^ {
        case i ~ None => NumericLit(i.mkString)
        case i ~ Some(d) => FloatLit(i.mkString + "." + d.mkString)
      }
    | '\'' ~> chrExcept('\'', '\n', EofCh).* <~ '\'' ^^
      { case chars => StringLit(chars mkString "") }
    | '"' ~> chrExcept('"', '\n', EofCh).* <~ '"' ^^
      { case chars => StringLit(chars mkString "") }
    | '`' ~> chrExcept('`', '\n', EofCh).* <~ '`' ^^
      { case chars => Identifier(chars mkString "") }
    | EofCh ^^^ EOF
    | '\'' ~> failure("unclosed string literal")
    | '"' ~> failure("unclosed string literal")
    | delim
    | failure("illegal character")
    )

  override def identChar: Parser[Elem] = letter | elem('_')

  override def whitespace: Parser[Any] =
    ( whitespaceChar
    | '/' ~ '*' ~ comment
    | '/' ~ '/' ~ chrExcept(EofCh, '\n').*
    | '#' ~ chrExcept(EofCh, '\n').*
    | '-' ~ '-' ~ chrExcept(EofCh, '\n').*
    | '/' ~ '*' ~ failure("unclosed comment")
    ).*
}


text:
#pragma once
#include <aws/transcribe/TranscribeService_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/transcribe/model/CategoryProperties.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace TranscribeService
{
namespace Model
{
  class AWS_TRANSCRIBESERVICE_API ListCallAnalyticsCategoriesResult
  {
  public:
    ListCallAnalyticsCategoriesResult();
    ListCallAnalyticsCategoriesResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ListCallAnalyticsCategoriesResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
If NextToken is present in your response, it indicates that not
     * all results are displayed. To view the next set of results, copy the string
     * associated with the NextToken parameter in your results output,
     * then run your request again including NextToken with the value of
     * the copied string. Repeat as needed to view all your results.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
If NextToken is present in your response, it indicates that not
     * all results are displayed. To view the next set of results, copy the string
     * associated with the NextToken parameter in your results output,
     * then run your request again including NextToken with the value of
     * the copied string. Repeat as needed to view all your results.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }

    /**
     *
If NextToken is present in your response, it indicates that not
     * all results are displayed. To view the next set of results, copy the string
     * associated with the NextToken parameter in your results output,
     * then run your request again including NextToken with the value of
     * the copied string. Repeat as needed to view all your results.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }

    /**
     *
If NextToken is present in your response, it indicates that not
     * all results are displayed. To view the next set of results, copy the string
     * associated with the NextToken parameter in your results output,
     * then run your request again including NextToken with the value of
     * the copied string. Repeat as needed to view all your results.

     */
    inline void SetNextToken(const char* value) { m_nextToken.assign(value); }

    /**
     *
If NextToken is present in your response, it indicates that not
     * all results are displayed. To view the next set of results, copy the string
     * associated with the NextToken parameter in your results output,
     * then run your request again including NextToken with the value of
     * the copied string. Repeat as needed to view all your results.

     */
    inline ListCallAnalyticsCategoriesResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
If NextToken is present in your response, it indicates that not
     * all results are displayed. To view the next set of results, copy the string
     * associated with the NextToken parameter in your results output,
     * then run your request again including NextToken with the value of
     * the copied string. Repeat as needed to view all your results.

     */
    inline ListCallAnalyticsCategoriesResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
If NextToken is present in your response, it indicates that not
     * all results are displayed. To view the next set of results, copy the string
     * associated with the NextToken parameter in your results output,
     * then run your request again including NextToken with the value of
     * the copied string. Repeat as needed to view all your results.

     */
    inline ListCallAnalyticsCategoriesResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}

    /**
     *
Provides detailed information about your Call Analytics categories, including
     * all the rules associated with each category.

     */
    inline const Aws::Vector<CategoryProperties>& GetCategories() const{ return m_categories; }

    /**
     *
Provides detailed information about your Call Analytics categories, including
     * all the rules associated with each category.

     */
    inline void SetCategories(const Aws::Vector<CategoryProperties>& value) { m_categories = value; }

    /**
     *
Provides detailed information about your Call Analytics categories, including
     * all the rules associated with each category.

     */
    inline void SetCategories(Aws::Vector<CategoryProperties>&& value) { m_categories = std::move(value); }

    /**
     *
Provides detailed information about your Call Analytics categories, including
     * all the rules associated with each category.

     */
    inline ListCallAnalyticsCategoriesResult& WithCategories(const Aws::Vector<CategoryProperties>& value) { SetCategories(value); return *this;}

    /**
     *
Provides detailed information about your Call Analytics categories, including
     * all the rules associated with each category.

     */
    inline ListCallAnalyticsCategoriesResult& WithCategories(Aws::Vector<CategoryProperties>&& value) { SetCategories(std::move(value)); return *this;}

    /**
     *
Provides detailed information about your Call Analytics categories, including
     * all the rules associated with each category.

     */
    inline ListCallAnalyticsCategoriesResult& AddCategories(const CategoryProperties& value) { m_categories.push_back(value); return *this; }

    /**
     *
Provides detailed information about your Call Analytics categories, including
     * all the rules associated with each category.

     */
    inline ListCallAnalyticsCategoriesResult& AddCategories(CategoryProperties&& value) { m_categories.push_back(std::move(value)); return *this; }

  private:

    Aws::String m_nextToken;

    Aws::Vector<CategoryProperties> m_categories;
  };

} // namespace Model
} // namespace TranscribeService
} // namespace Aws


text:
require "test_helper"

class CorreiosTest < ActiveSupport::TestCase
  include ActiveShipping::Test::Fixtures

  def setup
    @carrier = Correios.new

    @saopaulo = Location.new(:zip => "01415000")
    @patosdeminas = Location.new(:zip => "38700000")

    @book = package_fixtures[:book]
    @poster = package_fixtures[:poster]

    @response_clothes = xml_fixture('correios/clothes_response')
    @response_shoes = xml_fixture('correios/shoes_response')
    @response_book_success = xml_fixture('correios/book_response')
    @response_poster_success = xml_fixture('correios/poster_response')
    @response_book_invalid = xml_fixture('correios/book_response_invalid')
  end

  def test_book_request
    @carrier.expects(:perform).returns([@response_book_success])
    response = @carrier.find_rates(@saopaulo, @patosdeminas, [@book])

    [
      "sCepOrigem=01415000",
      "sCepDestino=38700000",
      "nVlPeso=0.25",
      "nCdFormato=1",
      "nVlComprimento=19",
      "nVlAltura=2",
      "nVlLargura=14",
      "nVlDiametro=0"
    ].each do |query_param|
      assert_match query_param, response.urls.first
    end
  end

  def test_poster_request
    @carrier.expects(:perform).returns([@response_poster_success])
    response = @carrier.find_rates(@saopaulo, @patosdeminas, [@poster])

    [
      "sCepOrigem=01415000",
      "sCepDestino=38700000",
      "nVlPeso=0.1",
      "nCdFormato=1",
      "nVlComprimento=93",
      "nVlAltura=10",
      "nVlLargura=10",
      "nVlDiametro=10"
    ].each do |query_param|
      assert_match query_param, response.urls.first
    end
  end

  def test_poster_and_book_request
    @carrier.expects(:perform).returns([@response_poster_success, @response_book_success])
    response = @carrier.find_rates(@saopaulo, @patosdeminas, [@poster, @book])

    [
      "sCepOrigem=01415000",
      "sCepDestino=38700000",
      "nVlPeso=0.1",
      "nCdFormato=1",
      "nVlComprimento=93",
      "nVlAltura=10",
      "nVlLargura=10",
      "nVlDiametro=10"
    ].each do |query_param|
      assert_match query_param, response.urls.first
    end

    [
      "sCepOrigem=01415000",
      "sCepDestino=38700000",
      "nVlPeso=0.25",
      "nCdFormato=1",
      "nVlComprimento=19",
      "nVlAltura=2",
      "nVlLargura=14",
      "nVlDiametro=0"
    ].each do |query_param|
      assert_match query_param, response.urls.last
    end
  end

  def test_book_request_with_specific_services
    @carrier.expects(:perform).returns([@response_book_success])
    response = @carrier.find_rates(@saopaulo, @patosdeminas, [@book], :services => [41106, 40010, 40215])

    [
      "nCdServico=41106%2C40010%2C40215",
      "sCepOrigem=01415000",
      "sCepDestino=38700000",
      "nVlPeso=0.25",
      "nCdFormato=1",
      "nVlComprimento=19",
      "nVlAltura=2",
      "nVlLargura=14",
      "nVlDiametro=0"
    ].each do |query_param|
      assert_match query_param, response.urls.first
    end
  end

  def test_book_request_with_option_params
    options = {
      :company_id => 1010,
      :password => 123123,
      :declared_value_extra => 10.50,
      :delivery_notice_extra => true,
      :mao_propria_extra => true
    }

    @carrier.expects(:perform).returns([@response_book_success])
    response = @carrier.find_rates(@saopaulo, @patosdeminas, [@book], options)

    [
      "nCdEmpresa=1010",
      "sDsSenha=123123",
      "sCdMaoPropria=S",
      "nVlValorDeclarado=10%2C5",
      "sCdAvisoRecebimento=S",
      "nCdServico=04510%2C04014",
      "sCepOrigem=01415000",
      "sCepDestino=38700000",
      "nVlPeso=0.25",
      "nCdFormato=1",
      "nVlComprimento=19",
      "nVlAltura=2",
      "nVlLargura=14",
      "nVlDiametro=0"
    ].each do |query_param|
      assert_match query_param, response.urls.first
    end

  end

  def test_book_response
    @carrier.stubs(:perform).returns([@response_book_success])
    response = @carrier.find_rates(@saopaulo, @patosdeminas, [@book])

    assert_equal 1, response.rates.size
    assert_equal [10520], response.rates.map(&:price)
  end

  def test_poster_response
    @carrier.stubs(:perform).returns([@response_poster_success])
    response = @carrier.find_rates(@saopaulo, @patosdeminas, [@poster])

    assert_equal 2, response.rates.size
    assert_equal [1000, 2000], response.rates.map(&:price)
  end

  def test_two_books_response
    @carrier.stubs(:perform).returns([@response_book_success, @response_book_success])
    response = @carrier.find_rates(@saopaulo, @patosdeminas, [@book, @book])

    assert_equal 1, response.rates.size
    assert_equal [21040], response.rates.map(&:price)
  end

  def test_two_posters_response
    @carrier.stubs(:perform).returns([@response_poster_success, @response_poster_success])
    response = @carrier.find_rates(@saopaulo, @patosdeminas, [@poster, @poster])

    assert_equal 2, response.rates.size
    assert_equal [2000, 4000], response.rates.map(&:price)
  end

  def test_response_parsing
    @carrier.stubs(:perform).returns([@response_clothes, @response_shoes])
    response = @carrier.find_rates(@saopaulo, @patosdeminas, [@book, @book])
    service_codes = [41106, 41300, 40215, 81019]
    service_names = [
      'PAC sem contrato',
      'PAC para grandes formatos',
      'SEDEX 10, sem contrato',
      'e-SEDEX, com contrato'
    ]

    assert_equal service_codes, response.rates.map(&:service_code)
    assert_equal service_names, response.rates.map(&:service_name)
  end

  def test_response_params_options
    @carrier.stubs(:perform).returns([@response_book_success])
    response = @carrier.find_rates(@saopaulo, @patosdeminas, [@book])

    assert_equal [Nokogiri::XML::Document], response.params['responses'].map(&:class)
    assert_equal [Nokogiri::XML(@response_book_success).to_xml], response.params['responses'].map(&:to_xml)
  end

  def test_book_invalid_response
    error = assert_raises(ActiveShipping::ResponseError) do
      @carrier.stubs(:perform).returns([@response_book_invalid])
      @carrier.find_rates(@saopaulo, @patosdeminas, [@book])
    end

    assert_equal "CEP de origem invalido", error.message
    assert_equal error.response.raw_responses, [@response_book_invalid]
    assert_equal Hash.new, error.response.params
  end

  def test_valid_book_and_invalid_book_response
    error = assert_raises(ActiveShipping::ResponseError) do
      @carrier.stubs(:perform).returns([@response_book_success, @response_book_invalid])
      @carrier.find_rates(@saopaulo, @patosdeminas, [@book, @book])
    end

    assert_equal "CEP de origem invalido", error.message
    assert_equal error.response.raw_responses, [@response_book_success, @response_book_invalid]
    assert_equal Hash.new, error.response.params
  end

  def test_show_available_services
    services = Correios.available_services

    assert_kind_of Hash, services
    assert_equal 21, services.size
    assert_equal 'PAC sem contrato', services[41106]
    assert_equal 'PAC com contrato', services[41068]
    assert_equal 'PAC para grandes formatos', services[41300]
    assert_equal 'SEDEX sem contrato', services[40010]
    assert_equal 'SEDEX a Cobrar, sem contrato', services[40045]
    assert_equal 'SEDEX a Cobrar, com contrato', services[40126]
    assert_equal 'SEDEX 10, sem contrato', services[40215]
    assert_equal 'SEDEX Hoje, sem contrato', services[40290]
    assert_equal 'SEDEX com contrato', services[40096]
    assert_equal 'SEDEX com contrato', services[40436]
    assert_equal 'SEDEX com contrato', services[40444]
    assert_equal 'SEDEX com contrato', services[40568]
    assert_equal 'SEDEX com contrato', services[40606]
    assert_equal 'e-SEDEX, com contrato', services[81019]
    assert_equal 'e-SEDEX Prioritário, com contrato', services[81027]
    assert_equal 'e-SEDEX Express, com contrato', services[81035]
    assert_equal '(Grupo 1) e-SEDEX, com contrato', services[81868]
    assert_equal '(Grupo 2) e-SEDEX, com contrato', services[81833]
    assert_equal '(Grupo 3) e-SEDEX, com contrato', services[81850]
  end

  def test_maximum_address_field_length
    assert_equal 255, @carrier.maximum_address_field_length
  end
end


text:
import binascii
import logging
import os
import os.path
import random
import subprocess

LOG = logging.getLogger(__name__)

def get_random_string(nbytes=8):
    """Return a fixed-length random string

    :rtype: str
    """
    try:
        # NOTE(dhellmann): Not all systems support urandom().
        # hexlify returns binary, decode to convert to str.
        val = binascii.hexlify(os.urandom(nbytes)).decode('utf-8')
    except Exception as e:
        print('ERROR, perhaps urandom is not supported: %s' % e)
        val = u''.join(u'%02x' % random.randrange(256)
                       for i in range(nbytes))
    return val

def check_output(*args, **kwds):
    """Unicode-aware wrapper for subprocess.check_output"""
    process = subprocess.Popen(stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               *args, **kwds)
    output, errors = process.communicate()
    retcode = process.poll()
    if errors:
        LOG.debug('ran: %s', ' '.join(*args))
        LOG.debug('returned: %s', retcode)
        LOG.debug('error output: %s', errors.rstrip())
        LOG.debug('regular output: %s', output.rstrip())
    if retcode:
        LOG.debug('raising error')
        raise subprocess.CalledProcessError(retcode, args, output=output)
    return output.decode('utf-8')


text:
namespace genetic {

class fitness {
public:
   static void objective_weights(std::initializer_list<float> && weights_);

   fitness();
   bool valid() const;
   void dirty();
   void update(std::vector<float> && values);
   float weighted_fitness() const;

   bool operator<(fitness const & other) const;
   bool operator>(fitness const & other) const;

private:
   void throw_if_invalid() const;

private:
   static std::vector<float> weights;
   std::vector<float> values;
   bool valid_;
};

} // namespace genetic


text:
namespace gyper
{
class HtsReader
{
public:
  htsFile * fp{nullptr}; // htslib file pointer
  hts_idx_t * hts_index{nullptr};
  hts_itr_t * hts_iter{nullptr};
  std::vector<std::string> samples;
  int sample_index_offset{0};
  int rg_index_offset{0};
  std::vector<int> rg2sample_i; // uses the rg index to determine the sample index

private:
  int ret{0};                    // return value of the most recently read record
  bam1_t * rec{nullptr};         // The most recently read record
  std::vector<bam1_t *> records; // A bulk of records that have the same position.
  // TODO check if it is faster to first check if the records are sorted
  HtsStore & store;
  std::unordered_map<std::string, long> rg2index; // associates read groups with indices of that rg
  std::string filename{};                         // for log messages

  void set_reference(std::string const & reference_path);

public:
  HtsReader(HtsStore & _store);

  void open(std::string const & path, std::string const & region, std::string const & reference);
  void close();
  void set_sample_index_offset(int new_sample_index_offset);
  void set_rg_index_offset(int new_rg_index_offset);

  // Get the read when reading a HTS file in order. It is probably never a good idea to call both get_next_read_in_order
  //  and get_next_read().
  bam1_t * get_next_read_in_order(bam1_t * old_record);
  bam1_t * get_next_read_in_order();
  bam1_t * get_next_read();
  bam1_t * get_next_read(bam1_t * old_record);

  void get_sample_and_rg_index(long & sample_i, long & rg_i, bam1_t * rec) const;
  long get_num_rg() const;
};

} // namespace gyper


text:
.. _training:

======================
Training a recommender
======================

Here are the basic options for ``mrec_train``::

    $ mrec_train
    Usage: mrec_train [options]

    Options:
      -h, --help            show this help message and exit
      -n NUM_ENGINES, --num_engines=NUM_ENGINES
                            number of IPython engines to use
      --input_format=INPUT_FORMAT
                            format of training dataset(s) tsv | csv | mm
                            (matrixmarket) | fsm (fast_sparse_matrix)
      --train=TRAIN         glob specifying path(s) to training dataset(s)
                            IMPORTANT: must be in quotes if it includes the *
                            wildcard
      --outdir=OUTDIR       directory for output files
      --overwrite           overwrite existing files in outdir
      --model=MODEL         type of model to train: slim | knn | popularity
                            (default: slim)
      --max_sims=MAX_SIMS   max similar items to output for each training item
                            (default: 100)

The ``--train`` input file for training can hold the user-item matrix in a variety of formats.
You can specify more than one input file by passing a standard unix file glob
containing the * wildcard, for example specifying `--train ml100-k/u.train.*` will
train separate models for `ml-100k/u.train.0`, `ml-100k/u.train.1` and so on.
This can be useful if you're doing cross-validation.

``mrec_train`` currently support three types of recommender: `knn` learns a traditional k-nearest neighbours item similarity model; `slim` specifies a SLIM model which learns item similarities by solving a regression problem; and `popularity` is a trivial baseline that will make the same recommendations for all users, but which can be useful for evaluation.

.. note::

    All input training files must have the same data format.

A separate recommender will be trained for each input file, and saved to disk in the
specified output directory: if the input file is called `u.train.0` then the
recommender will be saved in the file `u.train.0.model.npz`, and so on.  See :ref:`filename_conventions-link` for more information.

The saved model
can be passed to the ``mrec_predict`` script as described in :ref:`evaluation`, or used programmatically like
this::

    >>> model = load_recommender('u.train.0.model.npz')
    >>> sims = model.get_similar_items(231)  # get items similar to 231
    >>> recs = model.recommend_items(101,max_items=30)  # recommend top 30 items for user 101

See :mod:`mrec.item_similarity.recommender` for more details.

You can supply additional options to ``mrec_train`` specifying parameter settings for the particular type of recommender you are training.
For a SLIM recommender you probably want to specify::

      --learner=LEARNER     underlying learner for SLIM learner: sgd | elasticnet
                            | fs_sgd (default: sgd)
      --l1_reg=L1_REG       l1 regularization constant (default: 0.1)
      --l2_reg=L2_REG       l2 regularization constant (default: 0.001)

For a k-nearest neighbour recommender you just need to supply::

      --metric=METRIC       metric for knn recommender: cosine | dot (default:
                        cosine)

In this case ``max_sims`` is simply passed to the constructor
of the ``KNNRecommender`` as the value of ``k``.

You can also train a baseline non-personalized recommender that just finds the most popular
items and recommends them to everybody. The options for this are::

      --popularity_method=POPULARITY_METHOD
                            how to compute popularity for baseline recommender:
                            count | sum | avg | thresh (default: count)
      --popularity_thresh=POPULARITY_THRESH
                            ignore scores below this when computing popularity for
                            baseline recommender (default: 0)

The different measures mean let you base the popularity of an item on its total number of
ratings of any value, or its total above some threshold; or on the sum or mean of its ratings.

There are also a couple of options relating to the IPython.parallel framework::

      --packer=PACKER       packer for IPython.parallel (default: pickle)
      --add_module_paths=ADD_MODULE_PATHS
                            optional comma-separated list of paths to append to
                            pythonpath (useful if you need to import uninstalled
                            modules to IPython engines on a cluster)

The ``--add_module_paths`` option can be useful to specify the path to `mrec` itself
if you didn't install it at start up time on all the machines in your cluster.

Parameter tuning for SLIM
-------------------------
Before training a SLIM recommender, you'll need to choose the regularization constants.
You can do this easily using the ``mrec_tune`` script, which computes similarity weights for some
sample items over a range of values for each constant, and picks the best combination based on some
simple parameters.  The 'best' regularization constants are those that give similarity weights
that are as sparse as possible, but not too sparse.  You run ``mrec_tune`` like this::

    $ mrec_tune -d u.data.train.0 --input_format tsv \
        --l1_min 0.001 --l1_max 1.0 \
        --l2_min 0.0001 --l2_max 1 \
        --max_sims 200 --min_sims 1 --max_sparse 0.3

This says that we want to find the best constants that result in no more than 200 similar items for each item,
provided no more than 30% of items have no similar items at all.  We'd like to explore combinations of regularization
constants where the l1 constant ranges from 0.001 to 1.0 and the l2 constant from 0.0001 to 1.0.
The script will run for a few seconds and then report the best settings::

    best parameter setting: {'l1_reg': 0.1, 'l2_reg': 0.001}
    mean # positive similarity weights per item = 96.0
    proportion of items with fewer than 1 positive similarity weights = 0.25
    mean # negative similarity weights per item = 43.4

.. note::

    For this little dataset even the best constant values shown will mean that we won't learn
    any similar items for quite a large proportion of the training items.  This isn't
    usually a problem with production size datasets.


text:
import React, { Component } from 'react';
import InventoryTable from './components/InventoryTable';

class Inventory extends Component {
	render() {

		var items = this.props.items;

		return

Current Inventory

				<InventoryTable items={items} />

	}
}

export default Inventory;


text:
@interface FindPasd (Event)<UITextFieldDelegate, MBProgressHUDDelegate, CommonPPMessageShowDelegate, CJPopupViewDelegate>

@end


text:
import logging
import os
import subprocess
import sys
import tempfile
import unittest
import re

THIS_FILE = os.path.abspath(__file__)
sys.path.insert(0, os.path.dirname(os.path.dirname(THIS_FILE)))

from third_party.depot_tools import fix_encoding
from utils import file_path
from utils import logging_utils

# PID YYYY-MM-DD HH:MM:SS.MMM
_LOG_HEADER = r'^%d \d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d\.\d\d\d' % os.getpid()
_LOG_HEADER_PID = r'^\d+ \d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d\.\d\d\d'

_PHASE = 'LOGGING_UTILS_TESTS_PHASE'

def call(phase, cwd):
  """Calls itself back."""
  env = os.environ.copy()
  env[_PHASE] = phase
  return subprocess.call([sys.executable, '-u', THIS_FILE], env=env, cwd=cwd)

class Test(unittest.TestCase):
  def setUp(self):
    super(Test, self).setUp()
    self.tmp = tempfile.mkdtemp(prefix='logging_utils')

  def tearDown(self):
    try:
      file_path.rmtree(self.tmp)
    finally:
      super(Test, self).tearDown()

  def test_capture(self):
    root = logging.RootLogger(logging.DEBUG)
    with logging_utils.CaptureLogs('foo', root) as log:
      root.debug('foo')
      result = log.read()
    expected = _LOG_HEADER + ': DEBUG foo\n$'
    if sys.platform == 'win32':
      expected = expected.replace('\n', '\r\n')
    self.assertTrue(re.match(expected, result), (expected, result))

  def test_prepare_logging(self):
    root = logging.RootLogger(logging.DEBUG)
    filepath = os.path.join(self.tmp, 'test.log')
    logging_utils.prepare_logging(filepath, root)
    root.debug('foo')
    with open(filepath, 'rb') as f:
      result = f.read()
    # It'd be nice to figure out a way to ensure it's properly in UTC but it's
    # tricky to do reliably.
    expected = _LOG_HEADER + ' D: foo\n$'
    self.assertTrue(re.match(expected, result), (expected, result))

  def test_rotating(self):
    # Create a rotating log. Create a subprocess then delete the file. Make sure
    # nothing blows up.
    # Everything is done in a child process because the called functions mutate
    # the global state.
    self.assertEqual(0, call('test_rotating_phase_1', cwd=self.tmp))
    self.assertEqual({'shared.1.log'}, set(os.listdir(self.tmp)))
    with open(os.path.join(self.tmp, 'shared.1.log'), 'rb') as f:
      lines = f.read().splitlines()
    expected = [
      r' I: Parent1',
      r' I: Child1',
      r' I: Child2',
      r' I: Parent2',
    ]
    for e, l in zip(expected, lines):
      ex = _LOG_HEADER_PID + e + '$'
      self.assertTrue(re.match(ex, l), (ex, l))
    self.assertEqual(len(expected), len(lines))

def test_rotating_phase_1():
  logging_utils.prepare_logging('shared.log')
  logging.info('Parent1')
  r = call('test_rotating_phase_2', None)
  logging.info('Parent2')
  return r

def test_rotating_phase_2():
  # Simulate rotating the log.
  logging_utils.prepare_logging('shared.log')
  logging.info('Child1')
  os.rename('shared.log', 'shared.1.log')
  logging.info('Child2')
  return 0

def main():
  phase = os.environ.get(_PHASE)
  if phase:
    return getattr(sys.modules[__name__], phase)()
  verbose = '-v' in sys.argv
  logging.basicConfig(level=logging.DEBUG if verbose else logging.ERROR)
  unittest.main()

if __name__ == '__main__':
  fix_encoding.fix_encoding()
  sys.exit(main())


text:
/**
 *
 */
package com.gemstone.gemfire.internal.cache;

import com.gemstone.gemfire.cache.server.ClientSubscriptionConfig;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
/**
 *
 * Configuration parameters for client subscription
 * @author aingle
 */
public class ClientSubscriptionConfigImpl implements ClientSubscriptionConfig {

  /**
   *  To get client subscription
   */
  public static final String CLIENT_SUBSCRIPTION = "client_subscription";

  private int haQueueCapacity = 1;

  private String haEvictionPolicy = null;

  /**
   * The name of the directory in which to store overflowed client queue entries
   */
  private String overflowDirectory;

  /**
   * disk store name for overflow
   */
  private String diskStoreName;

  private boolean hasOverflowDirectory = false;

  public ClientSubscriptionConfigImpl(){
    this.haQueueCapacity = DEFAULT_CAPACITY;
    this.haEvictionPolicy = DEFAULT_EVICTION_POLICY;
    this.overflowDirectory = DEFAULT_OVERFLOW_DIRECTORY;
  }
  /**
   * Returns the capacity of the client client queue.
   * will be in MB for eviction-policy mem else
   * number of entries
   * @see #DEFAULT_CAPACITY
   * @since 5.7
   */
  public int getCapacity(){
    return this.haQueueCapacity ;
  }
  /**
   * Sets the capacity of the client client queue.
   * will be in MB for eviction-policy mem else
   * number of entries
   * @see #DEFAULT_CAPACITY
   * @since 5.7
   */
  public void setCapacity(int capacity){
    this.haQueueCapacity = capacity;
  }
  /**
   * Returns the eviction policy that is executed when capacity of the client client queue is reached.
   * @see #DEFAULT_EVICTION_POLICY
   * @since 5.7
   */
  public String getEvictionPolicy(){
    return this.haEvictionPolicy ;
  }
  /**
   * Sets the eviction policy that is executed when capacity of the client client queue is reached.
   * @see #DEFAULT_EVICTION_POLICY
   * @since 5.7
   */
  public void setEvictionPolicy(String policy){
    this.haEvictionPolicy = policy;
  }

  /**
   * Sets the overflow directory for a client client queue
   * @param overflowDirectory the overflow directory for a client queue's overflowed entries
   * @since 5.7
   * @deprecated as of prPersistSprint2
   */
  @Deprecated
  public void setOverflowDirectory(String overflowDirectory) {
    if (this.getDiskStoreName() != null) {
      throw new IllegalStateException(LocalizedStrings.DiskStore_Deprecated_API_0_Cannot_Mix_With_DiskStore_1
          .toLocalizedString(new Object[] {"setOverflowDirectory", this.getDiskStoreName()}));
    }
    this.overflowDirectory = overflowDirectory;
    setHasOverflowDirectory(true);
  }

  /**
   * Answers the overflow directory for a client queue's
   * overflowed client queue entries.
   * @return the overflow directory for a client queue's
   * overflowed entries
   * @since 5.7
   * @deprecated as of prPersistSprint2
   */
  @Deprecated
  public String getOverflowDirectory() {
    if (this.getDiskStoreName() != null) {
      throw new IllegalStateException(LocalizedStrings.DiskStore_Deprecated_API_0_Cannot_Mix_With_DiskStore_1
          .toLocalizedString(new Object[] {"getOverflowDirectory", this.getDiskStoreName()}));
    }
    return this.overflowDirectory;
  }

  @Override
  public String toString() {
    String str = " Eviction policy "
        + this.getEvictionPolicy() + " capacity "
        + this.getCapacity();
    if (diskStoreName == null) {
      str += " Overflow Directory " + this.getOverflowDirectory();
    } else {
      str += " DiskStore Name: " + this.diskStoreName;
    }
    return str;
  }
  /**
   * get the diskStoreName for overflow
   * @since prPersistSprint2
   */
  public String getDiskStoreName() {
    return diskStoreName;
  }
  /**
   * Sets the disk store name for overflow
   * @param diskStoreName
   * @since prPersistSprint2
   */
  public void setDiskStoreName(String diskStoreName) {
    if (hasOverflowDirectory()) {
      throw new IllegalStateException(LocalizedStrings.DiskStore_Deprecated_API_0_Cannot_Mix_With_DiskStore_1
          .toLocalizedString(new Object[] {"setDiskStoreName", this.getDiskStoreName()}));
    }
    this.diskStoreName = diskStoreName;
  }

  public boolean hasOverflowDirectory()
  {
    return this.hasOverflowDirectory;
  }
  private void setHasOverflowDirectory(boolean hasOverflowDirectory)
  {
    this.hasOverflowDirectory = hasOverflowDirectory;
  }

  /*public boolean equals(ClientSubscriptionConfig other) {
    if (other != null && other.getEvictionPolicy() != null
        && other.getOverflowDirectory() != null) {
      if ((this.getEvictionPolicy() == other.getEvictionPolicy())
          && (this.getOverflowDirectory() == other.getOverflowDirectory())
          && (this.getCapacity() == this.getCapacity()))
        return true;
    }
    return false;
  }*/
}


text:
/*
 * Copyright (C) 2003 EBI, GRL
 *
 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package org.ensembl.healthcheck.testcase.funcgen;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.Team;

/**
 * Compare the xrefs in the current database with those from the equivalent
 * database on the secondary server.
 */

public class ComparePreviousVersionArrayXrefs extends RegulationComparePreviousVersion {

	/**
	 * Create a new  testcase.
	 */

	public ComparePreviousVersionArrayXrefs() {
		addToGroup("funcgen");
		addToGroup("funcgen-release");
		//setHintLongRunning(true);// ?Only take about 10 mins for mouse
		setTeamResponsible(Team.FUNCGEN);
		setDescription("Compare the Arrays xrefs in the current database with those from the equivalent database on the secondary server");
	}

	//We could add a run wrapper here to compare DISPLAYABLE arrays first?

	// ---------[-------------------------------------------------------------

	protected Map getCounts(DatabaseRegistryEntry dbre) {

		//Doing this in one query will most likely run the instance out of resources
		//Need to return an array of queries which can be performed bitwise

		Map arrayXrefCounts = new HashMap();
		//Get array_ids for all DISPLAYABLE
		//Also need to compare DISPLAYABLE arrays HC?

		String sql = "select a.array_id, a.vendor, a.name from array a " +
			" group by a.array_id";

		//Count object_xref records for each array

		try {
			Statement idStmt     = dbre.getConnection().createStatement();
			//Create separate Statment so we don't close the arrayIDs ResultSet
			Statement cntStmt    = dbre.getConnection().createStatement();
			ResultSet arrayIDs = idStmt.executeQuery(sql);
			//System.out.println(sql);

			while (arrayIDs != null && arrayIDs.next()) {
				//ResultSets are 'never null', so why test for this?

				//Set this to ProbeSet for affy, and Probe for all others
				//Would be nice to have this in the DB, but rely on vendor for now

				//Should probably

				if (arrayIDs.getString(2).equals("AFFY")) { //ProbeSets
					//

					sql = "SELECT a.name AS array_name, COUNT(distinct ox.object_xref_id) AS count FROM external_db edb, xref x, " +
					 	"object_xref ox, probe p, array_chip ac, array a " +
						"WHERE edb.external_db_id=x.external_db_id AND x.xref_id=ox.xref_id and ox.ensembl_id=p.probe_set_id and " +
						"p.array_chip_id=ac.array_chip_id and ac.array_id=a.array_id and ox.ensembl_object_type='ProbeSet' and " +
						"edb.db_display_name='EnsemblTranscript' and a.array_id=" + arrayIDs.getString(1) +
						" GROUP BY a.array_id";
				}
				else { //Probes
					sql = "SELECT a.name AS array_name, COUNT(distinct ox.object_xref_id) AS count FROM external_db edb, xref x, " +
						"object_xref ox, probe p, array_chip ac, array a " +
						"WHERE edb.external_db_id=x.external_db_id AND x.xref_id=ox.xref_id and ox.ensembl_id=p.probe_id and " +
						"p.array_chip_id=ac.array_chip_id and ac.array_id=a.array_id and ox.ensembl_object_type='Probe' and " +
					 	"edb.db_display_name='EnsemblTranscript' and a.array_id=" + arrayIDs.getString(1) +
						" GROUP BY a.array_id";
				}

				//SELECT a.name AS array_name, COUNT(distinct ox.object_xref_id) AS count FROM external_db edb, xref x, object_xref ox, probe p, array_chip ac, array a WHERE edb.external_db_id=x.external_db_id AND x.xref_id=ox.xref_id and ox.ensembl_id=p.probe_id and p.array_chip_id=ac.array_chip_id and ac.array_id=a.array_id and ox.ensembl_object_type='Probe' and edb.db_display_name='EnsemblTranscript' and a.array_id='' GROUP BY a.array_id

				//Can rely on only having xrefs against one edb per array due to
				//mandatory rollback in probe2transcript

				//Could do with warning if edb does not match schema build if new and old schema_build do not match.
				//i.e. we have a new assembly or gene build update

				//System.out.println(sql);

				//Recreate getCountsBySQL

				try {
					logger.finest("Counting " + entityDescription() + " for " + dbre.getName() + ':' + arrayIDs.getString(3)
								  + "\nUSING SQL:\n" + sql);
					ResultSet xrefCounts = cntStmt.executeQuery(sql);

					while (xrefCounts != null && xrefCounts.next()) {
						//recast count which mysql returns as string as Integer?
						arrayXrefCounts.put(xrefCounts.getString(1), new Integer(xrefCounts.getInt(2)));
					}
				} catch (SQLException e){
					e.printStackTrace();
				}
			}
		}catch (SQLException e){
			e.printStackTrace();
		}

		return arrayXrefCounts;

	} // ------------------------------------------------------------------------

	protected String entityDescription() {

		return "Array Xrefs";

	}

	// ------------------------------------------------------------------------

	protected double threshold() {

		//only allow 10% change before fail?
		return 0.95;

	}

        // ------------------------------------------------------------------------

        protected double minimum() {

                return 0;

        }

	// ----------------------------------------------------------------------

	protected boolean testUpperThreshold(){
		return true;
	}

	// ----------------------------------------------------------------------

} // ComparePreviousVersionArrayXrefs


text:
set -e

STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3
STATE_DEPENDENT=4

PID=$(pidof -x ceilometer-collector)

if ! KEY=$(sudo /bin/netstat -epta 2>/dev/null | grep $PID | grep amqp)
then
    echo "Ceilometer Collector is not connected to AMQP."
    exit $STATE_CRITICAL
fi

echo "Ceilometer Collector is working."


text:
namespace Google.Cloud.Compute.V1.Snippets
{
    // [START compute_v1_generated_Images_SetIamPolicy_async_flattened]
    using Google.Cloud.Compute.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedImagesClientSnippets
    {
        /// <summary>Snippet for SetIamPolicyAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task SetIamPolicyAsync()
        {
            // Create client
            ImagesClient imagesClient = await ImagesClient.CreateAsync();
            // Initialize request argument(s)
            string project = "";
            string resource = "";
            GlobalSetPolicyRequest globalSetPolicyRequestResource = new GlobalSetPolicyRequest();
            // Make the request
            Policy response = await imagesClient.SetIamPolicyAsync(project, resource, globalSetPolicyRequestResource);
        }
    }
    // [END compute_v1_generated_Images_SetIamPolicy_async_flattened]
}


text:
include_recipe 'chef-client::config'

#file '/etc/chef/client.d/syslog.rb' do
#  content <<-EOF
#log_location Chef::Log::Syslog.new("chef-client", ::Syslog::LOG_DAEMON)
#EOF
#end


text:
module Mayak
  module Preporator

    def prepare_model(model)
      class Field < Struct.new(:name, :type, :index)
        def initialize(name, type, index=false); super end
      end
      result = []
      model.columns.each do |column|
        mayak_field = Field.new
        case column.type
        when :string
          case column.name
          when 'slug'
            mayak_field.name = column.name
            mayak_field.type = :slug
            result << mayak_field
          when 'seodata'
            mayak_field.name = column.name
            mayak_field.type = :seo
            result << mayak_field
          else
            if is_uploader?(model, column.name)
              mayak_field.name = column.name
              mayak_field.type = :image
              result << mayak_field
            else
              mayak_field.name = column.name
              mayak_field.type = column.type
              result << mayak_field
            end
          end
        when :integer
          unless column.name == 'id'
            mayak_field.name = column.name
            mayak_field.type = column.type
            result << mayak_field
          end
        else
          mayak_field.name = column.name
          mayak_field.type = column.type
          result << mayak_field
        end
        result
      end
    end

    private

    def is_uploader?(model, filed)
      File.readlines("./app/models/#{model}.rb").select { |string| string.include?("mount_uploader :#{filed}") }.size > 0
    end

  end

end


text:
<?php

// @codingStandardsIgnoreFile

namespace Magento\Sales\Test\Unit\Model\AdminOrder;

use Magento\Sales\Model\AdminOrder\Product;
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class CreateTest extends \PHPUnit_Framework_TestCase
{
    const CUSTOMER_ID = 1;

    /** @var \Magento\Sales\Model\AdminOrder\Create */
    protected $adminOrderCreate;

    /** @var \Magento\Backend\Model\Session\Quote|\PHPUnit_Framework_MockObject_MockObject */
    protected $sessionQuoteMock;

    /** @var \Magento\Customer\Model\Metadata\FormFactory|\PHPUnit_Framework_MockObject_MockObject */
    protected $formFactoryMock;

    /** @var \Magento\Customer\Api\Data\CustomerInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject */
    protected $customerFactoryMock;

    /** @var \Magento\Quote\Model\Quote\Item\Updater|\PHPUnit_Framework_MockObject_MockObject */
    protected $itemUpdater;

    /** @var \Magento\Customer\Model\Customer\Mapper|\PHPUnit_Framework_MockObject_MockObject */
    protected $customerMapper;

    /**
     * @var Product\Quote\Initializer|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $quoteInitializerMock;

    /**
     * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $customerRepositoryMock;

    /**
     * @var \Magento\Customer\Api\AddressRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $addressRepositoryMock;

    /**
     * @var \Magento\Customer\Api\Data\AddressInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $addressFactoryMock;

    /**
     * @var \Magento\Customer\Api\GroupRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $groupRepositoryMock;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $scopeConfigMock;

    /**
     * @var \Magento\Sales\Model\AdminOrder\EmailSender|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $emailSenderMock;

    /**
     * @var \Magento\Customer\Api\AccountManagementInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $accountManagementMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $objectFactory;

    /**
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    protected function setUp()
    {
        $objectManagerMock = $this->getMock('Magento\Framework\ObjectManagerInterface');
        $eventManagerMock = $this->getMock('Magento\Framework\Event\ManagerInterface');
        $registryMock = $this->getMock('Magento\Framework\Registry');
        $configMock = $this->getMock('Magento\Sales\Model\Config', [], [], '', false);
        $this->sessionQuoteMock = $this->getMock('Magento\Backend\Model\Session\Quote', [], [], '', false);
        $loggerMock = $this->getMock('Psr\Log\LoggerInterface');
        $copyMock = $this->getMock('Magento\Framework\DataObject\Copy', [], [], '', false);
        $messageManagerMock = $this->getMock('Magento\Framework\Message\ManagerInterface');
        $this->formFactoryMock = $this->getMock(
            'Magento\Customer\Model\Metadata\FormFactory',
            ['create'],
            [],
            '',
            false
        );
        $this->customerFactoryMock = $this->getMock(
            'Magento\Customer\Api\Data\CustomerInterfaceFactory',
            ['create'],
            [],
            '',
            false
        );

        $this->itemUpdater = $this->getMock('Magento\Quote\Model\Quote\Item\Updater', [], [], '', false);

        $this->objectFactory = $this->getMockBuilder('\Magento\Framework\DataObject\Factory')
            ->disableOriginalConstructor()
            ->setMethods(['create'])
            ->getMock();

        $this->customerMapper = $this->getMockBuilder(
            'Magento\Customer\Model\Customer\Mapper'
        )->setMethods(['toFlatArray'])->disableOriginalConstructor()->getMock();

        $this->quoteInitializerMock = $this->getMock(
            'Magento\Sales\Model\AdminOrder\Product\Quote\Initializer',
            [],
            [],
            '',
            false
        );
        $this->customerRepositoryMock = $this->getMockForAbstractClass(
            'Magento\Customer\Api\CustomerRepositoryInterface',
            [],
            '',
            false
        );
        $this->addressRepositoryMock = $this->getMockForAbstractClass(
            'Magento\Customer\Api\AddressRepositoryInterface',
            [],
            '',
            false
        );
        $this->addressFactoryMock = $this->getMock(
            'Magento\Customer\Api\Data\AddressInterfaceFactory',
            [],
            [],
            '',
            false
        );
        $this->groupRepositoryMock = $this->getMockForAbstractClass(
            'Magento\Customer\Api\GroupRepositoryInterface',
            [],
            '',
            false
        );
        $this->scopeConfigMock = $this->getMockForAbstractClass(
            'Magento\Framework\App\Config\ScopeConfigInterface',
            [],
            '',
            false
        );
        $this->emailSenderMock = $this->getMock(
            'Magento\Sales\Model\AdminOrder\EmailSender',
            [],
            [],
            '',
            false
        );
        $this->accountManagementMock = $this->getMockForAbstractClass(
            'Magento\Customer\Api\AccountManagementInterface',
            [],
            '',
            false
        );

        $objectManagerHelper = new ObjectManagerHelper($this);
        $this->adminOrderCreate = $objectManagerHelper->getObject(
            'Magento\Sales\Model\AdminOrder\Create',
            [
                'objectManager' => $objectManagerMock,
                'eventManager' => $eventManagerMock,
                'coreRegistry' => $registryMock,
                'salesConfig' => $configMock,
                'quoteSession' => $this->sessionQuoteMock,
                'logger' => $loggerMock,
                'objectCopyService' => $copyMock,
                'messageManager' => $messageManagerMock,
                'quoteInitializer' => $this->quoteInitializerMock,
                'customerRepository' => $this->customerRepositoryMock,
                'addressRepository' => $this->addressRepositoryMock,
                'addressFactory' => $this->addressFactoryMock,
                'metadataFormFactory' => $this->formFactoryMock,
                'customerFactory' => $this->customerFactoryMock,
                'groupRepository' => $this->groupRepositoryMock,
                'quoteItemUpdater' => $this->itemUpdater,
                'customerMapper' => $this->customerMapper,
                'objectFactory' => $this->objectFactory,
                'accountManagement' => $this->accountManagementMock,
            ]
        );
    }

    public function testSetAccountData()
    {
        $taxClassId = 1;
        $attributes = [
            ['email', 'user@example.com'],
            ['group_id', 1]
        ];
        $attributeMocks = [];

        foreach ($attributes as $attribute) {
            $attributeMock = $this->getMock(
                'Magento\Customer\Api\Data\AttributeMetadataInterface',
                [],
                [],
                '',
                false
            );

            $attributeMock->expects($this->any())->method('getAttributeCode')->will($this->returnValue($attribute[0]));

            $attributeMocks[] = $attributeMock;
        }

        $customerGroupMock = $this->getMockForAbstractClass(
            'Magento\Customer\Api\Data\GroupInterface',
            [],
            '',
            false,
            true,
            true,
            ['getTaxClassId']
        );
        $customerGroupMock->expects($this->once())->method('getTaxClassId')->will($this->returnValue($taxClassId));
        $customerFormMock = $this->getMock('Magento\Customer\Model\Metadata\Form', [], [], '', false);
        $customerFormMock->expects($this->any())->method('getAttributes')->will($this->returnValue($attributeMocks));
        $customerFormMock->expects($this->any())->method('extractData')->will($this->returnValue([]));
        $customerFormMock->expects($this->any())->method('restoreData')->will($this->returnValue([]));

        $customerFormMock->expects($this->any())
            ->method('prepareRequest')
            ->will($this->returnValue($this->getMock('Magento\Framework\App\RequestInterface')));

        $customerMock = $this->getMock('Magento\Customer\Api\Data\CustomerInterface', [], [], '', false);
        $this->customerMapper->expects($this->any())->method('toFlatArray')
            ->will($this->returnValue(['email' => 'user@example.com', 'group_id' => 1]));
        $quoteMock = $this->getMock('Magento\Quote\Model\Quote', [], [], '', false);
        $quoteMock->expects($this->any())->method('getCustomer')->will($this->returnValue($customerMock));
        $quoteMock->expects($this->once())
            ->method('addData')
            ->with(
            [
                'customer_email' => $attributes[0][1],
                'customer_group_id' => $attributes[1][1],
                'customer_tax_class_id' => $taxClassId
            ]
        );

        $this->formFactoryMock->expects($this->any())->method('create')->will($this->returnValue($customerFormMock));
        $this->sessionQuoteMock->expects($this->any())->method('getQuote')->will($this->returnValue($quoteMock));
        $this->customerFactoryMock->expects($this->any())->method('create')->will($this->returnValue($customerMock));

        $this->groupRepositoryMock->expects($this->once())
            ->method('getById')
            ->will($this->returnValue($customerGroupMock));

        $this->adminOrderCreate->setAccountData([]);
    }

    public function testUpdateQuoteItemsNotArray()
    {
        $this->adminOrderCreate->updateQuoteItems('string');
    }

    public function testUpdateQuoteItemsEmptyConfiguredOption()
    {
        $items = [
            1 => [
                'qty' => 10,
                'configured' => false,
                'action' => false
            ]
        ];

        $itemMock = $this->getMock('Magento\Quote\Model\Quote\Item', [], [], '', false);

        $quoteMock = $this->getMock('Magento\Quote\Model\Quote', [], [], '', false);
        $quoteMock->expects($this->once())
            ->method('getItemById')
            ->will($this->returnValue($itemMock));

        $this->sessionQuoteMock->expects($this->any())->method('getQuote')->will($this->returnValue($quoteMock));
        $this->itemUpdater->expects($this->once())
            ->method('update')
            ->with($this->equalTo($itemMock), $this->equalTo($items[1]))
            ->will($this->returnSelf());

        $this->adminOrderCreate->setRecollect(false);
        $this->adminOrderCreate->updateQuoteItems($items);
    }

    public function testUpdateQuoteItemsWithConfiguredOption()
    {
        $qty = 100000000;
        $items = [
            1 => [
                'qty' => 10,
                'configured' => true,
                'action' => false
            ]
        ];

        $itemMock = $this->getMock('Magento\Quote\Model\Quote\Item', [], [], '', false);
        $itemMock->expects($this->once())
            ->method('getQty')
            ->will($this->returnValue($qty));

        $quoteMock = $this->getMock('Magento\Quote\Model\Quote', [], [], '', false);
        $quoteMock->expects($this->once())
            ->method('updateItem')
            ->will($this->returnValue($itemMock));

        $this->sessionQuoteMock->expects($this->any())->method('getQuote')->will($this->returnValue($quoteMock));

        $expectedInfo = $items[1];
        $expectedInfo['qty'] = $qty;
        $this->itemUpdater->expects($this->once())
            ->method('update')
            ->with($this->equalTo($itemMock), $this->equalTo($expectedInfo));

        $this->adminOrderCreate->setRecollect(false);
        $this->adminOrderCreate->updateQuoteItems($items);
    }
}


text:
'use strict';

angular.module('stackrApp')
  .controller('LogoutController', function ($state, LoginService) {

    LoginService.logout();
    $state.go('login');

  });