text:
package io.netty.handler.codec.compression;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.internal.ObjectUtil;

import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * Decompress a {@link ByteBuf} using the inflate algorithm.
 */
public class JdkZlibDecoder extends ZlibDecoder {
    private static final int FHCRC = 0x02;
    private static final int FEXTRA = 0x04;
    private static final int FNAME = 0x08;
    private static final int FCOMMENT = 0x10;
    private static final int FRESERVED = 0xE0;

    private Inflater inflater;
    private final byte[] dictionary;

    // GZIP related
    private final ByteBufChecksum crc;
    private final boolean decompressConcatenated;

    private enum GzipState {
        HEADER_START,
        HEADER_END,
        FLG_READ,
        XLEN_READ,
        SKIP_FNAME,
        SKIP_COMMENT,
        PROCESS_FHCRC,
        FOOTER_START,
    }

    private GzipState gzipState = GzipState.HEADER_START;
    private int flags = -1;
    private int xlen = -1;

    private volatile boolean finished;

    private boolean decideZlibOrNone;

    /**
     * Creates a new instance with the default wrapper ({@link ZlibWrapper#ZLIB}).
     */
    public JdkZlibDecoder() {
        this(ZlibWrapper.ZLIB, null, false, 0);
    }

    /**
     * Creates a new instance with the default wrapper ({@link ZlibWrapper#ZLIB})
     * and the specified maximum buffer allocation.
     *
     * @param maxAllocation
     *          Maximum size of the decompression buffer. Must be >= 0.
     *          If zero, maximum size is decided by the {@link ByteBufAllocator}.
     */
    public JdkZlibDecoder(int maxAllocation) {
        this(ZlibWrapper.ZLIB, null, false, maxAllocation);
    }

    /**
     * Creates a new instance with the specified preset dictionary. The wrapper
     * is always {@link ZlibWrapper#ZLIB} because it is the only format that
     * supports the preset dictionary.
     */
    public JdkZlibDecoder(byte[] dictionary) {
        this(ZlibWrapper.ZLIB, dictionary, false, 0);
    }

    /**
     * Creates a new instance with the specified preset dictionary and maximum buffer allocation.
     * The wrapper is always {@link ZlibWrapper#ZLIB} because it is the only format that
     * supports the preset dictionary.
     *
     * @param maxAllocation
     *          Maximum size of the decompression buffer. Must be >= 0.
     *          If zero, maximum size is decided by the {@link ByteBufAllocator}.
     */
    public JdkZlibDecoder(byte[] dictionary, int maxAllocation) {
        this(ZlibWrapper.ZLIB, dictionary, false, maxAllocation);
    }

    /**
     * Creates a new instance with the specified wrapper.
     * Be aware that only {@link ZlibWrapper#GZIP}, {@link ZlibWrapper#ZLIB} and {@link ZlibWrapper#NONE} are
     * supported atm.
     */
    public JdkZlibDecoder(ZlibWrapper wrapper) {
        this(wrapper, null, false, 0);
    }

    /**
     * Creates a new instance with the specified wrapper and maximum buffer allocation.
     * Be aware that only {@link ZlibWrapper#GZIP}, {@link ZlibWrapper#ZLIB} and {@link ZlibWrapper#NONE} are
     * supported atm.
     *
     * @param maxAllocation
     *          Maximum size of the decompression buffer. Must be >= 0.
     *          If zero, maximum size is decided by the {@link ByteBufAllocator}.
     */
    public JdkZlibDecoder(ZlibWrapper wrapper, int maxAllocation) {
        this(wrapper, null, false, maxAllocation);
    }

    public JdkZlibDecoder(ZlibWrapper wrapper, boolean decompressConcatenated) {
        this(wrapper, null, decompressConcatenated, 0);
    }

    public JdkZlibDecoder(ZlibWrapper wrapper, boolean decompressConcatenated, int maxAllocation) {
        this(wrapper, null, decompressConcatenated, maxAllocation);
    }

    public JdkZlibDecoder(boolean decompressConcatenated) {
        this(ZlibWrapper.GZIP, null, decompressConcatenated, 0);
    }

    public JdkZlibDecoder(boolean decompressConcatenated, int maxAllocation) {
        this(ZlibWrapper.GZIP, null, decompressConcatenated, maxAllocation);
    }

    private JdkZlibDecoder(ZlibWrapper wrapper, byte[] dictionary, boolean decompressConcatenated, int maxAllocation) {
        super(maxAllocation);

        ObjectUtil.checkNotNull(wrapper, "wrapper");

        this.decompressConcatenated = decompressConcatenated;
        switch (wrapper) {
            case GZIP:
                inflater = new Inflater(true);
                crc = ByteBufChecksum.wrapChecksum(new CRC32());
                break;
            case NONE:
                inflater = new Inflater(true);
                crc = null;
                break;
            case ZLIB:
                inflater = new Inflater();
                crc = null;
                break;
            case ZLIB_OR_NONE:
                // Postpone the decision until decode(...) is called.
                decideZlibOrNone = true;
                crc = null;
                break;
            default:
                throw new IllegalArgumentException("Only GZIP or ZLIB is supported, but you used " + wrapper);
        }
        this.dictionary = dictionary;
    }

    @Override
    public boolean isClosed() {
        return finished;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (finished) {
            // Skip data received after finished.
            in.skipBytes(in.readableBytes());
            return;
        }

        int readableBytes = in.readableBytes();
        if (readableBytes == 0) {
            return;
        }

        if (decideZlibOrNone) {
            // First two bytes are needed to decide if it's a ZLIB stream.
            if (readableBytes < 2) {
                return;
            }

            boolean nowrap = !looksLikeZlib(in.getShort(in.readerIndex()));
            inflater = new Inflater(nowrap);
            decideZlibOrNone = false;
        }

        if (crc != null) {
            if (gzipState != GzipState.HEADER_END) {
                if (gzipState == GzipState.FOOTER_START) {
                    if (!handleGzipFooter(in)) {
                        // Either there was not enough data or the input is finished.
                        return;
                    }
                    // If we consumed the footer we will start with the header again.
                    assert gzipState == GzipState.HEADER_START;
                }
                if (!readGZIPHeader(in)) {
                    // There was not enough data readable to read the GZIP header.
                    return;
                }
                // Some bytes may have been consumed, and so we must re-set the number of readable bytes.
                readableBytes = in.readableBytes();
                if (readableBytes == 0) {
                    return;
                }
            }
        }

        if (inflater.needsInput()) {
            if (in.hasArray()) {
                inflater.setInput(in.array(), in.arrayOffset() + in.readerIndex(), readableBytes);
            } else {
                byte[] array = new byte[readableBytes];
                in.getBytes(in.readerIndex(), array);
                inflater.setInput(array);
            }
        }

        ByteBuf decompressed = prepareDecompressBuffer(ctx, null, inflater.getRemaining() << 1);
        try {
            boolean readFooter = false;
            while (!inflater.needsInput()) {
                byte[] outArray = decompressed.array();
                int writerIndex = decompressed.writerIndex();
                int outIndex = decompressed.arrayOffset() + writerIndex;
                int writable = decompressed.writableBytes();
                int outputLength = inflater.inflate(outArray, outIndex, writable);
                if (outputLength > 0) {
                    decompressed.writerIndex(writerIndex + outputLength);
                    if (crc != null) {
                        crc.update(outArray, outIndex, outputLength);
                    }
                } else  if (inflater.needsDictionary()) {
                    if (dictionary == null) {
                        throw new DecompressionException(
                                "decompression failure, unable to set dictionary as non was specified");
                    }
                    inflater.setDictionary(dictionary);
                }

                if (inflater.finished()) {
                    if (crc == null) {
                        finished = true; // Do not decode anymore.
                    } else {
                        readFooter = true;
                    }
                    break;
                } else {
                    decompressed = prepareDecompressBuffer(ctx, decompressed, inflater.getRemaining() << 1);
                }
            }

            in.skipBytes(readableBytes - inflater.getRemaining());

            if (readFooter) {
                gzipState = GzipState.FOOTER_START;
                handleGzipFooter(in);
            }
        } catch (DataFormatException e) {
            throw new DecompressionException("decompression failure", e);
        } finally {
            if (decompressed.isReadable()) {
                out.add(decompressed);
            } else {
                decompressed.release();
            }
        }
    }

    private boolean handleGzipFooter(ByteBuf in) {
        if (readGZIPFooter(in)) {
            finished = !decompressConcatenated;

            if (!finished) {
                inflater.reset();
                crc.reset();
                gzipState = GzipState.HEADER_START;
                return true;
            }
        }
        return false;
    }

    @Override
    protected void decompressionBufferExhausted(ByteBuf buffer) {
        finished = true;
    }

    @Override
    protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved0(ctx);
        if (inflater != null) {
            inflater.end();
        }
    }

    private boolean readGZIPHeader(ByteBuf in) {
        switch (gzipState) {
            case HEADER_START:
                if (in.readableBytes() < 10) {
                    return false;
                }
                // read magic numbers
                int magic0 = in.readByte();
                int magic1 = in.readByte();

                if (magic0 != 31) {
                    throw new DecompressionException("Input is not in the GZIP format");
                }
                crc.update(magic0);
                crc.update(magic1);

                int method = in.readUnsignedByte();
                if (method != Deflater.DEFLATED) {
                    throw new DecompressionException("Unsupported compression method "
                            + method + " in the GZIP header");
                }
                crc.update(method);

                flags = in.readUnsignedByte();
                crc.update(flags);

                if ((flags & FRESERVED) != 0) {
                    throw new DecompressionException(
                            "Reserved flags are set in the GZIP header");
                }

                // mtime (int)
                crc.update(in, in.readerIndex(), 4);
                in.skipBytes(4);

                crc.update(in.readUnsignedByte()); // extra flags
                crc.update(in.readUnsignedByte()); // operating system

                gzipState = GzipState.FLG_READ;
                // fall through
            case FLG_READ:
                if ((flags & FEXTRA) != 0) {
                    if (in.readableBytes() < 2) {
                        return false;
                    }
                    int xlen1 = in.readUnsignedByte();
                    int xlen2 = in.readUnsignedByte();
                    crc.update(xlen1);
                    crc.update(xlen2);

                    xlen |= xlen1 << 8 | xlen2;
                }
                gzipState = GzipState.XLEN_READ;
                // fall through
            case XLEN_READ:
                if (xlen != -1) {
                    if (in.readableBytes() < xlen) {
                        return false;
                    }
                    crc.update(in, in.readerIndex(), xlen);
                    in.skipBytes(xlen);
                }
                gzipState = GzipState.SKIP_FNAME;
                // fall through
            case SKIP_FNAME:
                if (!skipIfNeeded(in, FNAME)) {
                    return false;
                }
                gzipState = GzipState.SKIP_COMMENT;
                // fall through
            case SKIP_COMMENT:
                if (!skipIfNeeded(in, FCOMMENT)) {
                    return false;
                }
                gzipState = GzipState.PROCESS_FHCRC;
                // fall through
            case PROCESS_FHCRC:
                if ((flags & FHCRC) != 0) {
                    if (!verifyCrc(in)) {
                        return false;
                    }
                }
                crc.reset();
                gzipState = GzipState.HEADER_END;
                // fall through
            case HEADER_END:
                return true;
            default:
                throw new IllegalStateException();
        }
    }

    /**
     * Skip bytes in the input if needed until we find the end marker {@code 0x00}.
     * @param   in the input
     * @param   flagMask the mask that should be present in the {@code flags} when we need to skip bytes.
     * @return  {@code true} if the operation is complete and we can move to the next state, {@code false} if we need
     *          the retry again once we have more readable bytes.
     */
    private boolean skipIfNeeded(ByteBuf in, int flagMask) {
        if ((flags & flagMask) != 0) {
            for (;;) {
                if (!in.isReadable()) {
                    // We didnt find the end yet, need to retry again once more data is readable
                    return false;
                }
                int b = in.readUnsignedByte();
                crc.update(b);
                if (b == 0x00) {
                    break;
                }
            }
        }
        // Skip is handled, we can move to the next processing state.
        return true;
    }

    /**
     * Read the GZIP footer.
     *
     * @param   in the input.
     * @return  {@code true} if the footer could be read, {@code false} if the read could not be performed as
     *          the input {@link ByteBuf} doesn't have enough readable bytes (8 bytes).
     */
    private boolean readGZIPFooter(ByteBuf in) {
        if (in.readableBytes() < 8) {
            return false;
        }

        boolean enoughData = verifyCrc(in);
        assert enoughData;

        // read ISIZE and verify
        int dataLength = 0;
        for (int i = 0; i < 4; ++i) {
            dataLength |= in.readUnsignedByte() << i * 8;
        }
        int readLength = inflater.getTotalOut();
        if (dataLength != readLength) {
            throw new DecompressionException(
                    "Number of bytes mismatch. Expected: " + dataLength + ", Got: " + readLength);
        }
        return true;
    }

    /**
     * Verifies CRC.
     *
     * @param   in the input.
     * @return  {@code true} if verification could be performed, {@code false} if verification could not be performed as
     *          the input {@link ByteBuf} doesn't have enough readable bytes (4 bytes).
     */
    private boolean verifyCrc(ByteBuf in) {
        if (in.readableBytes() < 4) {
            return false;
        }
        long crcValue = 0;
        for (int i = 0; i < 4; ++i) {
            crcValue |= (long) in.readUnsignedByte() << i * 8;
        }
        long readCrc = crc.getValue();
        if (crcValue != readCrc) {
            throw new DecompressionException(
                    "CRC value mismatch. Expected: " + crcValue + ", Got: " + readCrc);
        }
        return true;
    }

    /*
     * Returns true if the cmf_flg parameter (think: first two bytes of a zlib stream)
     * indicates that this is a zlib stream.
     *

     * You can lookup the details in the ZLIB RFC:
     * RFC 1950.
     */
    private static boolean looksLikeZlib(short cmf_flg) {
        return (cmf_flg & 0x7800) == 0x7800 &&
                cmf_flg % 31 == 0;
    }
}


text:
#ifndef C4_TEST_CALLBACKS_TESTER_HPP_
#define C4_TEST_CALLBACKS_TESTER_HPP_

#ifndef RYML_SINGLE_HEADER
#include "c4/yml/common.hpp"
#endif
#include <vector>
#include <iostream>

namespace c4 {
namespace yml {

struct CallbacksTester
{
    std::vector<char> memory_pool;
    const char *id;
    size_t num_allocs, alloc_size;
    size_t num_deallocs, dealloc_size;

    CallbacksTester(const char *id_="notset", size_t sz=10u * 1024u) // 10KB
        : memory_pool(sz)
        , id(id_)
        , num_allocs()
        , alloc_size()
        , num_deallocs()
        , dealloc_size()
    {
    }

    // checking
    ~CallbacksTester()
    {
        check();
    }

    void check()
    {
        std::cout << "size: alloc=" << alloc_size << " dealloc=" << dealloc_size << std::endl;
        std::cout << "count: #allocs=" << num_allocs << " #deallocs=" << num_deallocs << std::endl;
        RYML_CHECK(num_allocs == num_deallocs);
        RYML_CHECK(alloc_size == dealloc_size);
    }

    Callbacks callbacks() const
    {
        Callbacks cb = get_callbacks();
        cb.m_user_data = (void*) this;
        cb.m_allocate = [](size_t len, void *, void *data){ return ((CallbacksTester*) data)->allocate(len); };
        cb.m_free = [](void *mem, size_t len, void *data){ return ((CallbacksTester*) data)->free(mem, len); };
        return cb;
    }

    void *allocate(size_t len)
    {
        std::cout << "alloc[" << num_allocs << "]=" << len << "B\n";
        void *ptr = &memory_pool[alloc_size];
        alloc_size += len;
        ++num_allocs;
        RYML_CHECK(alloc_size < memory_pool.size());
        return ptr;
    }

    void free(void *mem, size_t len)
    {
        RYML_CHECK((char*)mem     >= &memory_pool.front() && (char*)mem     <  &memory_pool.back());
        RYML_CHECK((char*)mem+len >= &memory_pool.front() && (char*)mem+len <= &memory_pool.back());
        std::cout << "free[" << num_deallocs << "]=" << len << "B\n";
        dealloc_size += len;
        ++num_deallocs;
        // no need to free here
    }
};

} // namespace yml
} // namespace c4

#endif /* C4_TEST_CALLBACKS_TESTER_HPP_ */

redpajama_set_name: RedPajamaGithub


text:
if(NOT DEFINED CMAKE_INSTALL_PREFIX)
  set(CMAKE_INSTALL_PREFIX "/usr/local")
endif()
string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")

# Set the install configuration name.
if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
  if(BUILD_TYPE)
    string(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
           CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
  else()
    set(CMAKE_INSTALL_CONFIG_NAME "")
  endif()
  message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
endif()

# Set the component getting installed.
if(NOT CMAKE_INSTALL_COMPONENT)
  if(COMPONENT)
    message(STATUS "Install component: \"${COMPONENT}\"")
    set(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
  else()
    set(CMAKE_INSTALL_COMPONENT)
  endif()
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib" TYPE STATIC_LIBRARY FILES "/Users/pmyers/Projects/tacmap/ThirdParty/googletest/libgtest.a")
  if(EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libgtest.a" AND
     NOT IS_SYMLINK "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libgtest.a")
    execute_process(COMMAND "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ranlib" "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libgtest.a")
  endif()
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib" TYPE STATIC_LIBRARY FILES "/Users/pmyers/Projects/tacmap/ThirdParty/googletest/libgtest_main.a")
  if(EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libgtest_main.a" AND
     NOT IS_SYMLINK "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libgtest_main.a")
    execute_process(COMMAND "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ranlib" "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libgtest_main.a")
  endif()
endif()

if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/include" TYPE DIRECTORY FILES "/Users/pmyers/Projects/tacmap/ThirdParty/googletest/include/gtest")
endif()

if(CMAKE_INSTALL_COMPONENT)
  set(CMAKE_INSTALL_MANIFEST "install_manifest_${CMAKE_INSTALL_COMPONENT}.txt")
else()
  set(CMAKE_INSTALL_MANIFEST "install_manifest.txt")
endif()

string(REPLACE ";" "\n" CMAKE_INSTALL_MANIFEST_CONTENT
       "${CMAKE_INSTALL_MANIFEST_FILES}")
file(WRITE "/Users/pmyers/Projects/tacmap/ThirdParty/googletest/${CMAKE_INSTALL_MANIFEST}"
     "${CMAKE_INSTALL_MANIFEST_CONTENT}")


text:
/*
 * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
 * at the root of this project for more details.
 */
package io.github.nucleuspowered.nucleus.modules.ignore.commands;

import com.google.common.collect.Maps;
import io.github.nucleuspowered.nucleus.Nucleus;
import io.github.nucleuspowered.nucleus.internal.annotations.RunAsync;
import io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers;
import io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions;
import io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand;
import io.github.nucleuspowered.nucleus.internal.command.AbstractCommand;
import io.github.nucleuspowered.nucleus.internal.command.NucleusParameters;
import io.github.nucleuspowered.nucleus.internal.docgen.annotations.EssentialsEquivalent;
import io.github.nucleuspowered.nucleus.internal.permissions.PermissionInformation;
import io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel;
import io.github.nucleuspowered.nucleus.modules.ignore.datamodules.IgnoreUserDataModule;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.args.CommandElement;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.util.annotation.NonnullByDefault;

import java.util.Map;

@RunAsync
@NoModifiers
@RegisterCommand("ignore")
@Permissions(suggestedLevel = SuggestedLevel.USER)
@EssentialsEquivalent("ignore")
@NonnullByDefault
public class IgnoreCommand extends AbstractCommand<Player> {

    @Override
    protected Map<String, PermissionInformation> permissionSuffixesToRegister() {
        Map<String, PermissionInformation> m = Maps.newHashMap();
        m.put("exempt.chat", PermissionInformation.getWithTranslation("permission.ignore.chat", SuggestedLevel.MOD));
        return m;
    }

    @Override
    public CommandElement[] getArguments() {
        return new CommandElement[] {
                NucleusParameters.ONE_USER,
                NucleusParameters.OPTIONAL_ONE_TRUE_FALSE
        };
    }

    @Override
    public CommandResult executeCommand(Player src, CommandContext args, Cause cause) {
        // Get the target
        User target = args.<User>getOne(NucleusParameters.Keys.USER).get();

        if (target.equals(src)) {
            src.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.ignore.self"));
            return CommandResult.empty();
        }

        IgnoreUserDataModule inu = Nucleus.getNucleus().getUserDataManager().getUnchecked(src).get(IgnoreUserDataModule.class);

        if (this.permissions.testSuffix(target, "exempt.chat")) {
            // Make sure they are removed.
            inu.removeFromIgnoreList(target.getUniqueId());
            src.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.ignore.exempt", target.getName()));
            return CommandResult.empty();
        }

        // Ok, we can ignore or unignore them.
        boolean ignore = args.<Boolean>getOne(NucleusParameters.Keys.BOOL).orElse(!inu.getIgnoreList().contains(target.getUniqueId()));

        if (ignore) {
            inu.addToIgnoreList(target.getUniqueId());
            src.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.ignore.added", target.getName()));
        } else {
            inu.removeFromIgnoreList(target.getUniqueId());
            src.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.ignore.remove", target.getName()));
        }

        return CommandResult.success();
    }
}


text:
class Derivative
  attr_reader :type, :image

  def initialize(type, image)
    @type = type
    @image = image
  end
end


text:
CampDialogLayer = class("CampDialogLayer", function ( )
	return cc.Layer:create()
end)

CampDialogLayer.instance = nil

local function buySoldierTemple(self, prefix)
	local goldCount = GM:getGoldCount()
	local ui = self:getChildByName("UI")
	local campLevel = GM:getLevel("Camp")
	local cost = GM:getSoldierCost(prefix)
	local soldierNum   = GM:getSoldierNum(prefix)
	local soldierLimit = GM:getSoldierLimit(prefix)
	if soldierNum >= soldierLimit then
		GM:showNotice("请升级兵营。", self)
		return
	end
	if goldCount < cost then
		GM:showNotice("金币不足。", self)
		return
	end
	GM:setGoldChange(-cost)
	GM:setSoldierNum(prefix)
	local soldierCount = ccui.Helper:seekWidgetByName(ui, prefix .. "Count")
	soldierCount:setString((soldierNum + 1) .. "/" .. soldierLimit)
	local wgGoldCount = ccui.Helper:seekWidgetByName(ui, "GoldCount")
	wgGoldCount:setString(GM:getGoldCount())
end

function CampDialogLayer.buyCallback(self, sender)
	local labLevel = researchLabSprite.level
	local name = sender:getName()
	if name == "BuyFighterButton" then
		buySoldierTemple(self, "Fighter")
	elseif name == "BuyBowmanButton" then
		if labLevel < 2 then
			GM:showNotice("请升级研究所。", self)
			return
		end
		buySoldierTemple(self, "Bowman")
	elseif name == "BuyGunnerButton" then
		if labLevel < 3 then
			GM:showNotice("请升级研究所。", self)
			return
		end
		buySoldierTemple(self, "Gunner")
	elseif name == "BuyMeatShieldButton" then
		if labLevel < 4 then
			GM:showNotice("请升级研究所。", self)
			return
		end
		buySoldierTemple(self, "MeatShield")
	end
end

function CampDialogLayer.infoCallback(sender)
	-- 设置当前Layer以便关闭SoldierInfoDialogLayer时,把scene._dialogLayer设置回来
	local campDialogLayer = scene._dialogLayer
	campDialogLayer:setName("CampDialogLayer")
	local name = sender:getName()
	if name == "FighterInfoButton" then
		GM:showDialogLayer(SoldierInfoDialogLayer, 1)
	elseif name == "BowmanInfoButton" then
		GM:showDialogLayer(SoldierInfoDialogLayer, 2)
	elseif name == "GunnerInfoButton" then
		GM:showDialogLayer(SoldierInfoDialogLayer, 3)
	elseif name == "MeatShieldInfoButton" then
		GM:showDialogLayer(SoldierInfoDialogLayer, 4)
	end
end

function CampDialogLayer:addListener( )
	local ui = self:getChildByName("UI")
	-- 关闭按钮
	local btnClose = ccui.Helper:seekWidgetByName(ui, "CloseButton")
	btnClose:addClickEventListener(GM.closeDialogLayer)
	-- 信息按钮
	local btnFighterInfo = ccui.Helper:seekWidgetByName(ui, "FighterInfoButton")
	local btnBowmanInfo  = ccui.Helper:seekWidgetByName(ui, "BowmanInfoButton")
	local btnGunnerInfo  = ccui.Helper:seekWidgetByName(ui, "GunnerInfoButton")
	local btnMeatInfo    = ccui.Helper:seekWidgetByName(ui, "MeatShieldInfoButton")
	btnFighterInfo:addClickEventListener(CampDialogLayer.infoCallback)
	btnBowmanInfo:addClickEventListener(CampDialogLayer.infoCallback)
	btnGunnerInfo:addClickEventListener(CampDialogLayer.infoCallback)
	btnMeatInfo:addClickEventListener(CampDialogLayer.infoCallback)
	-- 训练按钮
	local btnFighterBuy = ccui.Helper:seekWidgetByName(ui, "BuyFighterButton")
	local btnBowmanBuy  = ccui.Helper:seekWidgetByName(ui, "BuyBowmanButton")
	local btnGunnerBuy  = ccui.Helper:seekWidgetByName(ui, "BuyGunnerButton")
	local btnMeatBuy    = ccui.Helper:seekWidgetByName(ui, "BuyMeatShieldButton")
	btnFighterBuy:addClickEventListener(function (...)
		CampDialogLayer.buyCallback(self, ...)
	end)
	btnBowmanBuy:addClickEventListener(function (...)
		CampDialogLayer.buyCallback(self, ...)
	end)
	btnGunnerBuy:addClickEventListener(function (...)
		CampDialogLayer.buyCallback(self, ...)
	end)
	btnMeatBuy:addClickEventListener(function (...)
		CampDialogLayer.buyCallback(self, ...)
	end)
end

local function showSoldierPanelTemple(ui, self, prefix, minLabLevel)
	local labLevel = researchLabSprite.level
	local wgCost  = ccui.Helper:seekWidgetByName(ui, prefix .. "GoldRequire")
	local soldierLevel = GM:getLevel(prefix)
	local cost    = DM[prefix .. "Info"].cost[soldierLevel]
	local wgLevel = ccui.Helper:seekWidgetByName(ui, prefix .. "Level")
	wgCost:setString(cost)
	wgLevel:setString(soldierLevel)
	if labLevel < minLabLevel then
		local soldier = ccui.Helper:seekWidgetByName(ui, "Soldier_" .. prefix)
		local btnInfo = ccui.Helper:seekWidgetByName(ui, prefix .. "InfoButton")
		local btnBuy  = ccui.Helper:seekWidgetByName(ui, "Buy" .. prefix .. "Button")
		local children = soldier:getChildren()
		for i = 1, #children do
			children[i]:setColor(cc.c3b(160, 160, 160))
		end
		btnBuy:setColor(cc.c3b(160, 160, 160))
		btnInfo:setColor(cc.c3b(160, 160, 160))
	else
		local wgCount = ccui.Helper:seekWidgetByName(ui, prefix .. "Count")
		local campLevel = self.instance:getLevel()
		wgCount:setString(GM:getSoldierNum(prefix) .. "/" .. GM:getSoldierLimit(prefix))
	end
end

function CampDialogLayer:showDialog( )
	-- Action
	local scale = cc.ScaleTo:create(0.3, 1)
	local act   = cc.EaseBackOut:create(scale)
	self:runAction(act)

	local ui = ccs.GUIReader:getInstance():widgetFromJsonFile(UI_DIALOG_CAMP)
	local bg = cc.Sprite:create(IMG_GRAY_BG)
	bg:setScale(size.width / 1000, size.height / 1000)
	bg:setOpacity(128)
	bg:setPosition(size.width / 2, size.height / 2)
	self:addChild(bg, ORD_BG)
	self:addChild(ui, ORD_BOTTOM, "UI")

	-- 资源数量
	local goldCount = ccui.Helper:seekWidgetByName(ui, "GoldCount")
	local woodCount = ccui.Helper:seekWidgetByName(ui, "WoodCount")
	goldCount:setString(GM:getGoldCount())
	woodCount:setString(DM.Resource.woodCount)

	-- 士兵数量
	showSoldierPanelTemple(ui, self, "Fighter", 1)
	showSoldierPanelTemple(ui, self, "Bowman",  2)
	showSoldierPanelTemple(ui, self, "Gunner",  3)
	showSoldierPanelTemple(ui, self, "MeatShield", 4)

end

function CampDialogLayer:onEnter()
	self:setScale(0)
	self:showDialog()
	self:addListener()
end

function CampDialogLayer:create(instance)
	local campDialogLayer = CampDialogLayer.new()
	self.instance = instance

	campDialogLayer:onEnter()

	return campDialogLayer
end


text:
var AddPointsTool = {
	name: "addPoints",
	description: "Add points to component",
	section: "modify",
	icon: "imgs/mini-icon-points_tool.png",

	enabled: false,
	continuous: false, //add while dragging
	mode: "camera_plane", //"colliders","render_instances","camera_plane","XZ","YZ","XY"
	min_distance: 0.1,
	valid_modes: ["colliders","render_instances","camera_plane","XZ","YZ","XY"],
	color: vec4.fromValues(1,1,1,1), //color and alpha
	size: 1,
	offset: 0,

	last_point: null,
	last_normal: vec3.fromValues(0,1,0),
	click_pos: vec2.create(),
	raycast_options: { normal: true, triangle_collision: true },

	onEnable: function()
	{
	},

	onClick: function()
	{
		this._component = null;
		this.last_point = null;
	},

	inspect: function( inspector )
	{
		inspector.addCombo("Collision mode", this.mode, { values: this.valid_modes, callback: function(v){
			AddPointsTool.mode = v;
		}});
		inspector.addCheckbox("Continuous", this.continuous, function(v) { AddPointsTool.continuous = v; });
		inspector.widgets_per_row = 2;
		inspector.addNumber("Min. distance", this.min_distance, { min: 0, callback: function(v) { AddPointsTool.min_distance = v; } });
		inspector.addNumber("Offset", this.offset, { callback: function(v) { AddPointsTool.offset = v; } });
		inspector.widgets_per_row = 1;
		inspector.addSeparator();
		inspector.addColor("Color", this.color, function(v) { AddPointsTool.color.set(v); });
		inspector.addSlider("Opacity", this.color[3], function(v) { AddPointsTool.color[3] = v; });
		inspector.addNumber("Size", this.size, function(v) { AddPointsTool.size = v; });
		inspector.addSeparator();

		//show components with addPoints method
		var node = SelectionModule.getSelectedNode();
		if(!node)
			node = LS.GlobalScene.root;
		var components = this.getValidComponents( node );
		var components_data = [];
		var selected = null;
		for(var i = 0; i < components.length; i++)
		{
			var component_info = { title: LS.getObjectClassName(components[i]), component: components[i] };
			if(components[i] == this._component)
				selected = component_info;
			components_data.push(component_info);
		}

		if(components_data.length == 1)
			AddPointsTool.setComponent( components_data[0].component );
		inspector.addCombo("Select Component", selected , { values: components_data, callback: function(v){
			if(v)
				AddPointsTool.setComponent( v.component );
			EditorModule.refreshAttributes();
			return;
		}});

		inspector.addButtons("Add Component",["PointCloud","LineCloud"], function(v){
			var component_class = LS.Components[v];
			if(!component_class)
				return;
			var	component = new component_class();
			var node = SelectionModule.getSelectedNode();
			if(!node)
				node = LS.GlobalScene.root;
			UndoModule.saveNodeChangeUndo( node );
			node.addComponent( component );
			AddPointsTool.setComponent( component );
			EditorModule.refreshAttributes();
			return;
		});
		inspector.addButtons("Actions",["Flatten","Set node flags","Clear"], { name_width: 120, callback:function(v){
			if(!AddPointsTool._component)
				return;
			var component = AddPointsTool._component;
			CORE.userAction("component_changed", component );

			if(v == "Clear")
			{
				component.reset();
			}
			else if(v == "Flatten")
			{
				var points = component.points;
				if(points)
				{
					for(var i = 0; i < points.length; ++i)
					{
						var p = points[i];
						if(p.length > 2)
							p[1] = 0;
					}
					component._must_update = true;
				}
			}
			else //set node flags
			{
				component._root.flags.depth_write = false;
			}

			EditorModule.refreshAttributes();
		}});
		inspector.addSeparator();

		if(SelectionModule.selection && SelectionModule.selection.instance && SelectionModule.selection.instance.getPointRef)
		{
			var ref = SelectionModule.selection.instance.getPointRef( SelectionModule.selection.info );
			if(ref)
			{
				inspector.widgets_per_row = 2;
				inspector.addVector3("Selected", ref , { width: "calc( 100 % - 40px )", callback: function(v){ ref[0] = v[0]; ref[1] = v[1]; ref[2] = v[2]; }});
				inspector.addButton(null, TRASH_ICON_CODE, { width: "40px", callback: function(){
					CORE.userAction("component_changed", SelectionModule.selection.instance );
					SelectionModule.selection.instance.removePoint( SelectionModule.selection.info );
					SelectionModule.selection = null;
				}});
				inspector.widgets_per_row = 1;
			}
		}

		inspector.addSeparator();
		if( this._component )
			inspector.showComponent( this._component );
	},

	mousedown: function(e) {
		this.click_pos[0] = e.canvasx;
		this.click_pos[1] = e.canvasy;

		if(!this._component)
		{
			var node = SelectionModule.getSelectedNode();
			if(!node)
				node = LS.GlobalScene.root;
			var components = this.getValidComponents( node );
			this.setComponent( components[0] );

			if(!this._component)
			{
				LiteGUI.alert("No component found in node " + node.name + " that has addPoints support. Add PointsCloud Component.");
				return;
			}
		}

		if(e.which == 1 && !e.ctrlKey && !this.continuous) //continuos is add while dragging, like painting
		{
			//test first closer point
			var index = this.findNearestPointIndex(this.click_pos, 20);
			if(index != -1)
			{
				console.log("selected point");
				SelectionModule.setSelection({ instance: this._component, info: index, node: this._component._root });
				return true;
			}

			//if no point, then add
			if(this._component)
				CORE.userAction("component_changed", this._component );
			var point = this.computePoint(e);
			if(point)
				this.addPoint( point );
			return true;
		}
	},

	mousemove: function(e) {

		if(!this._component)
			return;

		if(!this._component._root || !this._component._root.scene)
		{
			this._component = null;
			return;
		}

		if(e.ctrlKey)
			return;

		//test
		if(e.dragging && e.which == 1 && this.continuous)
		{
			var point = this.computePoint(e);
			if(point)
				this.addPoint( point );
		}
		return true;
	},

	mouseup: function(e) {
	},

	setComponent: function( component )
	{
		if(this._component != component )
			this.last_point = null;
		this._component = component;
	},

	getValidComponents: function( node )
	{
		var valid = [];
		var components = node.getComponents();
		for(var i = 0; i < components.length; i++)
		{
			var component = components[i];
			if( !component.addPoint )
				continue;
			valid.push( component );
		}
		return valid;
	},

	findNearestPointIndex: function(pos, max_dist)
	{
		if(max_dist === undefined)
			max_dist = 100000;
		var comp = this._component;
		if(!comp)
			return -1;
		var points = comp.points;
		var model = mat4.create();
		comp._root.transform.getGlobalMatrix(model);
		var camera = RenderModule.getActiveCamera();
		var points = comp.points;
		if(!points)
			return -1;
		var min_dist = 100000;
		var nearest = -1;
		var result = vec3.create();
		for(var i = 0; i < points.length; ++i)
		{
			var point = points[i];
			vec3.transformMat4( result, point, model );
			camera.project(result,null,result);
			//TODO; discard behind
			var dist = vec2.distance(pos, result);
			if( dist > min_dist || dist > max_dist )
				continue;
			min_dist = dist;
			nearest = i;
		}

		return nearest;
	},

	addPoint: function( point )
	{
		if(!point || !this._component)
			return;

		//apply offset
		if(this.offset)
			vec3.scaleAndAdd( point, point, this.last_normal, this.offset );

		if( this._component.in_world_coordinates )
		{
			//convert to local coordinates
			var node = this._component._root;
			var transform = node.transform;
			if(transform)
			{
				var matrix = transform.getGlobalMatrix();
				mat4.invert( matrix, matrix );
				vec3.transformMat4( point, point, matrix );
			}
		}

		if(this.min_distance && this.last_point && vec3.distance( this.last_point, point ) < this.min_distance )
			return;

		this.last_point = point;

		this._component.addPoint( point, this.color, this.size );

		if(this._component.max_points && this._component.num_points && this._component.max_points < this._component.num_points)
			this._component.max_points *= 2;

		EditorModule.updateInspector();
		LS.GlobalScene.refresh();
	},

	computePoint: function(e)
	{
		var camera = ToolUtils.getCamera();
		var ray = camera.getRayInPixel( e.canvasx, e.canvasy );

		if(this.mode == "colliders")
		{
			var collisions = LS.Physics.raycast( ray.origin, ray.direction, this.raycast_options );
			this.last_collisions = collisions;
			if(collisions.length)
			{
				if( collisions[0].normal )
					this.last_normal.set( collisions[0].normal );
				else
					this.last_normal.set([0,0,0]);
				return collisions[0].position;
			}
			return null;
		}

		if(this.mode == "render_instances")
		{
			var collisions = LS.Physics.raycastRenderInstances( ray.origin, ray.direction, this.raycast_options );
			this.last_collisions = collisions;
			if(collisions.length)
			{
				if( collisions[0].normal )
					this.last_normal.set( collisions[0].normal );
				else
					this.last_normal.set([0,0,0]);
				return collisions[0].position;
			}
			return null;
		}

		var plane_center = null;
		var plane_normal = null;

		if(this.mode == "camera_plane")
		{
			plane_center = camera.getCenter();
			plane_normal = camera.getFront();
			vec3.scale( plane_normal, plane_normal, -1 );
		}
		else if(this.mode == "XZ")
		{
			plane_center = [0,0,0];
			plane_normal = [0,1,0];
		}
		else if(this.mode == "XY")
		{
			plane_center = [0,0,0];
			plane_normal = [0,0,1];
		}
		else if(this.mode == "YZ")
		{
			plane_center = [0,0,0];
			plane_normal = [1,0,0];
		}
		else
			return null;

		this.last_normal.set( plane_normal );

		var result = vec3.create();
		if( geo.testRayPlane( ray.origin, ray.direction, plane_center, plane_normal, result ) )
			return result;
		return null;
	},

	renderEditor: function()
	{
	}
};

ToolsModule.registerTool( AddPointsTool );


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE pkgmetadata SYSTEM "http://www.gentoo.org/dtd/metadata.dtd">
<pkgmetadata>
	<maintainer type="person">
		<email>stefantalpalaru@yahoo.com</email>
		<name>Ștefan Talpalaru</name>
	</maintainer>
	<longdescription>
		VMWare Workstation is a virtual machine which can be used to install
		other operating systems in a virtual environment to run on top of Gentoo.
	</longdescription>
	<use>
		<flag name="macos-guests">Support macOS guests.</flag>
		<flag name="modules">Install <pkg>app-emulation/vmware-modules</pkg> in order to run VMs locally.</flag>
		<flag name="ovftool">Install OVF tool.</flag>
		<flag name="vix">Install VIX. The VIX API allows you to write programs and scripts
		that automate virtual machine operations, and run programs or manipulate
		files within guest operating systems.
		</flag>
		<flag name="vmware-tools-darwin">Install VMware Tools for OS X (El Capitan and later) guests.</flag>
		<flag name="vmware-tools-darwinPre15">Install VMware Tools for OS X (up to Yosemite) guests.</flag>
		<flag name="vmware-tools-linux">Install VMware Tools for Linux guests.</flag>
		<flag name="vmware-tools-linuxPreGlibc25">Install VMware Tools for Linux (glibc older than 2.5) guests.</flag>
		<flag name="vmware-tools-netware">Install VMware Tools for Netware guests.</flag>
		<flag name="vmware-tools-solaris">Install VMware Tools for Solaris guests.</flag>
		<flag name="vmware-tools-windows">Install VMware Tools for Windows (Vista and later) guests.</flag>
		<flag name="vmware-tools-winPre2k">Install VMware Tools for Windows (before 2000) guests.</flag>
		<flag name="vmware-tools-winPreVista">Install VMware Tools for Windows (after 2000, before Vista) guests.</flag>
	</use>
	<upstream>
		<remote-id type="github">akhuettel/systemd-vmware</remote-id>
	</upstream>
</pkgmetadata>


text:
<!--

********************************************************************************

WARNING:

    DO NOT EDIT "ghost/README.md"

    IT IS AUTO-GENERATED

    (from the other files in "ghost/" combined with a set of templates)

********************************************************************************

-->

# Quick reference

-	**Maintained by**:
	[the Docker Community](https://github.com/docker-library/ghost)

-	**Where to get help**:
	[the Docker Community Forums](https://forums.docker.com/), [the Docker Community Slack](https://dockr.ly/slack), or [Stack Overflow](https://stackoverflow.com/search?tab=newest&q=docker)

# Supported tags and respective `Dockerfile` links

-	[`4.10.2`, `4.10`, `4`, `latest`](https://github.com/docker-library/ghost/blob/8b76625d2bfca9e2985a4e236220e3a6e04c7781/4/debian/Dockerfile)
-	[`4.10.2-alpine`, `4.10-alpine`, `4-alpine`, `alpine`](https://github.com/docker-library/ghost/blob/8b76625d2bfca9e2985a4e236220e3a6e04c7781/4/alpine/Dockerfile)
-	[`3.42.5`, `3.42`, `3`](https://github.com/docker-library/ghost/blob/5f8c4895e23dc9ee4281aea85ee7f1093a4fbf0c/3/debian/Dockerfile)
-	[`3.42.5-alpine`, `3.42-alpine`, `3-alpine`](https://github.com/docker-library/ghost/blob/5f8c4895e23dc9ee4281aea85ee7f1093a4fbf0c/3/alpine/Dockerfile)

# Quick reference (cont.)

-	**Where to file issues**:
	[https://github.com/docker-library/ghost/issues](https://github.com/docker-library/ghost/issues)

-	**Supported architectures**: ([more info](https://github.com/docker-library/official-images#architectures-other-than-amd64))
	[`amd64`](https://hub.docker.com/r/amd64/ghost/), [`arm32v6`](https://hub.docker.com/r/arm32v6/ghost/), [`arm32v7`](https://hub.docker.com/r/arm32v7/ghost/), [`arm64v8`](https://hub.docker.com/r/arm64v8/ghost/), [`ppc64le`](https://hub.docker.com/r/ppc64le/ghost/), [`s390x`](https://hub.docker.com/r/s390x/ghost/)

-	**Published image artifact details**:
	[repo-info repo's `repos/ghost/` directory](https://github.com/docker-library/repo-info/blob/master/repos/ghost) ([history](https://github.com/docker-library/repo-info/commits/master/repos/ghost))
	(image metadata, transfer size, etc)

-	**Image updates**:
	[official-images repo's `library/ghost` label](https://github.com/docker-library/official-images/issues?q=label%3Alibrary%2Fghost)
	[official-images repo's `library/ghost` file](https://github.com/docker-library/official-images/blob/master/library/ghost) ([history](https://github.com/docker-library/official-images/commits/master/library/ghost))

-	**Source of this description**:
	[docs repo's `ghost/` directory](https://github.com/docker-library/docs/tree/master/ghost) ([history](https://github.com/docker-library/docs/commits/master/ghost))

# Ghost

Ghost is a free and open source blogging platform written in JavaScript and distributed under the MIT License, designed to simplify the process of online publishing for individual bloggers as well as online publications.

> [wikipedia.org/wiki/Ghost_(blogging_platform)](http://en.wikipedia.org/wiki/Ghost_%28blogging_platform%29)

![logo](https://raw.githubusercontent.com/docker-library/docs/c5b6d94dc8f0557925ab37ca43141c0efc5cc363/ghost/logo.png)

# How to use this image

This will start a Ghost instance listening on the default Ghost port of 2368.

```console
$ docker run -d --name some-ghost ghost
```

## Custom port

If you'd like to be able to access the instance from the host without the container's IP, standard port mappings can be used:

```console
$ docker run -d --name some-ghost -e url=http://localhost:3001 -p 3001:2368 ghost
```

If all goes well, you'll be able to access your new site on `http://localhost:3001` and `http://localhost:3001/ghost` to access Ghost Admin (or `http://host-ip:3001` and `http://host-ip:3001/ghost`, respectively).

### Upgrading Ghost

You will want to ensure you are running the latest minor version of Ghost before upgrading major versions. Otherwise, you may run into database errors.

For upgrading your Ghost container you will want to mount your data to the appropriate path in the predecessor container (see below): import your content from the admin panel, stop the container, and then re-mount your content to the successor container you are upgrading into; you can then export your content from the admin panel.

## Stateful

Mount your existing content. In this example we also use the Alpine base image.

```console
$ docker run -d --name some-ghost -p 3001:2368 -v /path/to/ghost/blog:/var/lib/ghost/content ghost:alpine
```

### Docker Volume

Alternatively you can use a named [docker volume](https://docs.docker.com/storage/volumes/) instead of a direct host path for `/var/lib/ghost/content`:

```console
$ docker run -d --name some-ghost -v some-ghost-data:/var/lib/ghost/content ghost
```

### SQLite Database

This Docker image for Ghost uses SQLite. There is nothing special to configure.

## Configuration

All Ghost configuration parameters (such as `url`) can be specified via environment variables. See [the Ghost documentation](https://ghost.org/docs/concepts/config/#running-ghost-with-config-env-variables) for details about what configuration is allowed and how to convert a nested configuration key into the appropriate environment variable name:

```console
$ docker run -d --name some-ghost -e url=http://some-ghost.example.com ghost
```

(There are further configuration examples in the `stack.yml` listed below.)

## What is the Node.js version?

When opening a ticket at https://github.com/TryGhost/Ghost/issues it becomes necessary to know the version of Node.js in use:

```console
$ docker exec <container-id> node --version
[node version output]
```

## Note about Ghost-CLI

While the Docker images do have Ghost-CLI available and do use some of its commands to set up the base Ghost image, many of the other Ghost-CLI commands won't work correctly, and really aren't designed/intended to. For more info see [docker-library/ghost#156 (comment)](https://github.com/docker-library/ghost/issues/156#issuecomment-428159861)

## ... via [`docker stack deploy`](https://docs.docker.com/engine/reference/commandline/stack_deploy/) or [`docker-compose`](https://github.com/docker/compose)

Example `stack.yml` for `ghost`:

```yaml
# by default, the Ghost image will use SQLite (and thus requires no separate database container)
# we have used MySQL here merely for demonstration purposes (especially environment-variable-based configuration)

version: '3.1'

services:

  ghost:
    image: ghost:4-alpine
    restart: always
    ports:
      - 8080:2368
    environment:
      # see https://ghost.org/docs/config/#configuration-options
      database__client: mysql
      database__connection__host: db
      database__connection__user: root
      database__connection__password: example
      database__connection__database: ghost
      # this url value is just an example, and is likely wrong for your environment!
      url: http://localhost:8080
      # contrary to the default mentioned in the linked documentation, this image defaults to NODE_ENV=production (so development mode needs to be explicitly specified if desired)
      #NODE_ENV: development

  db:
    image: mysql:5.7
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: example
```

[![Try in PWD](https://github.com/play-with-docker/stacks/raw/cff22438cb4195ace27f9b15784bbb497047afa7/assets/images/button.png)](http://play-with-docker.com?stack=https://raw.githubusercontent.com/docker-library/docs/cd439efd00ac238cdd9dcbb58c2e91e7d46a1ffa/ghost/stack.yml)

Run `docker stack deploy -c stack.yml ghost` (or `docker-compose -f stack.yml up`), wait for it to initialize completely, and visit `http://swarm-ip:8080`, `http://localhost:8080`, or `http://host-ip:8080` (as appropriate).

# Image Variants

The `ghost` images come in many flavors, each designed for a specific use case.

## `ghost:<version>`

This is the defacto image. If you are unsure about what your needs are, you probably want to use this one. It is designed to be used both as a throw away container (mount your source code and start the container to start your app), as well as the base to build other images off of.

## `ghost:<version>-alpine`

This image is based on the popular [Alpine Linux project](https://alpinelinux.org), available in [the `alpine` official image](https://hub.docker.com/_/alpine). Alpine Linux is much smaller than most distribution base images (~5MB), and thus leads to much slimmer images in general.

This variant is useful when final image size being as small as possible is your primary concern. The main caveat to note is that it does use [musl libc](https://musl.libc.org) instead of [glibc and friends](https://www.etalabs.net/compare_libcs.html), so software will often run into issues depending on the depth of their libc requirements/assumptions. See [this Hacker News comment thread](https://news.ycombinator.com/item?id=10782897) for more discussion of the issues that might arise and some pro/con comparisons of using Alpine-based images.

To minimize image size, it's uncommon for additional related tools (such as `git` or `bash`) to be included in Alpine-based images. Using this image as a base, add the things you need in your own Dockerfile (see the [`alpine` image description](https://hub.docker.com/_/alpine/) for examples of how to install packages if you are unfamiliar).

# License

View [license information](https://ghost.org/license/) for the software contained in this image.

As with all Docker images, these likely also contain other software which may be under other licenses (such as Bash, etc from the base distribution, along with any direct or indirect dependencies of the primary software being contained).

Some additional license information which was able to be auto-detected might be found in [the `repo-info` repository's `ghost/` directory](https://github.com/docker-library/repo-info/tree/master/repos/ghost).

As for any pre-built image usage, it is the image user's responsibility to ensure that any use of this image complies with any relevant licenses for all software contained within.


text:
package com.alternativepayments.apimocks;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;

import javax.ws.rs.core.Response.Status;

import com.alternativepayments.AlternativePaymentClient;
import com.github.tomakehurst.wiremock.client.WireMock;

public class CustomerErrorApiMock {

    private CustomerErrorApiMock() {

    }

    public static void expectApiErrorUpperCase() {
        WireMock.stubFor(
                get(urlMatching("/api/customers/error_upper_case"))
                .withHeader("Authorization", containing(""))
                .withHeader("User-Agent", equalTo("AlternativePayments Java SDK v" + AlternativePaymentClient.VERSION))
                .willReturn(aResponse()
                        .withStatus(Status.PAYMENT_REQUIRED.getStatusCode())
                        .withHeader("Content-Type", "application/json")
                        .withBodyFile("error/api_error.json")));
    }

    public static void expectApiErrorLowerCase() {
        WireMock.stubFor(
                get(urlMatching("/api/customers/error_lower_case"))
                .withHeader("Authorization", containing(""))
                .withHeader("User-Agent", equalTo("AlternativePayments Java SDK v" + AlternativePaymentClient.VERSION))
                .willReturn(aResponse()
                        .withStatus(Status.PAYMENT_REQUIRED.getStatusCode())
                        .withHeader("Content-Type", "application/json")
                        .withBodyFile("error/api_error.json")));
    }

    public static void expectUnsupportedError() {
        WireMock.stubFor(
                get(urlMatching("/api/customers/unsupported_error"))
                .withHeader("Authorization", containing(""))
                .withHeader("User-Agent", equalTo("AlternativePayments Java SDK v" + AlternativePaymentClient.VERSION))
                .willReturn(aResponse()
                        .withStatus(Status.INTERNAL_SERVER_ERROR.getStatusCode())
                        .withHeader("Content-Type", "application/json")
                        .withBodyFile("error/internal_server_error.json")));
    }

    public static void expectPaymentError() {
        WireMock.stubFor(
                get(urlMatching("/api/customers/payment_error"))
                .withHeader("Authorization", containing(""))
                .withHeader("User-Agent", equalTo("AlternativePayments Java SDK v" + AlternativePaymentClient.VERSION))
                .willReturn(aResponse()
                        .withStatus(Status.PAYMENT_REQUIRED.getStatusCode())
                        .withHeader("Content-Type", "application/json")
                        .withBodyFile("error/payment_error_void.json")));
    }

    public static void expectCustomerOlderError() {
        WireMock.stubFor(
                get(urlMatching("/api/customers/customer_older_error"))
                .withHeader("Authorization", containing(""))
                .withHeader("User-Agent", equalTo("AlternativePayments Java SDK v" + AlternativePaymentClient.VERSION))
                .willReturn(aResponse()
                        .withStatus(Status.PAYMENT_REQUIRED.getStatusCode())
                        .withHeader("Content-Type", "application/json")
                        .withBodyFile("error/payment_error_customer_age.json")));
    }

    public static void expectApiErrorNotFound() {
        WireMock.stubFor(
                get(urlMatching("/api/customers/not_found"))
                .withHeader("Authorization", containing(""))
                .withHeader("User-Agent", equalTo("AlternativePayments Java SDK v" + AlternativePaymentClient.VERSION))
                .willReturn(aResponse()
                        .withStatus(Status.PAYMENT_REQUIRED.getStatusCode())
                        .withHeader("Content-Type", "application/json")
                        .withBodyFile("error/api_error_not_found.json")));
    }

    public static void expectApiErrorInternalServerError() {
        WireMock.stubFor(
                get(urlMatching("/api/customers/internal_server_error"))
                .withHeader("Authorization", containing(""))
                .withHeader("User-Agent", equalTo("AlternativePayments Java SDK v" + AlternativePaymentClient.VERSION))
                .willReturn(aResponse()
                        .withStatus(Status.PAYMENT_REQUIRED.getStatusCode())
                        .withHeader("Content-Type", "application/json")
                        .withBodyFile("error/api_error_internal.json")));
    }

    public static void expectApiErrorAcquirerError() {
        WireMock.stubFor(
                get(urlMatching("/api/customers/acquirer_error"))
                .withHeader("Authorization", containing(""))
                .withHeader("User-Agent", equalTo("AlternativePayments Java SDK v" + AlternativePaymentClient.VERSION))
                .willReturn(aResponse()
                        .withStatus(Status.PAYMENT_REQUIRED.getStatusCode())
                        .withHeader("Content-Type", "application/json")
                        .withBodyFile("error/acquirer_down_error.json")));
    }

    public static void expectInvalidParameterSentError() {
        WireMock.stubFor(
                get(urlMatching("/api/customers/invalid_object_sent"))
                .withHeader("Authorization", containing(""))
                .withHeader("User-Agent", equalTo("AlternativePayments Java SDK v" + AlternativePaymentClient.VERSION))
                .willReturn(aResponse()
                        .withStatus(Status.BAD_REQUEST.getStatusCode())
                        .withHeader("Content-Type", "application/json")
                        .withBodyFile("error/invalid_parameter_error.json")));
    }

}


text:
#ifndef __MTYPE_H
#define __MTYPE_H

#include <time.h>

#define	FAR
#define	NEAR
#define WINAPI

typedef long LONG;
typedef int BOOL;
typedef float FLOAT;
typedef double DOUBLE;
typedef int INT;
typedef short SHORT;
typedef unsigned long ULONG;
typedef ULONG *PULONG;
typedef unsigned short USHORT;
typedef USHORT *PUSHORT;
typedef unsigned char UCHAR;
typedef char TCHAR;
typedef UCHAR *PUCHAR;
typedef char *PSZ;
typedef char *LPTSTR;
typedef const char *LPCTSTR;
typedef unsigned long DWORD;
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef FLOAT *PFLOAT;
typedef BOOL NEAR *PBOOL;
typedef BOOL FAR *LPBOOL;
typedef BYTE NEAR *PBYTE;
typedef BYTE FAR *LPBYTE;
typedef int NEAR *PINT;
typedef int FAR *LPINT;
typedef WORD NEAR *PWORD;
typedef WORD FAR *LPWORD;
typedef long FAR *LPLONG;
typedef DWORD NEAR *PDWORD;
typedef DWORD FAR *LPDWORD;
typedef void FAR *LPVOID;
typedef const void FAR *LPCVOID;
typedef unsigned int UINT;
typedef unsigned int *PUINT;
typedef double DATE;
typedef long long INT64;
typedef INT64 NEAR *PINT64;
typedef INT64 FAR *LPINT64;

/////////////////////////////////

typedef DWORD HGLOBAL;
typedef DWORD HWND;
typedef DWORD HMENU;
typedef DWORD COLORREF;
typedef DWORD HICON;
typedef DWORD HANDLE;
typedef void* HINSTANCE;
typedef void (*FARPROC) ();

typedef struct tagRECT
{
    LONG    left;
    LONG    top;
    LONG    right;
    LONG    bottom;
} RECT, *PRECT, NEAR *NPRECT, FAR *LPRECT;

typedef const RECT FAR* LPCRECT;

typedef struct _RECTL       /* rcl */
{
    LONG    left;
    LONG    top;
    LONG    right;
    LONG    bottom;
} RECTL, *PRECTL, *LPRECTL;

typedef const RECTL FAR* LPCRECTL;

typedef struct tagPOINT
{
    LONG  x;
    LONG  y;
} POINT, *PPOINT, NEAR *NPPOINT, FAR *LPPOINT;

typedef struct _POINTL      /* ptl  */
{
    LONG  x;
    LONG  y;
} POINTL, *PPOINTL;

typedef struct tagSIZE
{
    LONG        cx;
    LONG        cy;
} SIZE, *PSIZE, *LPSIZE;

typedef SIZE               SIZEL;
typedef SIZE               *PSIZEL, *LPSIZEL;

typedef struct tagPOINTS
{
    SHORT   x;
    SHORT   y;
} POINTS, *PPOINTS, *LPPOINTS;

/////////////////////////////////

#ifndef NULL
#ifdef __cplusplus
#define NULL    0
#else
#define NULL    ((void *)0)
#endif
#endif

#ifndef FALSE
#define FALSE               0
#endif

#ifndef TRUE
#define TRUE                1
#endif

#ifndef max
#define max(a,b)            (((a) > (b)) ? (a) : (b))
#endif

#ifndef min
#define min(a,b)            (((a) < (b)) ? (a) : (b))
#endif

#ifndef INT_MAX
#define INT_MAX             0x7FFFFFFF
#endif

#define MAKEWORD(a, b)      ((WORD)(((BYTE)(a)) | ((WORD)((BYTE)(b))) << 8))
#define MAKELONG(a, b)      ((LONG)(((WORD)(a)) | ((DWORD)((WORD)(b))) << 16))
#define LOWORD(l)           ((WORD)(l))
#define HIWORD(l)           ((WORD)(((DWORD)(l) >> 16) & 0xFFFF))
#define LOBYTE(w)           ((BYTE)(w))
#define HIBYTE(w)           ((BYTE)(((WORD)(w) >> 8) & 0xFF))

#define _T(string)            string
#define IS_CC(ch)             ((ch & 0x80) != 0)
#define GET_HZ(btLow,btHigh)  (MAKEWORD (btHigh, btLow))

#define MIN_DATE            (-657434L)  // about year 100
#define MAX_DATE            2958465L    // about year 9999

#define ENTRY_LIB_FUNCTION

#ifdef __COMPILE_FNR
    #define _WT(text)	                    _T("")
    #define _CMDS_COUNT(CmdsCount)          0
    #define _CMDS_PTR(CmdsPtr)              NULL
    #define _EVENTS_COUNT(EventsCount)      0
    #define _EVENTS_PTR(EventsPtr)          NULL
    #define _ELEMENTS_COUNT(ElementsCount)  0
    #define _ELEMENTS_PTR(ElementsPtr)      NULL
    #define _FORM_BASE_CLASS	            CWnd
#else
    #define _WT(text)	                    _T(text)
    #define _CMDS_COUNT(CmdsCount)          CmdsCount
    #define _CMDS_PTR(CmdsPtr)              CmdsPtr
    #define _EVENTS_COUNT(EventsCount)      EventsCount
    #define _EVENTS_PTR(EventsPtr)          ((PEVENT_INFO2)EventsPtr)
    #define _ELEMENTS_COUNT(ElementsCount)  ElementsCount
    #define _ELEMENTS_PTR(ElementsPtr)      ElementsPtr
    #define _FORM_BASE_CLASS	            CFrameWnd
#endif

/////////////////////////////////

#endif


text:
using System.Collections;
using Alachisoft.NCache.Common.Net;

namespace Alachisoft.NCache.Caching.Topologies.Clustered
{
    public struct BucketTxfrInfo
    {
        public ArrayList bucketIds;
        public bool isSparsed;
        public Address owner;
        public bool end;

        public BucketTxfrInfo(bool end)
        {
            bucketIds = null;
            owner = null;
            isSparsed = false;
            this.end = end;
        }

        public BucketTxfrInfo(ArrayList bucketIds, bool isSparsed, Address owner)
        {
            this.bucketIds = bucketIds;
            this.isSparsed = isSparsed;
            this.owner = owner;
            this.end = false;
        }
    }
}


text:
import json

from tempest.common import rest_client
from tempest import config
from tempest import exceptions

CONF = config.CONF

class IdentityV3ClientJSON(rest_client.RestClient):

    def __init__(self, auth_provider):
        super(IdentityV3ClientJSON, self).__init__(auth_provider)
        self.service = CONF.identity.catalog_type
        self.endpoint_url = 'adminURL'
        self.api_version = "v3"

    def create_user(self, user_name, **kwargs):
        """Creates a user."""
        password = kwargs.get('password', None)
        email = kwargs.get('email', None)
        en = kwargs.get('enabled', True)
        project_id = kwargs.get('project_id', None)
        description = kwargs.get('description', None)
        domain_id = kwargs.get('domain_id', 'default')
        post_body = {
            'project_id': project_id,
            'description': description,
            'domain_id': domain_id,
            'email': email,
            'enabled': en,
            'name': user_name,
            'password': password
        }
        post_body = json.dumps({'user': post_body})
        resp, body = self.post('users', post_body)
        body = json.loads(body)
        return resp, body['user']

    def update_user(self, user_id, name, **kwargs):
        """Updates a user."""
        resp, body = self.get_user(user_id)
        email = kwargs.get('email', body['email'])
        en = kwargs.get('enabled', body['enabled'])
        project_id = kwargs.get('project_id', body['project_id'])
        description = kwargs.get('description', body['description'])
        domain_id = kwargs.get('domain_id', body['domain_id'])
        post_body = {
            'name': name,
            'email': email,
            'enabled': en,
            'project_id': project_id,
            'id': user_id,
            'domain_id': domain_id,
            'description': description
        }
        post_body = json.dumps({'user': post_body})
        resp, body = self.patch('users/%s' % user_id, post_body)
        body = json.loads(body)
        return resp, body['user']

    def list_user_projects(self, user_id):
        """Lists the projects on which a user has roles assigned."""
        resp, body = self.get('users/%s/projects' % user_id)
        body = json.loads(body)
        return resp, body['projects']

    def get_users(self):
        """Get the list of users."""
        resp, body = self.get("users")
        body = json.loads(body)
        return resp, body['users']

    def get_user(self, user_id):
        """GET a user."""
        resp, body = self.get("users/%s" % user_id)
        body = json.loads(body)
        return resp, body['user']

    def delete_user(self, user_id):
        """Deletes a User."""
        resp, body = self.delete("users/%s" % user_id)
        return resp, body

    def create_project(self, name, **kwargs):
        """Creates a project."""
        description = kwargs.get('description', None)
        en = kwargs.get('enabled', True)
        domain_id = kwargs.get('domain_id', 'default')
        post_body = {
            'description': description,
            'domain_id': domain_id,
            'enabled': en,
            'name': name
        }
        post_body = json.dumps({'project': post_body})
        resp, body = self.post('projects', post_body)
        body = json.loads(body)
        return resp, body['project']

    def list_projects(self):
        resp, body = self.get("projects")
        body = json.loads(body)
        return resp, body['projects']

    def update_project(self, project_id, **kwargs):
        resp, body = self.get_project(project_id)
        name = kwargs.get('name', body['name'])
        desc = kwargs.get('description', body['description'])
        en = kwargs.get('enabled', body['enabled'])
        domain_id = kwargs.get('domain_id', body['domain_id'])
        post_body = {
            'id': project_id,
            'name': name,
            'description': desc,
            'enabled': en,
            'domain_id': domain_id,
        }
        post_body = json.dumps({'project': post_body})
        resp, body = self.patch('projects/%s' % project_id, post_body)
        body = json.loads(body)
        return resp, body['project']

    def get_project(self, project_id):
        """GET a Project."""
        resp, body = self.get("projects/%s" % project_id)
        body = json.loads(body)
        return resp, body['project']

    def delete_project(self, project_id):
        """Delete a project."""
        resp, body = self.delete('projects/%s' % str(project_id))
        return resp, body

    def create_role(self, name):
        """Create a Role."""
        post_body = {
            'name': name
        }
        post_body = json.dumps({'role': post_body})
        resp, body = self.post('roles', post_body)
        body = json.loads(body)
        return resp, body['role']

    def get_role(self, role_id):
        """GET a Role."""
        resp, body = self.get('roles/%s' % str(role_id))
        body = json.loads(body)
        return resp, body['role']

    def list_roles(self):
        """Get the list of Roles."""
        resp, body = self.get("roles")
        body = json.loads(body)
        return resp, body['roles']

    def update_role(self, name, role_id):
        """Create a Role."""
        post_body = {
            'name': name
        }
        post_body = json.dumps({'role': post_body})
        resp, body = self.patch('roles/%s' % str(role_id), post_body)
        body = json.loads(body)
        return resp, body['role']

    def delete_role(self, role_id):
        """Delete a role."""
        resp, body = self.delete('roles/%s' % str(role_id))
        return resp, body

    def assign_user_role(self, project_id, user_id, role_id):
        """Add roles to a user on a project."""
        resp, body = self.put('projects/%s/users/%s/roles/%s' %
                              (project_id, user_id, role_id), None)
        return resp, body

    def create_domain(self, name, **kwargs):
        """Creates a domain."""
        description = kwargs.get('description', None)
        en = kwargs.get('enabled', True)
        post_body = {
            'description': description,
            'enabled': en,
            'name': name
        }
        post_body = json.dumps({'domain': post_body})
        resp, body = self.post('domains', post_body)
        body = json.loads(body)
        return resp, body['domain']

    def delete_domain(self, domain_id):
        """Delete a domain."""
        resp, body = self.delete('domains/%s' % str(domain_id))
        return resp, body

    def list_domains(self):
        """List Domains."""
        resp, body = self.get('domains')
        body = json.loads(body)
        return resp, body['domains']

    def update_domain(self, domain_id, **kwargs):
        """Updates a domain."""
        resp, body = self.get_domain(domain_id)
        description = kwargs.get('description', body['description'])
        en = kwargs.get('enabled', body['enabled'])
        name = kwargs.get('name', body['name'])
        post_body = {
            'description': description,
            'enabled': en,
            'name': name
        }
        post_body = json.dumps({'domain': post_body})
        resp, body = self.patch('domains/%s' % domain_id, post_body)
        body = json.loads(body)
        return resp, body['domain']

    def get_domain(self, domain_id):
        """Get Domain details."""
        resp, body = self.get('domains/%s' % domain_id)
        body = json.loads(body)
        return resp, body['domain']

    def get_token(self, resp_token):
        """Get token details."""
        headers = {'X-Subject-Token': resp_token}
        resp, body = self.get("auth/tokens", headers=headers)
        body = json.loads(body)
        return resp, body['token']

    def delete_token(self, resp_token):
        """Deletes token."""
        headers = {'X-Subject-Token': resp_token}
        resp, body = self.delete("auth/tokens", headers=headers)
        return resp, body

    def create_group(self, name, **kwargs):
        """Creates a group."""
        description = kwargs.get('description', None)
        domain_id = kwargs.get('domain_id', 'default')
        project_id = kwargs.get('project_id', None)
        post_body = {
            'description': description,
            'domain_id': domain_id,
            'project_id': project_id,
            'name': name
        }
        post_body = json.dumps({'group': post_body})
        resp, body = self.post('groups', post_body)
        body = json.loads(body)
        return resp, body['group']

    def get_group(self, group_id):
        """Get group details."""
        resp, body = self.get('groups/%s' % group_id)
        body = json.loads(body)
        return resp, body['group']

    def update_group(self, group_id, **kwargs):
        """Updates a group."""
        resp, body = self.get_group(group_id)
        name = kwargs.get('name', body['name'])
        description = kwargs.get('description', body['description'])
        post_body = {
            'name': name,
            'description': description
        }
        post_body = json.dumps({'group': post_body})
        resp, body = self.patch('groups/%s' % group_id, post_body)
        body = json.loads(body)
        return resp, body['group']

    def delete_group(self, group_id):
        """Delete a group."""
        resp, body = self.delete('groups/%s' % str(group_id))
        return resp, body

    def add_group_user(self, group_id, user_id):
        """Add user into group."""
        resp, body = self.put('groups/%s/users/%s' % (group_id, user_id),
                              None)
        return resp, body

    def list_group_users(self, group_id):
        """List users in group."""
        resp, body = self.get('groups/%s/users' % group_id)
        body = json.loads(body)
        return resp, body['users']

    def list_user_groups(self, user_id):
        """Lists groups which a user belongs to."""
        resp, body = self.get('users/%s/groups' % user_id)
        body = json.loads(body)
        return resp, body['groups']

    def delete_group_user(self, group_id, user_id):
        """Delete user in group."""
        resp, body = self.delete('groups/%s/users/%s' % (group_id, user_id))
        return resp, body

    def assign_user_role_on_project(self, project_id, user_id, role_id):
        """Add roles to a user on a project."""
        resp, body = self.put('projects/%s/users/%s/roles/%s' %
                              (project_id, user_id, role_id), None)
        return resp, body

    def assign_user_role_on_domain(self, domain_id, user_id, role_id):
        """Add roles to a user on a domain."""
        resp, body = self.put('domains/%s/users/%s/roles/%s' %
                              (domain_id, user_id, role_id), None)
        return resp, body

    def list_user_roles_on_project(self, project_id, user_id):
        """list roles of a user on a project."""
        resp, body = self.get('projects/%s/users/%s/roles' %
                              (project_id, user_id))
        body = json.loads(body)
        return resp, body['roles']

    def list_user_roles_on_domain(self, domain_id, user_id):
        """list roles of a user on a domain."""
        resp, body = self.get('domains/%s/users/%s/roles' %
                              (domain_id, user_id))
        body = json.loads(body)
        return resp, body['roles']

    def revoke_role_from_user_on_project(self, project_id, user_id, role_id):
        """Delete role of a user on a project."""
        resp, body = self.delete('projects/%s/users/%s/roles/%s' %
                                 (project_id, user_id, role_id))
        return resp, body

    def revoke_role_from_user_on_domain(self, domain_id, user_id, role_id):
        """Delete role of a user on a domain."""
        resp, body = self.delete('domains/%s/users/%s/roles/%s' %
                                 (domain_id, user_id, role_id))
        return resp, body

    def assign_group_role_on_project(self, project_id, group_id, role_id):
        """Add roles to a user on a project."""
        resp, body = self.put('projects/%s/groups/%s/roles/%s' %
                              (project_id, group_id, role_id), None)
        return resp, body

    def assign_group_role_on_domain(self, domain_id, group_id, role_id):
        """Add roles to a user on a domain."""
        resp, body = self.put('domains/%s/groups/%s/roles/%s' %
                              (domain_id, group_id, role_id), None)
        return resp, body

    def list_group_roles_on_project(self, project_id, group_id):
        """list roles of a user on a project."""
        resp, body = self.get('projects/%s/groups/%s/roles' %
                              (project_id, group_id))
        body = json.loads(body)
        return resp, body['roles']

    def list_group_roles_on_domain(self, domain_id, group_id):
        """list roles of a user on a domain."""
        resp, body = self.get('domains/%s/groups/%s/roles' %
                              (domain_id, group_id))
        body = json.loads(body)
        return resp, body['roles']

    def revoke_role_from_group_on_project(self, project_id, group_id, role_id):
        """Delete role of a user on a project."""
        resp, body = self.delete('projects/%s/groups/%s/roles/%s' %
                                 (project_id, group_id, role_id))
        return resp, body

    def revoke_role_from_group_on_domain(self, domain_id, group_id, role_id):
        """Delete role of a user on a domain."""
        resp, body = self.delete('domains/%s/groups/%s/roles/%s' %
                                 (domain_id, group_id, role_id))
        return resp, body

    def create_trust(self, trustor_user_id, trustee_user_id, project_id,
                     role_names, impersonation, expires_at):
        """Creates a trust."""
        roles = [{'name': n} for n in role_names]
        post_body = {
            'trustor_user_id': trustor_user_id,
            'trustee_user_id': trustee_user_id,
            'project_id': project_id,
            'impersonation': impersonation,
            'roles': roles,
            'expires_at': expires_at
        }
        post_body = json.dumps({'trust': post_body})
        resp, body = self.post('OS-TRUST/trusts', post_body)
        body = json.loads(body)
        return resp, body['trust']

    def delete_trust(self, trust_id):
        """Deletes a trust."""
        resp, body = self.delete("OS-TRUST/trusts/%s" % trust_id)
        return resp, body

    def get_trusts(self, trustor_user_id=None, trustee_user_id=None):
        """GET trusts."""
        if trustor_user_id:
            resp, body = self.get("OS-TRUST/trusts?trustor_user_id=%s"
                                  % trustor_user_id)
        elif trustee_user_id:
            resp, body = self.get("OS-TRUST/trusts?trustee_user_id=%s"
                                  % trustee_user_id)
        else:
            resp, body = self.get("OS-TRUST/trusts")
        body = json.loads(body)
        return resp, body['trusts']

    def get_trust(self, trust_id):
        """GET trust."""
        resp, body = self.get("OS-TRUST/trusts/%s" % trust_id)
        body = json.loads(body)
        return resp, body['trust']

    def get_trust_roles(self, trust_id):
        """GET roles delegated by a trust."""
        resp, body = self.get("OS-TRUST/trusts/%s/roles" % trust_id)
        body = json.loads(body)
        return resp, body['roles']

    def get_trust_role(self, trust_id, role_id):
        """GET role delegated by a trust."""
        resp, body = self.get("OS-TRUST/trusts/%s/roles/%s"
                              % (trust_id, role_id))
        body = json.loads(body)
        return resp, body['role']

    def check_trust_role(self, trust_id, role_id):
        """HEAD Check if role is delegated by a trust."""
        resp, body = self.head("OS-TRUST/trusts/%s/roles/%s"
                               % (trust_id, role_id))
        return resp, body

class V3TokenClientJSON(rest_client.RestClient):

    def __init__(self):
        super(V3TokenClientJSON, self).__init__(None)
        auth_url = CONF.identity.uri_v3
        if not auth_url and CONF.identity_feature_enabled.api_v3:
            raise exceptions.InvalidConfiguration('you must specify a v3 uri '
                                                  'if using the v3 identity '
                                                  'api')
        if 'auth/tokens' not in auth_url:
            auth_url = auth_url.rstrip('/') + '/auth/tokens'

        self.auth_url = auth_url

    def auth(self, user=None, password=None, tenant=None, user_type='id',
             domain=None, token=None):
        """
        :param user: user id or name, as specified in user_type
        :param domain: the user and tenant domain
        :param token: a token to re-scope.

        Accepts different combinations of credentials. Restrictions:
        - tenant and domain are only name (no id)
        - user domain and tenant domain are assumed identical
        - domain scope is not supported here
        Sample sample valid combinations:
        - token
        - token, tenant, domain
        - user_id, password
        - username, password, domain
        - username, password, tenant, domain
        Validation is left to the server side.
        """
        creds = {
            'auth': {
                'identity': {
                    'methods': [],
                }
            }
        }
        id_obj = creds['auth']['identity']
        if token:
            id_obj['methods'].append('token')
            id_obj['token'] = {
                'id': token
            }
        if user and password:
            id_obj['methods'].append('password')
            id_obj['password'] = {
                'user': {
                    'password': password,
                }
            }
            if user_type == 'id':
                id_obj['password']['user']['id'] = user
            else:
                id_obj['password']['user']['name'] = user
            if domain is not None:
                _domain = dict(name=domain)
                id_obj['password']['user']['domain'] = _domain
        if tenant is not None:
            _domain = dict(name=domain)
            project = dict(name=tenant, domain=_domain)
            scope = dict(project=project)
            creds['auth']['scope'] = scope

        body = json.dumps(creds)
        resp, body = self.post(self.auth_url, body=body)
        return resp, body

    def request(self, method, url, extra_headers=False, headers=None,
                body=None):
        """A simple HTTP request interface."""
        if headers is None:
            # Always accept 'json', for xml token client too.
            # Because XML response is not easily
            # converted to the corresponding JSON one
            headers = self.get_headers(accept_type="json")
        elif extra_headers:
            try:
                headers.update(self.get_headers(accept_type="json"))
            except (ValueError, TypeError):
                headers = self.get_headers(accept_type="json")

        resp, resp_body = self.http_obj.request(url, method,
                                                headers=headers, body=body)
        self._log_request(method, url, resp)

        if resp.status in [401, 403]:
            resp_body = json.loads(resp_body)
            raise exceptions.Unauthorized(resp_body['error']['message'])
        elif resp.status not in [200, 201, 204]:
            raise exceptions.IdentityError(
                'Unexpected status code {0}'.format(resp.status))

        return resp, json.loads(resp_body)

    def get_token(self, user, password, tenant, domain='Default',
                  auth_data=False):
        """
        :param user: username
        Returns (token id, token data) for supplied credentials
        """
        resp, body = self.auth(user, password, tenant, user_type='name',
                               domain=domain)

        token = resp.get('x-subject-token')
        if auth_data:
            return token, body['token']
        else:
            return token


text:
package main

import "fmt"

type t struct{}

func (x t) a() error {
	fmt.Println("this method returns an error") // UNCHECKED
//line myfile.txt:100
	fmt.Println("this method also returns an error") // UNCHECKED
	return nil
}

type u struct {
	t t
}