text:
/*!
 * \file
 * \brief Stencil Tests
 *//*--------------------------------------------------------------------*/

#include "vktPipelineStencilTests.hpp"
#include "vktPipelineClearUtil.hpp"
#include "vktPipelineImageUtil.hpp"
#include "vktPipelineVertexUtil.hpp"
#include "vktPipelineReferenceRenderer.hpp"
#include "vktPipelineUniqueRandomIterator.hpp"
#include "vktTestCase.hpp"
#include "vkImageUtil.hpp"
#include "vkMemUtil.hpp"
#include "vkPrograms.hpp"
#include "vkQueryUtil.hpp"
#include "vkRef.hpp"
#include "vkRefUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkCmdUtil.hpp"
#include "vkObjUtil.hpp"
#include "tcuImageCompare.hpp"
#include "deMemory.h"
#include "deRandom.hpp"
#include "deStringUtil.hpp"
#include "deUniquePtr.hpp"

#include <algorithm>
#include <sstream>
#include <vector>

namespace vkt
{
namespace pipeline
{

using namespace vk;

namespace
{

bool isSupportedDepthStencilFormat (const InstanceInterface& instanceInterface, VkPhysicalDevice device, VkFormat format)
{
	VkFormatProperties formatProps;

	instanceInterface.getPhysicalDeviceFormatProperties(device, format, &formatProps);

	return (formatProps.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) != 0;
}

class StencilOpStateUniqueRandomIterator : public UniqueRandomIterator<VkStencilOpState>
{
public:
								StencilOpStateUniqueRandomIterator	(int seed);
	virtual						~StencilOpStateUniqueRandomIterator	(void) {}
	virtual VkStencilOpState	getIndexedValue						(deUint32 index);

private:

	// Pre-calculated constants
	const static deUint32		s_stencilOpsLength;
	const static deUint32		s_stencilOpsLength2;
	const static deUint32		s_stencilOpsLength3;
	const static deUint32		s_compareOpsLength;

	// Total number of cross-combinations of (stencilFailOp x stencilPassOp x stencilDepthFailOp x stencilCompareOp)
	const static deUint32		s_totalStencilOpStates;
};

class StencilTest : public vkt::TestCase
{
public:
	enum
	{
		QUAD_COUNT = 4
	};

	struct StencilStateConfig
	{
		deUint32	frontReadMask;
		deUint32	frontWriteMask;
		deUint32	frontRef;

		deUint32	backReadMask;
		deUint32	backWriteMask;
		deUint32	backRef;
	};

	const static StencilStateConfig			s_stencilStateConfigs[QUAD_COUNT];
	const static float						s_quadDepths[QUAD_COUNT];

											StencilTest				(tcu::TestContext&			testContext,
																	 const std::string&			name,
																	 const std::string&			description,
																	 VkFormat					stencilFormat,
																	 const VkStencilOpState&	stencilOpStateFront,
																	 const VkStencilOpState&	stencilOpStateBack,
																	 const bool					colorAttachmentEnable,
																	 const bool					separateDepthStencilLayouts);
	virtual									~StencilTest			(void);
	virtual void							initPrograms			(SourceCollections& sourceCollections) const;
	virtual void							checkSupport			(Context& context) const;
	virtual TestInstance*					createInstance			(Context& context) const;

private:
	VkFormat								m_stencilFormat;
	const VkStencilOpState					m_stencilOpStateFront;
	const VkStencilOpState					m_stencilOpStateBack;
	const bool								m_colorAttachmentEnable;
	const bool								m_separateDepthStencilLayouts;
};

class StencilTestInstance : public vkt::TestInstance
{
public:
										StencilTestInstance		(Context&					context,
																 VkFormat					stencilFormat,
																 const VkStencilOpState&	stencilOpStatesFront,
																 const VkStencilOpState&	stencilOpStatesBack,
																 const bool					colorAttachmentEnable,
																 const bool					separateDepthStencilLayouts);
	virtual								~StencilTestInstance	(void);
	virtual tcu::TestStatus				iterate					(void);

private:
	tcu::TestStatus						verifyImage				(void);

	VkStencilOpState					m_stencilOpStateFront;
	VkStencilOpState					m_stencilOpStateBack;
	const bool							m_colorAttachmentEnable;
	const bool							m_separateDepthStencilLayouts;
	const tcu::UVec2					m_renderSize;
	const VkFormat						m_colorFormat;
	const VkFormat						m_stencilFormat;
	VkImageSubresourceRange				m_stencilImageSubresourceRange;

	VkImageCreateInfo					m_colorImageCreateInfo;
	Move<VkImage>						m_colorImage;
	de::MovePtr<Allocation>				m_colorImageAlloc;
	Move<VkImage>						m_stencilImage;
	de::MovePtr<Allocation>				m_stencilImageAlloc;
	Move<VkImageView>					m_colorAttachmentView;
	Move<VkImageView>					m_stencilAttachmentView;
	Move<VkRenderPass>					m_renderPass;
	Move<VkFramebuffer>					m_framebuffer;

	Move<VkShaderModule>				m_vertexShaderModule;
	Move<VkShaderModule>				m_fragmentShaderModule;

	Move<VkBuffer>						m_vertexBuffer;
	std::vector<Vertex4RGBA>			m_vertices;
	de::MovePtr<Allocation>				m_vertexBufferAlloc;

	Move<VkPipelineLayout>				m_pipelineLayout;
	Move<VkPipeline>					m_graphicsPipelines[StencilTest::QUAD_COUNT];

	Move<VkCommandPool>					m_cmdPool;
	Move<VkCommandBuffer>				m_cmdBuffer;
};

const VkStencilOp stencilOps[] =
{
	VK_STENCIL_OP_KEEP,
	VK_STENCIL_OP_ZERO,
	VK_STENCIL_OP_REPLACE,
	VK_STENCIL_OP_INCREMENT_AND_CLAMP,
	VK_STENCIL_OP_DECREMENT_AND_CLAMP,
	VK_STENCIL_OP_INVERT,
	VK_STENCIL_OP_INCREMENT_AND_WRAP,
	VK_STENCIL_OP_DECREMENT_AND_WRAP
};

const VkCompareOp compareOps[] =
{
	VK_COMPARE_OP_NEVER,
	VK_COMPARE_OP_LESS,
	VK_COMPARE_OP_EQUAL,
	VK_COMPARE_OP_LESS_OR_EQUAL,
	VK_COMPARE_OP_GREATER,
	VK_COMPARE_OP_NOT_EQUAL,
	VK_COMPARE_OP_GREATER_OR_EQUAL,
	VK_COMPARE_OP_ALWAYS
};

// StencilOpStateUniqueRandomIterator

const deUint32 StencilOpStateUniqueRandomIterator::s_stencilOpsLength		= DE_LENGTH_OF_ARRAY(stencilOps);
const deUint32 StencilOpStateUniqueRandomIterator::s_stencilOpsLength2		= s_stencilOpsLength * s_stencilOpsLength;
const deUint32 StencilOpStateUniqueRandomIterator::s_stencilOpsLength3		= s_stencilOpsLength2 * s_stencilOpsLength;
const deUint32 StencilOpStateUniqueRandomIterator::s_compareOpsLength		= DE_LENGTH_OF_ARRAY(compareOps);
const deUint32 StencilOpStateUniqueRandomIterator::s_totalStencilOpStates	= s_stencilOpsLength3 * s_compareOpsLength;

StencilOpStateUniqueRandomIterator::StencilOpStateUniqueRandomIterator (int seed)
	: UniqueRandomIterator<VkStencilOpState>(s_totalStencilOpStates, s_totalStencilOpStates, seed)
{
}

VkStencilOpState StencilOpStateUniqueRandomIterator::getIndexedValue (deUint32 index)
{
	const deUint32 stencilCompareOpIndex = index / s_stencilOpsLength3;
	const deUint32 stencilCompareOpSeqIndex = stencilCompareOpIndex * s_stencilOpsLength3;

	const deUint32 stencilDepthFailOpIndex = (index - stencilCompareOpSeqIndex) / s_stencilOpsLength2;
	const deUint32 stencilDepthFailOpSeqIndex = stencilDepthFailOpIndex * s_stencilOpsLength2;

	const deUint32 stencilPassOpIndex = (index - stencilCompareOpSeqIndex - stencilDepthFailOpSeqIndex) / s_stencilOpsLength;
	const deUint32 stencilPassOpSeqIndex = stencilPassOpIndex * s_stencilOpsLength;

	const deUint32 stencilFailOpIndex = index - stencilCompareOpSeqIndex - stencilDepthFailOpSeqIndex - stencilPassOpSeqIndex;

	const VkStencilOpState stencilOpState =
	{
		stencilOps[stencilFailOpIndex],			// VkStencilOp	failOp;
		stencilOps[stencilPassOpIndex],			// VkStencilOp	passOp;
		stencilOps[stencilDepthFailOpIndex],	// VkStencilOp	depthFailOp;
		compareOps[stencilCompareOpIndex],		// VkCompareOp	compareOp;
		0x0,									// deUint32		compareMask;
		0x0,									// deUint32		writeMask;
		0x0										// deUint32		reference;
	};

	return stencilOpState;
}

// StencilTest

const StencilTest::StencilStateConfig StencilTest::s_stencilStateConfigs[QUAD_COUNT] =
{
	//	frontReadMask	frontWriteMask		frontRef		backReadMask	backWriteMask	backRef
	{	0xFF,			0xFF,				0xAB,			0xF0,			0xFF,			0xFF	},
	{	0xFF,			0xF0,				0xCD,			0xF0,			0xF0,			0xEF	},
	{	0xF0,			0x0F,				0xEF,			0xFF,			0x0F,			0xCD	},
	{	0xF0,			0x01,				0xFF,			0xFF,			0x01,			0xAB	}
};

const float StencilTest::s_quadDepths[QUAD_COUNT] =
{
	0.1f,
	0.0f,
	0.3f,
	0.2f
};

StencilTest::StencilTest (tcu::TestContext&			testContext,
						  const std::string&		name,
						  const std::string&		description,
						  VkFormat					stencilFormat,
						  const VkStencilOpState&	stencilOpStateFront,
						  const VkStencilOpState&	stencilOpStateBack,
						  const bool				colorAttachmentEnable,
						  const bool				separateDepthStencilLayouts)
	: vkt::TestCase					(testContext, name, description)
	, m_stencilFormat				(stencilFormat)
	, m_stencilOpStateFront			(stencilOpStateFront)
	, m_stencilOpStateBack			(stencilOpStateBack)
	, m_colorAttachmentEnable		(colorAttachmentEnable)
	, m_separateDepthStencilLayouts	(separateDepthStencilLayouts)
{
}

StencilTest::~StencilTest (void)
{
}

void StencilTest::checkSupport (Context& context) const
{
	if (!isSupportedDepthStencilFormat(context.getInstanceInterface(), context.getPhysicalDevice(), m_stencilFormat))
		throw tcu::NotSupportedError(std::string("Unsupported depth/stencil format: ") + getFormatName(m_stencilFormat));

	if (m_separateDepthStencilLayouts && !context.isDeviceFunctionalitySupported("VK_KHR_separate_depth_stencil_layouts"))
		TCU_THROW(NotSupportedError, "VK_KHR_separate_depth_stencil_layouts is not supported");
}

TestInstance* StencilTest::createInstance (Context& context) const
{
	return new StencilTestInstance(context, m_stencilFormat, m_stencilOpStateFront, m_stencilOpStateBack, m_colorAttachmentEnable, m_separateDepthStencilLayouts);
}

void StencilTest::initPrograms (SourceCollections& sourceCollections) const
{
	if (m_colorAttachmentEnable)
	{
		sourceCollections.glslSources.add("color_vert") << glu::VertexSource(
			"#version 310 es\n"
			"layout(location = 0) in vec4 position;\n"
			"layout(location = 1) in vec4 color;\n"
			"layout(location = 0) out highp vec4 vtxColor;\n"
			"void main (void)\n"
			"{\n"
			"	gl_Position = position;\n"
			"	vtxColor = color;\n"
			"}\n");

		sourceCollections.glslSources.add("color_frag") << glu::FragmentSource(
			"#version 310 es\n"
			"layout(location = 0) in highp vec4 vtxColor;\n"
			"layout(location = 0) out highp vec4 fragColor;\n"
			"void main (void)\n"
			"{\n"
			"	fragColor = vtxColor;\n"
			"}\n");
	}
	else
	{
		sourceCollections.glslSources.add("color_vert") << glu::VertexSource(
			"#version 310 es\n"
			"layout(location = 0) in vec4 position;\n"
			"layout(location = 1) in vec4 color;\n"
			"void main (void)\n"
			"{\n"
			"	gl_Position = position;\n"
			"}\n");
	}
}

// StencilTestInstance

StencilTestInstance::StencilTestInstance (Context&					context,
										  VkFormat					stencilFormat,
										  const VkStencilOpState&	stencilOpStateFront,
										  const VkStencilOpState&	stencilOpStateBack,
										  const bool				colorAttachmentEnable,
										  const bool				separateDepthStencilLayouts)
	: vkt::TestInstance				(context)
	, m_stencilOpStateFront			(stencilOpStateFront)
	, m_stencilOpStateBack			(stencilOpStateBack)
	, m_colorAttachmentEnable		(colorAttachmentEnable)
	, m_separateDepthStencilLayouts	(separateDepthStencilLayouts)
	, m_renderSize					(32, 32)
	, m_colorFormat					(colorAttachmentEnable ? VK_FORMAT_R8G8B8A8_UNORM : VK_FORMAT_UNDEFINED)
	, m_stencilFormat				(stencilFormat)
{
	const DeviceInterface&		vk						= context.getDeviceInterface();
	const VkDevice				vkDevice				= context.getDevice();
	const deUint32				queueFamilyIndex		= context.getUniversalQueueFamilyIndex();
	SimpleAllocator				memAlloc				(vk, vkDevice, getPhysicalDeviceMemoryProperties(context.getInstanceInterface(), context.getPhysicalDevice()));
	const VkComponentMapping	componentMappingRGBA	= { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A };

	// Create color image
	if (m_colorAttachmentEnable)
	{
		const VkImageCreateInfo colorImageParams =
		{
			VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,										// VkStructureType			sType;
			DE_NULL,																	// const void*				pNext;
			0u,																			// VkImageCreateFlags		flags;
			VK_IMAGE_TYPE_2D,															// VkImageType				imageType;
			m_colorFormat,																// VkFormat					format;
			{ m_renderSize.x(), m_renderSize.y(), 1u },									// VkExtent3D				extent;
			1u,																			// deUint32					mipLevels;
			1u,																			// deUint32					arrayLayers;
			VK_SAMPLE_COUNT_1_BIT,														// VkSampleCountFlagBits	samples;
			VK_IMAGE_TILING_OPTIMAL,													// VkImageTiling			tiling;
			VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,		// VkImageUsageFlags		usage;
			VK_SHARING_MODE_EXCLUSIVE,													// VkSharingMode			sharingMode;
			1u,																			// deUint32					queueFamilyIndexCount;
			&queueFamilyIndex,															// const deUint32*			pQueueFamilyIndices;
			VK_IMAGE_LAYOUT_UNDEFINED													// VkImageLayout			initialLayout;
		};

		m_colorImageCreateInfo	= colorImageParams;
		m_colorImage			= createImage(vk, vkDevice, &m_colorImageCreateInfo);

		// Allocate and bind color image memory
		m_colorImageAlloc		= memAlloc.allocate(getImageMemoryRequirements(vk, vkDevice, *m_colorImage), MemoryRequirement::Any);
		VK_CHECK(vk.bindImageMemory(vkDevice, *m_colorImage, m_colorImageAlloc->getMemory(), m_colorImageAlloc->getOffset()));
	}

	// Create stencil image
	{
		const VkImageUsageFlags	usageFlags			= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;

		const VkImageCreateInfo	stencilImageParams	=
		{
			VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,			// VkStructureType			sType;
			DE_NULL,										// const void*				pNext;
			0u,												// VkImageCreateFlags		flags;
			VK_IMAGE_TYPE_2D,								// VkImageType				imageType;
			m_stencilFormat,								// VkFormat					format;
			{ m_renderSize.x(), m_renderSize.y(), 1u },		// VkExtent3D				extent;
			1u,												// deUint32					mipLevels;
			1u,												// deUint32					arrayLayers;
			VK_SAMPLE_COUNT_1_BIT,							// VkSampleCountFlagBits	samples;
			VK_IMAGE_TILING_OPTIMAL,						// VkImageTiling			tiling;
			usageFlags,										// VkImageUsageFlags		usage;
			VK_SHARING_MODE_EXCLUSIVE,						// VkSharingMode			sharingMode;
			1u,												// deUint32					queueFamilyIndexCount;
			&queueFamilyIndex,								// const deUint32*			pQueueFamilyIndices;
			VK_IMAGE_LAYOUT_UNDEFINED						// VkImageLayout			initialLayout;
		};

		m_stencilImage = createImage(vk, vkDevice, &stencilImageParams);

		// Allocate and bind stencil image memory
		m_stencilImageAlloc = memAlloc.allocate(getImageMemoryRequirements(vk, vkDevice, *m_stencilImage), MemoryRequirement::Any);
		VK_CHECK(vk.bindImageMemory(vkDevice, *m_stencilImage, m_stencilImageAlloc->getMemory(), m_stencilImageAlloc->getOffset()));

		const VkImageAspectFlags aspect = (mapVkFormat(m_stencilFormat).order == tcu::TextureFormat::DS ? VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_DEPTH_BIT
																										: VK_IMAGE_ASPECT_STENCIL_BIT);
		m_stencilImageSubresourceRange  = makeImageSubresourceRange(aspect, 0u, stencilImageParams.mipLevels, 0u, stencilImageParams.arrayLayers);
	}

	// Create color attachment view
	if (m_colorAttachmentEnable)
	{
		const VkImageViewCreateInfo colorAttachmentViewParams =
		{
			VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,			// VkStructureType			sType;
			DE_NULL,											// const void*				pNext;
			0u,													// VkImageViewCreateFlags	flags;
			*m_colorImage,										// VkImage					image;
			VK_IMAGE_VIEW_TYPE_2D,								// VkImageViewType			viewType;
			m_colorFormat,										// VkFormat					format;
			componentMappingRGBA,								// VkComponentMapping		components;
			{ VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u }		// VkImageSubresourceRange	subresourceRange;
		};

		m_colorAttachmentView = createImageView(vk, vkDevice, &colorAttachmentViewParams);
	}

	// Create stencil attachment view
	{
		const VkImageViewCreateInfo stencilAttachmentViewParams =
		{
			VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,			// VkStructureType			sType;
			DE_NULL,											// const void*				pNext;
			0u,													// VkImageViewCreateFlags	flags;
			*m_stencilImage,									// VkImage					image;
			VK_IMAGE_VIEW_TYPE_2D,								// VkImageViewType			viewType;
			m_stencilFormat,									// VkFormat					format;
			componentMappingRGBA,								// VkComponentMapping		components;
			m_stencilImageSubresourceRange,						// VkImageSubresourceRange	subresourceRange;
		};

		m_stencilAttachmentView = createImageView(vk, vkDevice, &stencilAttachmentViewParams);
	}

	// Create render pass
	m_renderPass = makeRenderPass(vk, vkDevice, m_colorFormat, m_stencilFormat);

	// Create framebuffer
	{
		std::vector<VkImageView>		attachmentBindInfos;

		if (m_colorAttachmentEnable)
			attachmentBindInfos.push_back(*m_colorAttachmentView);

		attachmentBindInfos.push_back(*m_stencilAttachmentView);

		const VkFramebufferCreateInfo	framebufferParams =
		{
			VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,			// VkStructureType			sType;
			DE_NULL,											// const void*				pNext;
			0u,													// VkFramebufferCreateFlags	flags;
			*m_renderPass,										// VkRenderPass				renderPass;
			(deUint32)attachmentBindInfos.size(),				// deUint32					attachmentCount;
			attachmentBindInfos.data(),							// const VkImageView*		pAttachments;
			(deUint32)m_renderSize.x(),							// deUint32					width;
			(deUint32)m_renderSize.y(),							// deUint32					height;
			1u													// deUint32					layers;
		};

		m_framebuffer = createFramebuffer(vk, vkDevice, &framebufferParams);
	}

	// Create pipeline layout
	{
		const VkPipelineLayoutCreateInfo pipelineLayoutParams =
		{
			VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,		// VkStructureType				sType;
			DE_NULL,											// const void*					pNext;
			0u,													// VkPipelineLayoutCreateFlags	flags;
			0u,													// deUint32						setLayoutCount;
			DE_NULL,											// const VkDescriptorSetLayout*	pSetLayouts;
			0u,													// deUint32						pushConstantRangeCount;
			DE_NULL												// const VkPushConstantRange*	pPushConstantRanges;
		};

		m_pipelineLayout = createPipelineLayout(vk, vkDevice, &pipelineLayoutParams);
	}

	m_vertexShaderModule		= createShaderModule(vk, vkDevice, m_context.getBinaryCollection().get("color_vert"), 0);
	if (m_colorAttachmentEnable)
		m_fragmentShaderModule	= createShaderModule(vk, vkDevice, m_context.getBinaryCollection().get("color_frag"), 0);

	// Create pipeline
	{
		const VkVertexInputBindingDescription vertexInputBindingDescription =
		{
			0u,										// deUint32					binding;
			sizeof(Vertex4RGBA),					// deUint32					strideInBytes;
			VK_VERTEX_INPUT_RATE_VERTEX				// VkVertexInputStepRate	inputRate;
		};

		const VkVertexInputAttributeDescription vertexInputAttributeDescriptions[2] =
		{
			{
				0u,									// deUint32	location;
				0u,									// deUint32	binding;
				VK_FORMAT_R32G32B32A32_SFLOAT,		// VkFormat	format;
				0u									// deUint32	offsetInBytes;
			},
			{
				1u,									// deUint32	location;
				0u,									// deUint32	binding;
				VK_FORMAT_R32G32B32A32_SFLOAT,		// VkFormat	format;
				DE_OFFSET_OF(Vertex4RGBA, color),	// deUint32	offsetInBytes;
			}
		};

		const VkPipelineVertexInputStateCreateInfo vertexInputStateParams =
		{
			VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,		// VkStructureType							sType;
			DE_NULL,														// const void*								pNext;
			0u,																// VkPipelineVertexInputStateCreateFlags	flags;
			1u,																// deUint32									vertexBindingDescriptionCount;
			&vertexInputBindingDescription,									// const VkVertexInputBindingDescription*	pVertexBindingDescriptions;
			2u,																// deUint32									vertexAttributeDescriptionCount;
			vertexInputAttributeDescriptions								// const VkVertexInputAttributeDescription*	pVertexAttributeDescriptions;
		};

		const std::vector<VkViewport>	viewports	(1, makeViewport(m_renderSize));
		const std::vector<VkRect2D>		scissors	(1, makeRect2D(m_renderSize));

		const bool isDepthEnabled = (vk::mapVkFormat(m_stencilFormat).order != tcu::TextureFormat::S);

		VkPipelineDepthStencilStateCreateInfo depthStencilStateParams =
		{
			VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,	// VkStructureType							sType;
			DE_NULL,													// const void*								pNext;
			0u,															// VkPipelineDepthStencilStateCreateFlags	flags;
			isDepthEnabled,												// VkBool32									depthTestEnable;
			isDepthEnabled,												// VkBool32									depthWriteEnable;
			VK_COMPARE_OP_LESS,											// VkCompareOp								depthCompareOp;
			false,														// VkBool32									depthBoundsTestEnable;
			true,														// VkBool32									stencilTestEnable;
			m_stencilOpStateFront,										// VkStencilOpState							front;
			m_stencilOpStateBack,										// VkStencilOpState							back;
			0.0f,														// float									minDepthBounds;
			1.0f														// float									maxDepthBounds;
		};

		// Make sure rasterization is not disabled when the fragment shader is missing.
		const vk::VkPipelineRasterizationStateCreateInfo rasterizationStateParams =
		{
			vk::VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,	//	VkStructureType							sType;
			nullptr,														//	const void*								pNext;
			0u,																//	VkPipelineRasterizationStateCreateFlags	flags;
			VK_FALSE,														//	VkBool32								depthClampEnable;
			VK_FALSE,														//	VkBool32								rasterizerDiscardEnable;
			vk::VK_POLYGON_MODE_FILL,										//	VkPolygonMode							polygonMode;
			vk::VK_CULL_MODE_NONE,											//	VkCullModeFlags							cullMode;
			vk::VK_FRONT_FACE_COUNTER_CLOCKWISE,							//	VkFrontFace								frontFace;
			VK_FALSE,														//	VkBool32								depthBiasEnable;
			0.0f,															//	float									depthBiasConstantFactor;
			0.0f,															//	float									depthBiasClamp;
			0.0f,															//	float									depthBiasSlopeFactor;
			1.0f,															//	float									lineWidth;
		};

		// Setup different stencil masks and refs in each quad
		for (int quadNdx = 0; quadNdx < StencilTest::QUAD_COUNT; quadNdx++)
		{
			const StencilTest::StencilStateConfig&	config	= StencilTest::s_stencilStateConfigs[quadNdx];
			VkStencilOpState&						front	= depthStencilStateParams.front;
			VkStencilOpState&						back	= depthStencilStateParams.back;

			front.compareMask	= config.frontReadMask;
			front.writeMask		= config.frontWriteMask;
			front.reference		= config.frontRef;

			back.compareMask	= config.backReadMask;
			back.writeMask		= config.backWriteMask;
			back.reference		= config.backRef;

			m_graphicsPipelines[quadNdx] = makeGraphicsPipeline(vk,										// const DeviceInterface&                        vk
																vkDevice,								// const VkDevice                                device
																*m_pipelineLayout,						// const VkPipelineLayout                        pipelineLayout
																*m_vertexShaderModule,					// const VkShaderModule                          vertexShaderModule
																DE_NULL,								// const VkShaderModule                          tessellationControlModule
																DE_NULL,								// const VkShaderModule                          tessellationEvalModule
																DE_NULL,								// const VkShaderModule                          geometryShaderModule
																*m_fragmentShaderModule,				// const VkShaderModule                          fragmentShaderModule
																*m_renderPass,							// const VkRenderPass                            renderPass
																viewports,								// const std::vector<VkViewport>&                viewports
																scissors,								// const std::vector<VkRect2D>&                  scissors
																VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,	// const VkPrimitiveTopology                     topology
																0u,										// const deUint32                                subpass
																0u,										// const deUint32                                patchControlPoints
																&vertexInputStateParams,				// const VkPipelineVertexInputStateCreateInfo*   vertexInputStateCreateInfo
																&rasterizationStateParams,				// const VkPipelineRasterizationStateCreateInfo* rasterizationStateCreateInfo
																DE_NULL,								// const VkPipelineMultisampleStateCreateInfo*   multisampleStateCreateInfo
																&depthStencilStateParams);				// const VkPipelineDepthStencilStateCreateInfo*  depthStencilStateCreateInfo
		}
	}

	// Create vertex buffer
	{
		const VkBufferCreateInfo vertexBufferParams =
		{
			VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,		// VkStructureType		sType;
			DE_NULL,									// const void*			pNext;
			0u,											// VkBufferCreateFlags	flags;
			1024u,										// VkDeviceSize			size;
			VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,			// VkBufferUsageFlags	usage;
			VK_SHARING_MODE_EXCLUSIVE,					// VkSharingMode		sharingMode;
			1u,											// deUint32				queueFamilyIndexCount;
			&queueFamilyIndex							// const deUint32*		pQueueFamilyIndices;
		};

		m_vertices			= createOverlappingQuads();
		m_vertexBuffer		= createBuffer(vk, vkDevice, &vertexBufferParams);
		m_vertexBufferAlloc	= memAlloc.allocate(getBufferMemoryRequirements(vk, vkDevice, *m_vertexBuffer), MemoryRequirement::HostVisible);

		VK_CHECK(vk.bindBufferMemory(vkDevice, *m_vertexBuffer, m_vertexBufferAlloc->getMemory(), m_vertexBufferAlloc->getOffset()));

		// Adjust depths
		for (int quadNdx = 0; quadNdx < 4; quadNdx++)
			for (int vertexNdx = 0; vertexNdx < 6; vertexNdx++)
				m_vertices[quadNdx * 6 + vertexNdx].position.z() = StencilTest::s_quadDepths[quadNdx];

		// Load vertices into vertex buffer
		deMemcpy(m_vertexBufferAlloc->getHostPtr(), m_vertices.data(), m_vertices.size() * sizeof(Vertex4RGBA));
		flushAlloc(vk, vkDevice, *m_vertexBufferAlloc);
	}

	// Create command pool
	m_cmdPool = createCommandPool(vk, vkDevice, VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, queueFamilyIndex);

	// Create command buffer
	{
		const VkImageMemoryBarrier	colorImageBarrier					=
		{
			VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,			// VkStructureType            sType;
			DE_NULL,										// const void*                pNext;
			(VkAccessFlags)0,								// VkAccessFlags              srcAccessMask;
			VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,			// VkAccessFlags              dstAccessMask;
			VK_IMAGE_LAYOUT_UNDEFINED,						// VkImageLayout              oldLayout;
			VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,		// VkImageLayout              newLayout;
			VK_QUEUE_FAMILY_IGNORED,						// uint32_t                   srcQueueFamilyIndex;
			VK_QUEUE_FAMILY_IGNORED,						// uint32_t                   dstQueueFamilyIndex;
			*m_colorImage,									// VkImage                    image;
			{ VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u }	// VkImageSubresourceRange    subresourceRange;
		};

		VkImageSubresourceRange		stencilImageBarrierSubresourceRange	= m_stencilImageSubresourceRange;
		VkImageLayout				newLayout							= VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
		if (m_separateDepthStencilLayouts)
		{
			stencilImageBarrierSubresourceRange.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
			newLayout = VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL_KHR;
		}

		const VkImageMemoryBarrier	stencilImageBarrier					=
		{
			VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,									// VkStructureType            sType;
			DE_NULL,																// const void*                pNext;
			(VkAccessFlags)0,														// VkAccessFlags              srcAccessMask;
			VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,							// VkAccessFlags              dstAccessMask;
			VK_IMAGE_LAYOUT_UNDEFINED,												// VkImageLayout              oldLayout;
			newLayout,																// VkImageLayout              newLayout;
			VK_QUEUE_FAMILY_IGNORED,												// uint32_t                   srcQueueFamilyIndex;
			VK_QUEUE_FAMILY_IGNORED,												// uint32_t                   dstQueueFamilyIndex;
			*m_stencilImage,														// VkImage                    image;
			stencilImageBarrierSubresourceRange,									// VkImageSubresourceRange    subresourceRange;
		};

		std::vector<VkClearValue>			attachmentClearValues;
		std::vector<VkImageMemoryBarrier>	imageLayoutBarriers;

		if (m_colorAttachmentEnable)
		{
			attachmentClearValues.push_back(defaultClearValue(m_colorFormat));
			imageLayoutBarriers.push_back(colorImageBarrier);
		}

		attachmentClearValues.push_back(defaultClearValue(m_stencilFormat));
		imageLayoutBarriers.push_back(stencilImageBarrier);

		m_cmdBuffer = allocateCommandBuffer(vk, vkDevice, *m_cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY);

		beginCommandBuffer(vk, *m_cmdBuffer, 0u);

		vk.cmdPipelineBarrier(*m_cmdBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, (VkDependencyFlags)0,
			0u, DE_NULL, 0u, DE_NULL, (deUint32)imageLayoutBarriers.size(), imageLayoutBarriers.data());

		beginRenderPass(vk, *m_cmdBuffer, *m_renderPass, *m_framebuffer, makeRect2D(0, 0, m_renderSize.x(), m_renderSize.y()), (deUint32)attachmentClearValues.size(), attachmentClearValues.data());

		const VkDeviceSize		quadOffset		= (m_vertices.size() / StencilTest::QUAD_COUNT) * sizeof(Vertex4RGBA);

		for (int quadNdx = 0; quadNdx < StencilTest::QUAD_COUNT; quadNdx++)
		{
			VkDeviceSize vertexBufferOffset = quadOffset * quadNdx;

			vk.cmdBindPipeline(*m_cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *m_graphicsPipelines[quadNdx]);
			vk.cmdBindVertexBuffers(*m_cmdBuffer, 0, 1, &m_vertexBuffer.get(), &vertexBufferOffset);
			vk.cmdDraw(*m_cmdBuffer, (deUint32)(m_vertices.size() / StencilTest::QUAD_COUNT), 1, 0, 0);
		}

		endRenderPass(vk, *m_cmdBuffer);
		endCommandBuffer(vk, *m_cmdBuffer);
	}
}

StencilTestInstance::~StencilTestInstance (void)
{
}

tcu::TestStatus StencilTestInstance::iterate (void)
{
	const DeviceInterface&		vk			= m_context.getDeviceInterface();
	const VkDevice				vkDevice	= m_context.getDevice();
	const VkQueue				queue		= m_context.getUniversalQueue();

	submitCommandsAndWait(vk, vkDevice, queue, m_cmdBuffer.get());

	return verifyImage();
}

tcu::TestStatus StencilTestInstance::verifyImage (void)
{
	const tcu::TextureFormat	tcuColorFormat		= mapVkFormat(VK_FORMAT_R8G8B8A8_UNORM);
	const tcu::TextureFormat	tcuStencilFormat	= mapVkFormat(m_stencilFormat);
	const ColorVertexShader		vertexShader;
	const ColorFragmentShader	fragmentShader		(tcuColorFormat, tcuStencilFormat);
	const rr::Program			program				(&vertexShader, &fragmentShader);
	ReferenceRenderer			refRenderer			(m_renderSize.x(), m_renderSize.y(), 1, tcuColorFormat, tcuStencilFormat, &program);
	bool						colorCompareOk		= false;
	bool						stencilCompareOk	= false;

	// Render reference image
	{
		// Set depth state
		rr::RenderState renderState(refRenderer.getViewportState(), m_context.getDeviceProperties().limits.subPixelPrecisionBits);

		renderState.fragOps.depthTestEnabled	= true;
		renderState.fragOps.depthFunc			= mapVkCompareOp(VK_COMPARE_OP_LESS);
		renderState.fragOps.stencilTestEnabled	= true;

		rr::StencilState& refStencilFront	= renderState.fragOps.stencilStates[rr::FACETYPE_FRONT];
		rr::StencilState& refStencilBack	= renderState.fragOps.stencilStates[rr::FACETYPE_BACK];

		refStencilFront.sFail		= mapVkStencilOp(m_stencilOpStateFront.failOp);
		refStencilFront.dpFail		= mapVkStencilOp(m_stencilOpStateFront.depthFailOp);
		refStencilFront.dpPass		= mapVkStencilOp(m_stencilOpStateFront.passOp);
		refStencilFront.func		= mapVkCompareOp(m_stencilOpStateFront.compareOp);

		refStencilBack.sFail		= mapVkStencilOp(m_stencilOpStateBack.failOp);
		refStencilBack.dpPass		= mapVkStencilOp(m_stencilOpStateBack.passOp);
		refStencilBack.dpFail		= mapVkStencilOp(m_stencilOpStateBack.depthFailOp);
		refStencilBack.func			= mapVkCompareOp(m_stencilOpStateBack.compareOp);

		// Reverse winding of vertices, as Vulkan screen coordinates start at upper left
		std::vector<Vertex4RGBA> cwVertices(m_vertices);
		for (size_t vertexNdx = 0; vertexNdx < cwVertices.size() - 2; vertexNdx += 3)
		{
			const Vertex4RGBA cwVertex1	= cwVertices[vertexNdx + 1];

			cwVertices[vertexNdx + 1]	= cwVertices[vertexNdx + 2];
			cwVertices[vertexNdx + 2]	= cwVertex1;
		}

		for (int quadNdx = 0; quadNdx < StencilTest::QUAD_COUNT; quadNdx++)
		{
			refStencilFront.ref			= (int)StencilTest::s_stencilStateConfigs[quadNdx].frontRef;
			refStencilFront.compMask	= StencilTest::s_stencilStateConfigs[quadNdx].frontReadMask;
			refStencilFront.writeMask	= StencilTest::s_stencilStateConfigs[quadNdx].frontWriteMask;

			refStencilBack.ref			= (int)StencilTest::s_stencilStateConfigs[quadNdx].backRef;
			refStencilBack.compMask		= StencilTest::s_stencilStateConfigs[quadNdx].backReadMask;
			refStencilBack.writeMask	= StencilTest::s_stencilStateConfigs[quadNdx].backWriteMask;

			refRenderer.draw(renderState,
							 rr::PRIMITIVETYPE_TRIANGLES,
							 std::vector<Vertex4RGBA>(cwVertices.begin() + quadNdx * 6,
													  cwVertices.begin() + (quadNdx + 1) * 6));
		}
	}

	// Compare result with reference image
	if (m_colorAttachmentEnable)
	{
		const DeviceInterface&				vk					= m_context.getDeviceInterface();
		const VkDevice						vkDevice			= m_context.getDevice();
		const VkQueue						queue				= m_context.getUniversalQueue();
		const deUint32						queueFamilyIndex	= m_context.getUniversalQueueFamilyIndex();
		SimpleAllocator						allocator			(vk, vkDevice, getPhysicalDeviceMemoryProperties(m_context.getInstanceInterface(), m_context.getPhysicalDevice()));
		de::UniquePtr<tcu::TextureLevel>	result				(readColorAttachment(vk, vkDevice, queue, queueFamilyIndex, allocator, *m_colorImage, m_colorFormat, m_renderSize).release());

		colorCompareOk = tcu::intThresholdPositionDeviationCompare(m_context.getTestContext().getLog(),
																   "IntImageCompare",
																   "Image comparison",
																   refRenderer.getAccess(),
																   result->getAccess(),
																   tcu::UVec4(2, 2, 2, 2),
																   tcu::IVec3(1, 1, 0),
																   true,
																   tcu::COMPARE_LOG_RESULT);
	}
	else
	{
		colorCompareOk = true;
	}

	// Compare stencil result with reference image
	{
		const DeviceInterface&				vk					= m_context.getDeviceInterface();
		const VkDevice						vkDevice			= m_context.getDevice();
		const VkQueue						queue				= m_context.getUniversalQueue();
		const deUint32						queueFamilyIndex	= m_context.getUniversalQueueFamilyIndex();
		SimpleAllocator						allocator			(vk, vkDevice, getPhysicalDeviceMemoryProperties(m_context.getInstanceInterface(), m_context.getPhysicalDevice()));
		de::UniquePtr<tcu::TextureLevel>	result				(readStencilAttachment(vk, vkDevice, queue, queueFamilyIndex, allocator, *m_stencilImage, m_stencilFormat, m_renderSize).release());

		{
			const tcu::PixelBufferAccess stencilAccess (tcu::getEffectiveDepthStencilAccess(refRenderer.getDepthStencilAccess(), tcu::Sampler::MODE_STENCIL));
			stencilCompareOk = tcu::intThresholdPositionDeviationCompare(m_context.getTestContext().getLog(),
																		 "StencilImageCompare",
																		 "Stencil image comparison",
																		 stencilAccess,
																		 result->getAccess(),
																		 tcu::UVec4(2, 2, 2, 2),
																		 tcu::IVec3(1, 1, 0),
																		 true,
																		 tcu::COMPARE_LOG_RESULT);
		}
	}

	if (colorCompareOk && stencilCompareOk)
		return tcu::TestStatus::pass("Result image matches reference");
	else
		return tcu::TestStatus::fail("Image mismatch");
}

// Utilities for test names

const char* getShortName (VkStencilOp stencilOp)
{
	switch (stencilOp)
	{
		case VK_STENCIL_OP_KEEP:					return "keep";
		case VK_STENCIL_OP_ZERO:					return "zero";
		case VK_STENCIL_OP_REPLACE:					return "repl";
		case VK_STENCIL_OP_INCREMENT_AND_CLAMP:		return "incc";
		case VK_STENCIL_OP_DECREMENT_AND_CLAMP:		return "decc";
		case VK_STENCIL_OP_INVERT:					return "inv";
		case VK_STENCIL_OP_INCREMENT_AND_WRAP:		return "wrap";
		case VK_STENCIL_OP_DECREMENT_AND_WRAP:		return "decw";

		default:
			DE_FATAL("Invalid VkStencilOpState value");
	}
	return DE_NULL;
}

std::string getStencilStateSetDescription(const VkStencilOpState& stencilOpStateFront,
										  const VkStencilOpState& stencilOpStateBack)
{
	std::ostringstream desc;

	desc << "\nFront faces:\n" << stencilOpStateFront;
	desc << "Back faces:\n" << stencilOpStateBack;

	return desc.str();
}

std::string getFormatCaseName (VkFormat format)
{
	const std::string fullName = getFormatName(format);

	DE_ASSERT(de::beginsWith(fullName, "VK_FORMAT_"));

	return de::toLower(fullName.substr(10));
}

} // anonymous

tcu::TestCaseGroup* createStencilTests (tcu::TestContext& testCtx)
{
	const VkFormat stencilFormats[] =
	{
		VK_FORMAT_S8_UINT,
		VK_FORMAT_D16_UNORM_S8_UINT,
		VK_FORMAT_D24_UNORM_S8_UINT,
		VK_FORMAT_D32_SFLOAT_S8_UINT
	};

	DE_STATIC_ASSERT(DE_LENGTH_OF_ARRAY(compareOps) == 8);
	DE_STATIC_ASSERT(vk::VK_COMPARE_OP_LAST == 8);

	static const char* compareOpNames[8] =
	{
		"comp_never",
		"comp_less",
		"comp_equal",
		"comp_less_or_equal",
		"comp_greater",
		"comp_not_equal",
		"comp_greater_or_equal",
		"comp_always"
	};

	de::MovePtr<tcu::TestCaseGroup>		stencilTests				(new tcu::TestCaseGroup(testCtx, "stencil", "Stencil tests"));
	de::MovePtr<tcu::TestCaseGroup>		noColorAttachmentTests		(new tcu::TestCaseGroup(testCtx, "nocolor", "Stencil tests with no color attachment"));
	const bool							colorAttachmentEnabled[]	= { true, false };

	for (deUint32 colorAttachmentEnabledIdx = 0; colorAttachmentEnabledIdx < DE_LENGTH_OF_ARRAY(colorAttachmentEnabled); colorAttachmentEnabledIdx++)
	{
		const bool							colorEnabled				= colorAttachmentEnabled[colorAttachmentEnabledIdx];
		de::MovePtr<tcu::TestCaseGroup>		formatTests					(new tcu::TestCaseGroup(testCtx, "format", "Uses different stencil formats"));
		StencilOpStateUniqueRandomIterator	stencilOpItr				(123);

		for (size_t formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(stencilFormats); formatNdx++)
		{
			const VkFormat	stencilFormat				= stencilFormats[formatNdx];
			const bool		hasDepth					= tcu::hasDepthComponent(mapVkFormat(stencilFormat).order);
			const bool		hasStencil					= tcu::hasStencilComponent(mapVkFormat(stencilFormat).order);
			const int		separateLayoutsLoopCount	= (hasDepth && hasStencil) ? 2 : 1;

			for (int separateDepthStencilLayouts = 0; separateDepthStencilLayouts < separateLayoutsLoopCount; ++separateDepthStencilLayouts)
			{
				const bool			useSeparateDepthStencilLayouts	= bool(separateDepthStencilLayouts);

				de::MovePtr<tcu::TestCaseGroup>	formatTest		(new tcu::TestCaseGroup(testCtx,
																						(getFormatCaseName(stencilFormat) + ((useSeparateDepthStencilLayouts) ? "_separate_layouts" : "")).c_str(),
																						(std::string("Uses format ") + getFormatName(stencilFormat) + ((useSeparateDepthStencilLayouts) ? " with separate depth/stencil layouts" : "")).c_str()));

				de::MovePtr<tcu::TestCaseGroup>	stencilStateTests;
				{
					std::ostringstream desc;
					desc << "Draws 4 quads with the following depths and dynamic stencil states: ";

					for (int quadNdx = 0; quadNdx < StencilTest::QUAD_COUNT; quadNdx++)
					{
						const StencilTest::StencilStateConfig& stencilConfig = StencilTest::s_stencilStateConfigs[quadNdx];

						desc << "(" << quadNdx << ") "
							 << "z = " << StencilTest::s_quadDepths[quadNdx] << ", "
							 << "frontReadMask = " << stencilConfig.frontReadMask << ", "
							 << "frontWriteMask = " << stencilConfig.frontWriteMask << ", "
							 << "frontRef = " << stencilConfig.frontRef << ", "
							 << "backReadMask = " << stencilConfig.backReadMask << ", "
							 << "backWriteMask = " << stencilConfig.backWriteMask << ", "
							 << "backRef = " << stencilConfig.backRef;
					}

					stencilStateTests = de::MovePtr<tcu::TestCaseGroup>(new tcu::TestCaseGroup(testCtx, "states", desc.str().c_str()));
				}

				stencilOpItr.reset();

				for (deUint32 failOpNdx = 0u; failOpNdx < DE_LENGTH_OF_ARRAY(stencilOps); failOpNdx++)
				{
					const std::string				failOpName	= std::string("fail_") + getShortName(stencilOps[failOpNdx]);
					de::MovePtr<tcu::TestCaseGroup>	failOpTest	(new tcu::TestCaseGroup(testCtx, failOpName.c_str(), ""));

					for (deUint32 passOpNdx = 0u; passOpNdx < DE_LENGTH_OF_ARRAY(stencilOps); passOpNdx++)
					{
						const std::string				passOpName	= std::string("pass_") + getShortName(stencilOps[passOpNdx]);
						de::MovePtr<tcu::TestCaseGroup>	passOpTest	(new tcu::TestCaseGroup(testCtx, passOpName.c_str(), ""));

						for (deUint32 dFailOpNdx = 0u; dFailOpNdx < DE_LENGTH_OF_ARRAY(stencilOps); dFailOpNdx++)
						{
							const std::string				dFailOpName	= std::string("dfail_") + getShortName(stencilOps[dFailOpNdx]);
							de::MovePtr<tcu::TestCaseGroup>	dFailOpTest	(new tcu::TestCaseGroup(testCtx, dFailOpName.c_str(), ""));

							for (deUint32 compareOpNdx = 0u; compareOpNdx < DE_LENGTH_OF_ARRAY(compareOps); compareOpNdx++)
							{
								// Iterate front set of stencil state in ascending order
								const VkStencilOpState	stencilStateFront	=
								{
									stencilOps[failOpNdx],		// failOp
									stencilOps[passOpNdx],		// passOp
									stencilOps[dFailOpNdx],		// depthFailOp
									compareOps[compareOpNdx],	// compareOp
									0x0,						// compareMask
									0x0,						// writeMask
									0x0							// reference
								};

								// Iterate back set of stencil state in random order
								const VkStencilOpState	stencilStateBack	= stencilOpItr.next();
								const std::string		caseName			= compareOpNames[compareOpNdx];
								const std::string		caseDesc			= getStencilStateSetDescription(stencilStateFront, stencilStateBack);

								dFailOpTest->addChild(new StencilTest(testCtx, caseName, caseDesc, stencilFormat, stencilStateFront, stencilStateBack, colorEnabled, useSeparateDepthStencilLayouts));
							}
							passOpTest->addChild(dFailOpTest.release());
						}
						failOpTest->addChild(passOpTest.release());
					}
					stencilStateTests->addChild(failOpTest.release());
				}

				formatTest->addChild(stencilStateTests.release());
				formatTests->addChild(formatTest.release());
			}
		}

		if (colorEnabled)
			stencilTests->addChild(formatTests.release());
		else
			noColorAttachmentTests->addChild(formatTests.release());
	}

	stencilTests->addChild(noColorAttachmentTests.release());

	return stencilTests.release();
}

} // pipeline
} // vkt


text:
/*global document, jQuery*/
jQuery.fn.voteWidget = function (activityLog, alert) {
	'use strict';
	return this.each(function () {
		var element = jQuery(this);
		element.on('show', function () {
			element.find('input:checked').attr('checked', false);
			element.find('[name=other]').val('');
		});
		jQuery('#sendVote').click(function () {
			var val = element.find('input:checked').val() || element.find('[name=other]').val();
			if (val) {
				activityLog.log('Feature Vote', val);
				alert.show('Thanks for voting', 'We\'ll do our best to roll popular features out quickly', 'success');
			} else {
				return false;
			}
		});
		if (document.location.hash === '#vote') {
			element.modal('show');
		}
	});
};

redpajama_set_name: RedPajamaGithub


text:
import wap
import random
import qBotLib

print "\n You won't believe but i am a bot. Ask me anything\n";

while 1:

    qBotLib.resetBotParts();

    question=raw_input('\n> ');

    if qBotLib.isQuestionProfane(question)==1:
        print qBotLib.proFaneMsg_array[random.randint(0,1)];

    elif qBotLib.isQuestionOverriden(question)!=-1:
        print qBotLib.overridenQAns[qBotLib.isQuestionOverriden(question)];

    else:

        waeo = wap.WolframAlphaEngine(qBotLib.appid, qBotLib.server);
        queryStr = waeo.CreateQuery(question);
        wap.WolframAlphaQuery(queryStr, qBotLib.appid);
        result = waeo.PerformQuery(queryStr);
        result = wap.WolframAlphaQueryResult(result);

        for pod in result.Pods():
            waPod = wap.Pod(pod);
            title = waPod.Title()[0];
            if  title == "Result":
                qBotLib.findAnswer(waPod);
                qBotLib.updateNoAnsFlag(1);
                break;

            #Check if we have any reply from Knowledge engine
        if qBotLib.noAns!=1:
            print qBotLib.preDefinedMsg_array[random.randint(0,1)];


text:
<!doctype html>
<meta charset="UTF-8">
<title>IMAGE EDITOR</title>
<form id="image-select-form">
  <fieldset>
    <legend>File</legend>
    <input accept="image/*" id="user-select-images" multiple required type="file">
  </fieldset>
</form>
<script src="./script/main.js"></script>


text:
release_hdr := $(shell sh -c './mkreleasehdr.sh')
uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not')
OPTIMIZATION?=-O2
DEPENDENCY_TARGETS=hiredis linenoise lua

# Default settings
STD=-std=c99 -pedantic -DREDIS_STATIC=''
WARN=-Wall -W
OPT=$(OPTIMIZATION)

PREFIX?=/usr/local
INSTALL_BIN=$(PREFIX)/bin
INSTALL=install

# Default allocator
ifeq ($(uname_S),Linux)
	MALLOC=jemalloc
else
	MALLOC=libc
endif

# Backwards compatibility for selecting an allocator
ifeq ($(USE_TCMALLOC),yes)
	MALLOC=tcmalloc
endif

ifeq ($(USE_TCMALLOC_MINIMAL),yes)
	MALLOC=tcmalloc_minimal
endif

ifeq ($(USE_JEMALLOC),yes)
	MALLOC=jemalloc
endif

ifeq ($(USE_JEMALLOC),no)
	MALLOC=libc
endif

# Override default settings if possible
-include .make-settings

FINAL_CFLAGS=$(STD) $(WARN) $(OPT) $(DEBUG) $(CFLAGS) $(REDIS_CFLAGS)
FINAL_LDFLAGS=$(LDFLAGS) $(REDIS_LDFLAGS) $(DEBUG)
FINAL_LIBS=-lm
DEBUG=-g -ggdb

ifeq ($(uname_S),SunOS)
	# SunOS
	INSTALL=cp -pf
	FINAL_CFLAGS+= -D__EXTENSIONS__ -D_XPG6
	FINAL_LIBS+= -ldl -lnsl -lsocket -lresolv -lpthread -lrt
else
ifeq ($(uname_S),Darwin)
	# Darwin (nothing to do)
else
ifeq ($(uname_S),AIX)
        # AIX
        FINAL_LDFLAGS+= -Wl,-bexpall
        FINAL_LIBS+= -pthread -lcrypt -lbsd

else
	# All the other OSes (notably Linux)
	FINAL_LDFLAGS+= -rdynamic
	FINAL_LIBS+= -pthread
endif
endif
endif
# Include paths to dependencies
FINAL_CFLAGS+= -I../deps/hiredis -I../deps/linenoise -I../deps/lua/src

ifeq ($(MALLOC),tcmalloc)
	FINAL_CFLAGS+= -DUSE_TCMALLOC
	FINAL_LIBS+= -ltcmalloc
endif

ifeq ($(MALLOC),tcmalloc_minimal)
	FINAL_CFLAGS+= -DUSE_TCMALLOC
	FINAL_LIBS+= -ltcmalloc_minimal
endif

ifeq ($(MALLOC),jemalloc)
	DEPENDENCY_TARGETS+= jemalloc
	FINAL_CFLAGS+= -DUSE_JEMALLOC -I../deps/jemalloc/include
	FINAL_LIBS+= ../deps/jemalloc/lib/libjemalloc.a -ldl
endif

REDIS_CC=$(QUIET_CC)$(CC) $(FINAL_CFLAGS)
REDIS_LD=$(QUIET_LINK)$(CC) $(FINAL_LDFLAGS)
REDIS_INSTALL=$(QUIET_INSTALL)$(INSTALL)

CCCOLOR="\033[34m"
LINKCOLOR="\033[34;1m"
SRCCOLOR="\033[33m"
BINCOLOR="\033[37;1m"
MAKECOLOR="\033[32;1m"
ENDCOLOR="\033[0m"

ifndef V
QUIET_CC = @printf '    %b %b\n' $(CCCOLOR)CC$(ENDCOLOR) $(SRCCOLOR)$@$(ENDCOLOR) 1>&2;
QUIET_LINK = @printf '    %b %b\n' $(LINKCOLOR)LINK$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2;
QUIET_INSTALL = @printf '    %b %b\n' $(LINKCOLOR)INSTALL$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2;
endif

REDIS_SERVER_NAME=redis-server
REDIS_SENTINEL_NAME=redis-sentinel
REDIS_SERVER_OBJ=adlist.o quicklist.o ae.o anet.o dict.o redis.o sds.o zmalloc.o lzf_c.o lzf_d.o pqsort.o zipmap.o sha1.o ziplist.o release.o networking.o util.o object.o db.o replication.o rdb.o t_string.o t_list.o t_set.o t_zset.o t_hash.o config.o aof.o pubsub.o multi.o debug.o sort.o intset.o syncio.o cluster.o crc16.o endianconv.o slowlog.o scripting.o bio.o rio.o rand.o memtest.o crc64.o bitops.o sentinel.o notify.o setproctitle.o blocked.o hyperloglog.o latency.o sparkline.o redis-check-rdb.o hedis.o
REDIS_CLI_NAME=redis-cli
REDIS_CLI_OBJ=anet.o sds.o adlist.o redis-cli.o zmalloc.o release.o anet.o ae.o crc64.o
REDIS_BENCHMARK_NAME=redis-benchmark
REDIS_BENCHMARK_OBJ=ae.o anet.o redis-benchmark.o sds.o adlist.o zmalloc.o redis-benchmark.o
REDIS_CHECK_RDB_NAME=redis-check-rdb
REDIS_CHECK_AOF_NAME=redis-check-aof
REDIS_CHECK_AOF_OBJ=redis-check-aof.o

all: $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_RDB_NAME) $(REDIS_CHECK_AOF_NAME)
	@echo ""
	@echo "Hint: It's a good idea to run 'make test' ;)"
	@echo ""

.PHONY: all

# Deps (use make dep to generate this)
include Makefile.dep

dep:
	$(REDIS_CC) -MM *.c > Makefile.dep

.PHONY: dep

persist-settings: distclean
	echo STD=$(STD) >> .make-settings
	echo WARN=$(WARN) >> .make-settings
	echo OPT=$(OPT) >> .make-settings
	echo MALLOC=$(MALLOC) >> .make-settings
	echo CFLAGS=$(CFLAGS) >> .make-settings
	echo LDFLAGS=$(LDFLAGS) >> .make-settings
	echo REDIS_CFLAGS=$(REDIS_CFLAGS) >> .make-settings
	echo REDIS_LDFLAGS=$(REDIS_LDFLAGS) >> .make-settings
	echo PREV_FINAL_CFLAGS=$(FINAL_CFLAGS) >> .make-settings
	echo PREV_FINAL_LDFLAGS=$(FINAL_LDFLAGS) >> .make-settings
	-(cd ../deps && $(MAKE) $(DEPENDENCY_TARGETS))

.PHONY: persist-settings

# Prerequisites target
.make-prerequisites:
	@touch $@

# Clean everything, persist settings and build dependencies if anything changed
ifneq ($(strip $(PREV_FINAL_CFLAGS)), $(strip $(FINAL_CFLAGS)))
.make-prerequisites: persist-settings
endif

ifneq ($(strip $(PREV_FINAL_LDFLAGS)), $(strip $(FINAL_LDFLAGS)))
.make-prerequisites: persist-settings
endif

# redis-server
$(REDIS_SERVER_NAME): $(REDIS_SERVER_OBJ)
	$(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a ../deps/lua/src/liblua.a $(FINAL_LIBS)

# redis-sentinel
$(REDIS_SENTINEL_NAME): $(REDIS_SERVER_NAME)
	$(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME)

# redis-check-rdb
$(REDIS_CHECK_RDB_NAME): $(REDIS_SERVER_NAME)
	$(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(REDIS_CHECK_RDB_NAME)

# redis-cli
$(REDIS_CLI_NAME): $(REDIS_CLI_OBJ)
	$(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a ../deps/linenoise/linenoise.o $(FINAL_LIBS)

# redis-benchmark
$(REDIS_BENCHMARK_NAME): $(REDIS_BENCHMARK_OBJ)
	$(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a $(FINAL_LIBS)

# redis-check-aof
$(REDIS_CHECK_AOF_NAME): $(REDIS_CHECK_AOF_OBJ)
	$(REDIS_LD) -o $@ $^ $(FINAL_LIBS)

# Because the jemalloc.h header is generated as a part of the jemalloc build,
# building it should complete before building any other object. Instead of
# depending on a single artifact, build all dependencies first.
%.o: %.c .make-prerequisites
	$(REDIS_CC) -c $<

clean:
	rm -rf $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_RDB_NAME) $(REDIS_CHECK_AOF_NAME) *.o *.gcda *.gcno *.gcov redis.info lcov-html

.PHONY: clean

distclean: clean
	-(cd ../deps && $(MAKE) distclean)
	-(rm -f .make-*)

.PHONY: distclean

test: $(REDIS_SERVER_NAME) $(REDIS_CHECK_AOF_NAME)
	@(cd ..; ./runtest)

test-sentinel: $(REDIS_SENTINEL_NAME)
	@(cd ..; ./runtest-sentinel)

check: test

lcov:
	$(MAKE) gcov
	@(set -e; cd ..; ./runtest --clients 1)
	@geninfo -o redis.info .
	@genhtml --legend -o lcov-html redis.info

test-sds: sds.c sds.h
	$(REDIS_CC) sds.c zmalloc.c -DSDS_TEST_MAIN -o /tmp/sds_test
	/tmp/sds_test

.PHONY: lcov

bench: $(REDIS_BENCHMARK_NAME)
	./$(REDIS_BENCHMARK_NAME)

32bit:
	@echo ""
	@echo "WARNING: if it fails under Linux you probably need to install libc6-dev-i386"
	@echo ""
	$(MAKE) CFLAGS="-m32" LDFLAGS="-m32"

gcov:
	$(MAKE) REDIS_CFLAGS="-fprofile-arcs -ftest-coverage -DCOVERAGE_TEST" REDIS_LDFLAGS="-fprofile-arcs -ftest-coverage"

noopt:
	$(MAKE) OPTIMIZATION="-O0"

valgrind:
	$(MAKE) OPTIMIZATION="-O0" MALLOC="libc"

src/help.h:
	@../utils/generate-command-help.rb > help.h

install: all
	@mkdir -p $(INSTALL_BIN)
	$(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(INSTALL_BIN)
	$(REDIS_INSTALL) $(REDIS_BENCHMARK_NAME) $(INSTALL_BIN)
	$(REDIS_INSTALL) $(REDIS_CLI_NAME) $(INSTALL_BIN)
	$(REDIS_INSTALL) $(REDIS_CHECK_RDB_NAME) $(INSTALL_BIN)
	$(REDIS_INSTALL) $(REDIS_CHECK_AOF_NAME) $(INSTALL_BIN)
	@ln -sf $(REDIS_SERVER_NAME) $(INSTALL_BIN)/$(REDIS_SENTINEL_NAME)


text:
import * as url from 'url'
import * as path from 'path'
import * as fs from 'fs-extra'
import * as _ from 'lodash'
import { Request } from '../class'
import { RequestType, LangTypes } from '../declare'
import util, { config } from '../util'

// check if the directory is a package.json dir
const packageMainCache = Object.create(null)

const requestPathCache = Object.create(null)

function getStat (requestPath: string) {
  let isFile = util.isFile(requestPath)
  let isDir = isFile ? false : util.isDir(requestPath)
  return {
    isFile,
    isDir
  }
}

function readPackageMain (requestPath: string) {
  let pkgMain = ''
  let entry = packageMainCache[requestPath]
  if (entry) {
    return entry
  }

  let jsonPath = path.resolve(requestPath, 'package.json')

  if (!fs.existsSync(jsonPath)) {
    return false
  }

  try {
    let json = fs.readJsonSync(jsonPath)
    pkgMain = packageMainCache[requestPath] = json.main
  } catch (err) {
    err.path = jsonPath
    err.message = 'Error parsing ' + jsonPath + ': ' + err.message
    throw err
  }
  return pkgMain
}

function tryPackage (requestPath: string, exts: string[]) {
  let pkgMain = readPackageMain(requestPath)

  if (!pkgMain) {
    return false
  }

  let filename = path.resolve(requestPath, pkgMain)
  return tryFile(filename) ||
         tryExtensions(filename, exts) ||
         tryExtensions(path.resolve(filename, 'index'), exts)
}

function tryFile (requestPath: string) {
  return getStat(requestPath).isFile && requestPath
}

// given a path check a the file exists with any of the set extensions
function tryExtensions (requestPath: string, exts: string[]) {
  for (let i = 0; i < exts.length; i++) {
    let filename = tryFile(requestPath + exts[i])

    if (filename) {
      return filename
    }
  }
  return false
}

/**
 * 检测请求类型是否包含 config.alias 比如
 * ① request = @scope/wxc-loading => true
 * ② request = components/example => true
 * ③ request = ./hello/index => false
 *
 * @param {string} request
 * @returns
 */
function inAlias (request: string): boolean {
  return getAlias(request) !== null
}

function getAlias (request: string): {name: string, value: string} | null {
  let spes = request.split('/')

  for (let key in config.alias) {
    if (spes[0] === key) {
      return {
        name: key,
        value: config.alias[key]
      }
    }
  }
  return null
}

/**
 * 检测请求类型是否包含 config.scope 比如
 * ① request = @scope/wxc-loading => true
 * ② request = components/example => false
 * ③ request = ./hello/index => false
 *
 * @param {string} request
 * @returns
 */
function inScope (request: string): boolean {
  let spes = request.split('/')
  return spes[0] === config.npm.scope
}

/**
 * 判断是否为wxc组件
 *
 * @param {string} request
 * @returns {boolean}
 */
function isWxcPackage (request: string, requestType: RequestType): boolean {
  // isWXC && @scope/wxc- => true
  // isWXC && wxc-loading => true
  // isWXC && ./index.wxc => false
  // isWXC && alias/wxc-toast => false
  // isWXC && src/... => false
  // isWXC && packages/... => false

  if (requestType !== RequestType.WXC) {
    return false
  }
  if (request.charAt(0) === '.') {
    return false
  }
  if (request.split('/')[0] === config.src) {
    return false
  }
  if (request.split('/')[0] === config.packages) {
    return false
  }
  if (!inScope(request) && inAlias(request)) {
    return false
  }
  return true
}

function src2destRelative (srcRelative: string, isPublish?: boolean) {
  // let ext = path.extname(srcRelative)
  let destRelative = srcRelative

  if (!isPublish) {
    // source => dist
    destRelative = destRelative.replace(new RegExp(`^${config.src}`), config.dest)
  }

  // packages => dist/packages
  destRelative = destRelative.replace(new RegExp(`^${config.packages}`), (match) => {
    return config.npm.dest
  })

  // node_modules => dist/npm/wxcs
  // path/node_modules => path/npm/wxcs
  destRelative = destRelative.replace(new RegExp(`(^|\\${path.sep})${config.npm.src}`, 'ig'), (match, $1) => {
    // let npm = ext === config.ext.wxc ? config.npm.dest.wxcs : config.npm.dest.modules
    let npmDest = config.npm.dest

    if ($1 === '') {
      // node_modules => dist/npm/wxcs
      // node_modules => dist/npm/modules
      return npmDest
    } else if ($1 === path.sep) {
      // path/node_modules => path/npm/wxcs
      // path/node_modules => path/npm/modules
      return npmDest.split(path.sep).slice(1).join(path.sep)
    } else {
      return match
    }
  })

  // /wxc-hello/src/ => /wxc-hello/dist/
  destRelative = destRelative.replace(new RegExp(`(\\${path.sep}${config.prefixStr}[a-z-]+\\${path.sep})([a-z]+)`), (match, $1, $2) => {
    if ($2 === config.package.src) {
      return `${$1}${config.package.dest}`
    }
    return match
  })
  return destRelative
}

function getRequestType (ext: string): RequestType | undefined {
  let { requestType = undefined } = LangTypes[ext] || {}
  return requestType
}

function getRequestLookupExts (requestType: RequestType): string[] {
  let exts: string[] = []

  _.forIn(LangTypes, (value, key) => {
    if (requestType === value.requestType) {
      exts.push(key)
    }
  })

  return exts
}

/**
 * 返回匹配的请求后缀和请求类型
 * ① 通过扩展名匹配,优先返回与扩展名匹配的`后缀`和`请求类型`
 * ② 未匹配到,默认是`.js 后缀` 和`REQUEST_JS 请求类型`
 *
 * @param {string} request
 * @param {RequestType} [requestType]
 * @returns {{exts: string[], requestType: RequestType}}
 */
function getMatchRequest (request: string, requestType?: RequestType): {lookupExts: string[], requestType: RequestType} {
  let ext = path.extname(request)
  let exts: string[] = []

  // 非白名单内的扩展名,默认通过 requestType 来获取 ext 扩展名
  if (ext) {
    ext = _.findKey(config.ext, value => value === ext) ? ext : ''
  }

  if (!ext && !requestType) {
    throw new Error(`Ext 和 RequestType 不能同时为空`)
  }

  if (ext && requestType) {
    if (getRequestType(ext) !== requestType) {
      throw new Error(`Ext 和 RequestType 同时存在,但通过 Ext 找到的 RequestType 与实际的不符合`)
    }
  } else if (!ext && requestType) {
    exts = [
      ...exts,
      ...getRequestLookupExts(requestType)
    ]
  } else if (ext && !requestType) {
    requestType = getRequestType(ext)
  }

  if (!requestType) {
    throw new Error('没有找到匹配的 RequestType,请确认是否将 Ext 与 RequestType 进行关联')
  }

  return {
    lookupExts: exts,
    requestType
  }
}

// 补充扩展名
function supExtName (filePath: string, defExtName = config.ext.js) {
  if (path.extname(filePath) === '') {
    return `${filePath}${defExtName}`
  }
  return filePath
}

function findPath (request: string, requestType: RequestType, paths: string[], exts: string[]): any {
  if (!paths || paths.length === 0) {
    return false
  }

  let cacheKey = request + '\x00' + (paths.length === 1 ? paths[0] : paths.join('\x00'))
  let entry = requestPathCache[cacheKey]
  if (entry) {
    if (util.isFile(entry)) {
      return entry
    } else {
      delete requestPathCache[cacheKey]
    }
  }

  let trailingSlash = request.length > 0 &&
                      request.charCodeAt(request.length - 1) === 47 /* / */

  // For each path
  for (let i = 0; i < paths.length; i++) {
    let curPath = paths[i]
    let curRequest = request

    if (!curPath || !getStat(curPath).isDir) {
      continue
    }

    if (isWxcPackage(curRequest, requestType)) {
      // @scope/wxc-hello => ['@scope', 'wxc-hello']
      // @scope/wxc-hello/index => ['@scope', 'wxc-hello', 'index']
      // wxc-hello => ['wxc-hello']
      // wxc-hello/index => ['wxc-hello', 'index']
      let seps = curRequest.split('/')
      let scope = ''
      if (seps.length > 0 && seps[0].startsWith('@')) { // ['@scope', 'wxc-hello', ...]
        if (seps.length === 1) {  // ['@scope']
          throw new Error(`引用路径错误${curRequest}`)
        }
        // ['@scope', 'wxc-hello', ...] => @scope
        scope = seps[0]
        // ['@scope', 'wxc-loading', ...] => ['wxc-loading', ...]
        seps.shift()
      }

      // ['wxc-hello', ...]
      if (seps.length === 1) {
        // ['wxc-hello'] => ['wxc-hello', 'src', 'index']
        seps = seps.concat([config.package.src, config.package.default])
      } else if (seps.length > 1 && seps[1] !== 'src') {
        // ['wxc-hello', 'index'] => ['wxc-hello', 'src', 'index']
        seps.splice(1, 0, config.package.src)
      }

      if (scope) {
        seps.unshift(scope)
      }
      curRequest = seps.join('/')
    }

    // 当巡回的路径与 cwd 相同时,开始匹配 alias 别名路径
    if (curPath === config.cwd) {
      let alias = getAlias(curRequest)
      if (alias) {
        let spes = curRequest.split('/')
        spes.shift()
        spes.unshift(alias.value)

        // request = 'components/example' => 'source/components/example'
        // request = '@scope/wxc-hello/src/index' => 'source/packages/wxc-hello/src/index'
        curRequest = spes.join('/')
      }
    }

    // TODO 简陋版
    // 支持 package.json 的 browser
    let curPathPkgPath = path.join(curPath, 'package.json')
    if (/node_modules\//.test(curPath) && fs.existsSync(curPathPkgPath)) {
      let { browser = {} } = fs.readJSONSync(curPathPkgPath)

      for (const key in browser) {
        let aPath = supExtName(path.join(curPath, key))
        let bPath = supExtName(path.join(curPath, curRequest))
        if (aPath === bPath) {
          curRequest = browser[key]
        }
      }
    }

    let basePath = path.resolve(curPath, curRequest)
    let filename
    let stat = getStat(basePath)

    // index or index.js
    if (!trailingSlash) {
      if (stat.isFile) { // File.
        filename = basePath
      } else if (stat.isDir) { // Directory.
        filename = tryPackage(basePath, exts)
      }

      if (!filename) {
        // try it with each of the extensions
        filename = tryExtensions(basePath, exts)
      }
    }

    if (!filename && stat.isDir) {  // Directory.
      filename = tryPackage(basePath, exts)
    }

    if (!filename && stat.isDir) {  // Directory.
      // try it with each of the extensions at "index"
      filename = tryExtensions(path.resolve(basePath, 'index'), exts)
    }

    if (filename) {
      requestPathCache[cacheKey] = filename
      return filename
    }
  }
  return false
}

/**
 * 从 node_modules 和 source/packages 目录下,就近原则返回匹配的 node_modules 目录
 *
 * @param {string} parent
 * @returns
 */
function resolveLookupNpmPaths (parent: string) {
  let paths = [path.join(config.cwd, 'node_modules')]

  // 'node_modules/@scope/wxc-hello'
  // 'source/packages/wxc-hello'
  // 'source/pages/hello'
  let relPath = path.relative(config.cwd, parent)

  // 相对路径起始不包含 node_modules 或 source/packages,返回默认
  if (!new RegExp(`^(node_modules|${config.packages})\\${path.sep}`).test(relPath)) {
    return paths
  }

  // ['node_modules', '@scope', 'wxc-hello']
  // ['source', 'packages', 'wxc-hello']
  let spes = relPath.split(path.sep)

  for (let i = 0; i < spes.length; i++) {
    let name = spes[i]
    // node_modules
    // @scope
    if (name === 'node_modules' || name === config.npm.scope) {
      continue
    }

    let lookup = spes.slice(0, i + 1).join(path.sep)

    // 'source'
    // 'source/packages'
    if (lookup === config.src || lookup === config.packages) {
      continue
    }

    // 'node_modules/@scope/wxc-hello/node_modules'
    // 'source/packages/wxc-hello/node_modules'
    paths.unshift(
      path.join(config.cwd, lookup, 'node_modules')
    )
  }

  return paths
}

function resolveLookupPaths (request: string, parent?: string): string[] {
  // 父路径转换
  if (parent) {
    // 绝对路径
    parent = path.isAbsolute(parent) ? parent : path.join(config.cwd, parent)
    // 目录地址
    parent = util.isFile(parent) ? path.dirname(parent) : parent
  }

  // 在 Alias 内
  if (inAlias(request)) { // alias => {'components': 'source/components', '@scope': 'source/packages'}
    let paths = [
      config.cwd // 任何的别名默认从 cwd 里开始查找
    ]

    // 在 Scope 内
    if (inScope(request)) { // scope => '@scope'
      paths = [
        ...paths,
        ...resolveLookupNpmPaths(parent || config.cwd) // 再从 node_modules 里查找
      ]
    }
    return paths
  }

  let defRelPath = parent || config.getPath('src')

  // 相对路径,优先从 parent,再默认从 src 路径
  if (request.charAt(0) === '.') { // ./index
    return [defRelPath]
  }

  // 非点开始的相对路径,返回结果同上,只不过会判断在 parent 或 src 下当前文件是否存在
  if (request.charAt(0) !== '@' && path.extname(request).length > 1) { // index.js
    if (fs.existsSync(path.join(defRelPath, request))) {
      return [defRelPath]
    }
  }

  // 最后再从 packages 和 node_modules 里查找
  return [
    config.getPath('packages'),
    ...resolveLookupNpmPaths(parent || config.cwd)
  ]
}

export function resolveDep (requestOptions: Request.Options): Request.Core {
  let {
    request,
    requestType: type,
    parent,
    isMain,
    isPublish,
    isThreeNpm = false
  } = requestOptions

  if (!request && !parent) {
    throw new Error('依赖分析错误,request 和 parent 不能同时为空')
  }

  if (request && path.isAbsolute(request)) {
    if (isMain) {
      parent = path.dirname(request)
      request = `./${path.basename(request)}`
    } else {
      throw new Error(`依赖分析错误,非入口文件 request 不能为绝对路径`)
    }
  }

  if (!request && parent) {
    if (isMain) {
      parent = path.dirname(parent)
      request = `./${path.basename(parent)}`
    } else {
      throw new Error(`依赖分析错误,非入口文件 request 不能为空`)
    }
  }

  let rawRequest = url.parse(request).pathname || ''

  let {
    requestType,
    lookupExts
  } = getMatchRequest(rawRequest, type)

  let lookupPaths = resolveLookupPaths(rawRequest, parent)

  let srcRelative = ''
  let ext = ''
  let dest = ''
  let destRelative = ''
  let $isThreeNpm = false

  let src = findPath(rawRequest, requestType, lookupPaths, lookupExts) || ''
  if (src) {
    srcRelative = path.relative(config.cwd, src)
    ext = path.extname(src)
    destRelative = src2destRelative(srcRelative, isPublish)
    dest = path.join(config.cwd, destRelative)

    // 判定是否来自第三方NPM(NPM包中非WXC的都定位为第三方NPM包,主要是不走编译)
    if (srcRelative.split('/')[0] === 'node_modules') {
      if (rawRequest.charAt(0) === '.') { // 引用相对路径,继承父级
        $isThreeNpm = isThreeNpm
      } else if (ext !== config.ext.wxc) { // 所有的NPM包中,引用路径扩展非.wxc,都定位第三方NPM包
        $isThreeNpm = true
      }
    }
  }

  return {
    // for Request.Default
    request,
    requestType,

    // for Request.Path
    src,
    srcRelative,
    ext,
    dest,
    destRelative,

    isThreeNpm: $isThreeNpm
  }
}


text:
extern "C" {
typedef struct vpx_codec_ctx vpx_codec_ctx_t;
}

namespace remoting {

struct VpxCodecDeleter {
  void operator()(vpx_codec_ctx_t* codec);
};

typedef scoped_ptr<vpx_codec_ctx_t, VpxCodecDeleter> ScopedVpxCodec;

} // namespace remoting

#endif  // REMOTING_CODEC_SCOPED_VPX_CODEC_H_


text:
var config        = require('../../config.js').iconfont,
    errorHandler  = require('../../helpers/errorHandler.js'),
    gulp         	= require('gulp'),
    changed       = require('gulp-changed'),
    plumber       = require('gulp-plumber'),
    iconfont      = require('gulp-iconfont'),
    iconfontCss   = require('gulp-iconfont-css');

var runTimestamp = Math.round(Date.now()/1000);

gulp.task('iconfont', function() {
  return gulp.src(config.source + '/**/*.svg', {base: config.base})
    .pipe(changed(config.dist))
    .pipe(iconfontCss({
      // Defines the name of the font
      fontName: config.fontName,
      // Path to Template
      path: config.template,
      // Path to export the stylus file
      targetPath: config.exportTo,
      // Path printed on the CSS file to load the font
      fontPath: config.fontPath
    }))
    .pipe(iconfont({
      fontName: config.fontName,
      appendUnicode: true,
      timestamp: runTimestamp
    }))
    .pipe(gulp.dest(config.dist))
});


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using AutoRest.Core.Model;
using AutoRest.Core.Utilities;
using AutoRest.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;

namespace AutoRest.Go.Model
{
    /// <summary>
    /// Defines a synthesized composite type that wraps a primary type, array, or dictionary method response.
    /// </summary>
    public class CompositeTypeGo : CompositeType
    {
        private bool _wrapper;

        // True if the type is returned by a method
        public bool IsResponseType;

        // Name of the field containing the URL used to retrieve the next result set
        // (null or empty if the model is not paged).
        public string NextLink;

        public bool PreparerNeeded = false;

        public CompositeTypeGo()
        {

        }

        public CompositeTypeGo(string name) : base(name)
        {

        }

        public CompositeTypeGo(IModelType wrappedType)
        {
            if (!wrappedType.ShouldBeSyntheticType())
            {
                throw new ArgumentException("{0} is not a valid type for SyntheticType", wrappedType.ToString());
            }

            // gosdk: Ensure the generated name does not collide with existing type names
            BaseType = wrappedType;

            IModelType elementType = GetElementType(wrappedType);

            if (elementType is PrimaryType)
            {
                var type = (elementType as PrimaryType).KnownPrimaryType;
                switch (type)
                {
                    case KnownPrimaryType.Object:
                        Name += "SetObject";
                        break;

                    case KnownPrimaryType.Boolean:
                        Name += "Bool";
                        break;

                    case KnownPrimaryType.Double:
                        Name += "Float64";
                        break;

                    case KnownPrimaryType.Int:
                        Name += "Int32";
                        break;

                    case KnownPrimaryType.Long:
                        Name += "Int64";
                        break;

                    case KnownPrimaryType.Stream:
                        Name += "ReadCloser";
                        break;

                    default:
                        Name += type.ToString();
                        break;
                }
            }
            else if (elementType is EnumType)
            {
                Name += "String";
            }
            else
            {
                Name += elementType.Name;
            }

            // add the wrapped type as a property named Value
            var p = new PropertyGo();
            p.Name = "Value";
            p.SerializedName = "value";
            p.ModelType = wrappedType;
            Add(p);

            _wrapper = true;
        }

        /// <summary>
        /// Add imports for composite types.
        /// </summary>
        /// <param name="imports"></param>
        public void AddImports(HashSet<string> imports)
        {
            Properties.ForEach(p => p.ModelType.AddImports(imports));
        }

        public string Fields()
        {
            var indented = new IndentedStringBuilder("    ");
            var properties = Properties.Cast<PropertyGo>().ToList();

            if (BaseModelType != null)
            {
                indented.Append(((CompositeTypeGo)BaseModelType).Fields());
            }

            // If the type is a paged model type, ensure the nextLink field exists
            // Note: Inject the field into a copy of the property list so as to not pollute the original list
            if (!string.IsNullOrEmpty(NextLink))
            {
                var nextLinkField = NextLink;
                foreach (Property p in properties)
                {
                    p.Name = CodeNamerGo.PascalCaseWithoutChar(p.Name, '.');
                    if (p.Name.EqualsIgnoreCase(nextLinkField))
                    {
                        p.Name = nextLinkField;
                    }
                }

                var baseHasNextLink = false;
                if (BaseModelType != null)
                {
                    baseHasNextLink = BaseModelType.Properties.Any(p => p.Name.EqualsIgnoreCase(nextLinkField));
                }

                if (!baseHasNextLink && !properties.Any(p => p.Name.EqualsIgnoreCase(nextLinkField)))
                {
                    var property = new PropertyGo();
                    property.Name = nextLinkField;
                    property.ModelType = new PrimaryTypeGo(KnownPrimaryType.String);
                    properties.Add(property);
                }
            }

            // Emit each property, except for named Enumerated types, as a pointer to the type
            foreach (var property in properties)
            {
                var enumType = property.ModelType as EnumTypeGo;
                if (enumType != null && enumType.IsNamed)
                {
                    indented.AppendFormat("{0} {1} {2}\n",
                                    property.Name,
                                    enumType.Name,
                                    property.JsonTag());

                }
                else if (property.ModelType is DictionaryType)
                {
                    indented.AppendFormat("{0} *{1} {2}\n", property.Name, (property.ModelType as DictionaryTypeGo).Name, property.JsonTag());
                }
                else if (property.ModelType.PrimaryType(KnownPrimaryType.Object))
                {
                    // TODO: I don't think this is the best way to handle object types
                    indented.AppendFormat("{0} *{1} {2}\n", property.Name, property.ModelType.Name, property.JsonTag());
                }
                else if (property.ShouldBeFlattened())
                {
                    // embed as an anonymous struct.  note that the ordering of this clause is
                    // important, i.e. we don't want to flatten primary types like dictionaries.
                    indented.AppendFormat("*{0} {1}\n", property.ModelType.Name, property.JsonTag());
                    property.Extensions[SwaggerExtensions.FlattenOriginalTypeName] = Name;
                }
                else
                {
                    indented.AppendFormat("{0} *{1} {2}\n", property.Name, property.ModelType.Name, property.JsonTag());
                }
            }

            return indented.ToString();
        }

        public bool IsWrapperType => _wrapper;

        public IModelType BaseType { get; private set; }

        public IModelType GetElementType(IModelType type)
        {
            if (type is SequenceTypeGo)
            {
                Name += "List";
                return GetElementType((type as SequenceType).ElementType);
            }
            else if (type is DictionaryTypeGo)
            {
                Name += "Set";
                return GetElementType(((type as DictionaryTypeGo).ValueType));
            }
            else
            {
                return type;
            }
        }

        public string PreparerMethodName => $"{Name}Preparer";

        public void SetName(string name)
        {
            Name = name;
        }
    }
}


text:
IsAvailableChangedEventArgs Class
=================================

Represents the arguments for a KinectSensor's IsAvailableChanged event.

Syntax
======

<colgroup>
<col width="100%" />
</colgroup>

C++

public ref class IsAvailableChangedEventArgs sealed

<colgroup>
<col width="100%" />
</colgroup>

C#

public sealed class IsAvailableChangedEventArgs

| JavaScript                                                                             |
|----------------------------------------------------------------------------------------|
| /\* In JavaScript, properties of event data objects begin with a lowercase letter. \*/ |

Members
=======

**IsAvailableChangedEventArgs** has the following members.

Properties
==========

<colgroup>
<col width="30%" />
<col width="60%" />
</colgroup>

Name
Description

IsAvailable
Gets whether or not the KinectSensor is available.

Remarks
=======

Requirements
============

**Namespace:**WindowsPreview.Kinect
**Metadata:**windowspreview.kinect.winmd

See also
========

#### Reference

[WindowsPreview.Kinect Namespace](../Kinect.md)


text:
namespace peloton {
  namespace logging {
    class CheckpointFactory {
    public:
      static Checkpoint &GetInstance() {
        return SimpleCheckpoint::GetInstance();
      }
    };
  }
}


text:
@interface NSMutableArray (QueueAdditions)

- (id) pop;
- (id) queueHead;
- (id) dequeue;
- (void) enqueue:(id)obj;

@end


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<qualifiedTypeNameHistroy>
<fullyQualifiedTypeName name="java.io.InputStreamReader"/>
<fullyQualifiedTypeName name="android.R"/>
<fullyQualifiedTypeName name="android.R.layout"/>
<fullyQualifiedTypeName name="java.lang.Exception"/>
<fullyQualifiedTypeName name="com.finalProject.smstranslator.GoogleTranslator"/>
<fullyQualifiedTypeName name="android.widget.Toast"/>
<fullyQualifiedTypeName name="com.finalProject.smstranslator.MainActivity.AsyncTranslator"/>
<fullyQualifiedTypeName name="java.net.URLEncoder"/>
<fullyQualifiedTypeName name="java.lang.Object"/>
<fullyQualifiedTypeName name="com.finalProject.smstranslator.R.xml"/>
<fullyQualifiedTypeName name="android.content.res.Resources"/>
<fullyQualifiedTypeName name="android.content.res.XmlResourceParser"/>
<fullyQualifiedTypeName name="org.xmlpull.v1.XmlPullParser"/>
<fullyQualifiedTypeName name="android.util.Xml"/>
<fullyQualifiedTypeName name="org.xmlpull.v1.XmlPullParserException"/>
<fullyQualifiedTypeName name="java.io.IOException"/>
<fullyQualifiedTypeName name="java.lang.Boolean"/>
<fullyQualifiedTypeName name="java.io.InputStream"/>
<fullyQualifiedTypeName name="com.finalProject.smstranslator.LanguagesHandler"/>
<fullyQualifiedTypeName name="android.widget.Spinner"/>
<fullyQualifiedTypeName name="com.finalProject.smstranslator.R.layout"/>
<fullyQualifiedTypeName name="android.widget.ArrayAdapter"/>
<fullyQualifiedTypeName name="android.widget.BaseAdapter"/>
<fullyQualifiedTypeName name="android.widget.SpinnerAdapter"/>
<fullyQualifiedTypeName name="com.finalProject.smstranslator.Language"/>
<fullyQualifiedTypeName name="android.view.View"/>
<fullyQualifiedTypeName name="android.view.ViewGroup"/>
<fullyQualifiedTypeName name="android.widget.TextView"/>
<fullyQualifiedTypeName name="android.graphics.Color"/>
<fullyQualifiedTypeName name="com.finalProject.smstranslator.SettingsActivity.LanguagesAdapter"/>
<fullyQualifiedTypeName name="android.content.Intent"/>
<fullyQualifiedTypeName name="android.view.MenuItem"/>
<fullyQualifiedTypeName name="android.view.LayoutInflater"/>
<fullyQualifiedTypeName name="android.preference.ListPreference"/>
<fullyQualifiedTypeName name="java.lang.CharSequence"/>
<fullyQualifiedTypeName name="android.preference.PreferenceManager"/>
<fullyQualifiedTypeName name="com.finalProject.smstranslator.R.string"/>
<fullyQualifiedTypeName name="android.telephony.TelephonyManager"/>
<fullyQualifiedTypeName name="java.util.ArrayList"/>
<fullyQualifiedTypeName name="java.util.Dictionary"/>
<fullyQualifiedTypeName name="java.util.Map"/>
<fullyQualifiedTypeName name="java.util.HashMap"/>
<fullyQualifiedTypeName name="android.location.Geocoder"/>
<fullyQualifiedTypeName name="java.util.Locale"/>
<fullyQualifiedTypeName name="android.location.Criteria"/>
<fullyQualifiedTypeName name="android.location.LocationManager"/>
<fullyQualifiedTypeName name="android.location.Location"/>
<fullyQualifiedTypeName name="java.util.List"/>
<fullyQualifiedTypeName name="android.location.Address"/>
<fullyQualifiedTypeName name="com.finalProject.smstranslator.LanguageLogics"/>
<fullyQualifiedTypeName name="android.content.Context"/>
<fullyQualifiedTypeName name="com.finalProject.smstranslator.MainActivity"/>
<fullyQualifiedTypeName name="java.lang.String"/>
<fullyQualifiedTypeName name="com.finalProject.smstranslator.AsyncTranslator"/>
<fullyQualifiedTypeName name="com.finalProject.smstranslator.R.id"/>
<fullyQualifiedTypeName name="android.widget.EditText"/>
<fullyQualifiedTypeName name="android.widget.Button"/>
<fullyQualifiedTypeName name="android.widget.ImageButton"/>
<fullyQualifiedTypeName name="android.content.SharedPreferences"/>
<fullyQualifiedTypeName name="com.finalProject.smstranslator.activitys.MainActivity"/>
</qualifiedTypeNameHistroy>


text:
package org.javarosa.core.util.externalizable;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class ExtWrapNullable extends ExternalizableWrapper {
    public ExternalizableWrapper type;

    /* serialization */

    public ExtWrapNullable(Object val) {
        this.val = val;
    }

    /* deserialization */

    public ExtWrapNullable() {

    }

    public ExtWrapNullable(Class type) {
        this.type = new ExtWrapBase(type);
    }

    /* serialization or deserialization, depending on context */

    public ExtWrapNullable(ExternalizableWrapper type) {
        if (type instanceof ExtWrapNullable) {
            throw new IllegalArgumentException("Wrapping nullable with nullable is redundant");
        } else if (type != null && type.isEmpty()) {
            this.type = type;
        } else {
            this.val = type;
        }
    }

    @Override
    public ExternalizableWrapper clone(Object val) {
        return new ExtWrapNullable(val);
    }

    @Override
    public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
        if (in.readBoolean()) {
            val = ExtUtil.read(in, type, pf);
        } else {
            val = null;
        }
    }

    @Override
    public void writeExternal(DataOutputStream out) throws IOException {
        if (val != null) {
            out.writeBoolean(true);
            ExtUtil.write(out, val);
        } else {
            out.writeBoolean(false);
        }
    }

    @Override
    public void metaReadExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
        type = ExtWrapTagged.readTag(in, pf);
    }

    @Override
    public void metaWriteExternal(DataOutputStream out) throws IOException {
        ExtWrapTagged.writeTag(out, val == null ? new Object() : val);
    }
}


text:
@interface CommonViewController ()

@end

@implementation CommonViewController

- (id)init
{
    self = [super init];
    if (self) {
        if ([self respondsToSelector:@selector(extendedLayoutIncludesOpaqueBars)]) {
            self.extendedLayoutIncludesOpaqueBars = YES;
        }
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = UIColorMake(240, 240, 240);
    [self initNavigationItems];
	[self initSubviews];
}

- (void)initSubviews
{
}

- (void)initNavigationItems
{
    self.navigationItem.title = @"Title";
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end


text:
package com.google.j2cl.jre.java.sql;

import com.google.gwt.junit.client.GWTTestCase;
import java.sql.Time;

/**
 * Tests {@link java.sql.Time}. We assume that the underlying
 * {@link java.util.Date} implementation is correct and concentrate only on the
 * differences between the two.
 */
@SuppressWarnings("deprecation")
public class SqlTimeTest extends GWTTestCase {

  /**
   * Sets module name so that javascript compiler can operate.
   */
  @Override
  public String getModuleName() {
    return "com.google.gwt.emultest.EmulSuite";
  }

  @SuppressWarnings("DoNotCall")
  public void testUnimplementedFunctions() {
    Time d = new Time(0);

    try {
      d.getYear();
      fail("Should have thrown IllegalArgumentException");
    } catch (IllegalArgumentException e) {
      // Expected behavior
    }

    try {
      d.getMonth();
      fail("Should have thrown IllegalArgumentException");
    } catch (IllegalArgumentException e) {
      // Expected behavior
    }

    try {
      d.getDate();
      fail("Should have thrown IllegalArgumentException");
    } catch (IllegalArgumentException e) {
      // Expected behavior
    }

    try {
      d.getDay();
      fail("Should have thrown IllegalArgumentException");
    } catch (IllegalArgumentException e) {
      // Expected behavior
    }

    try {
      d.setYear(0);
      fail("Should have thrown IllegalArgumentException");
    } catch (IllegalArgumentException e) {
      // Expected behavior
    }

    try {
      d.setMonth(0);
      fail("Should have thrown IllegalArgumentException");
    } catch (IllegalArgumentException e) {
      // Expected behavior
    }

    try {
      d.setDate(0);
      fail("Should have thrown IllegalArgumentException");
    } catch (IllegalArgumentException e) {
      // Expected behavior
    }
  }

  public void testParse() {
    try {
      Time.parse(null);
      fail("Should have thrown exception");
    } catch (IllegalArgumentException e) {
      // Expected
    }

    try {
      Time.parse("");
    } catch (IllegalArgumentException e) {
      // Expected
    }

    Time t = Time.valueOf("13:01:30");
    assertEquals(13, t.getHours());
    assertEquals(1, t.getMinutes());
    assertEquals(30, t.getSeconds());

    Time d2 = Time.valueOf(t.toString());
    assertEquals(t, d2);

    // tests to see if the various parts are indeed decoded in base-10 (till
    // r3728 the base was first inferred)
    Time t2 = Time.valueOf("08:09:01");
    assertEquals(8, t2.getHours());
    assertEquals(9, t2.getMinutes());
    assertEquals(1, t2.getSeconds());
    assertEquals(t2, Time.valueOf(t2.toString()));
  }

  public void testToString() {
    Time time = new Time(12, 34, 56);
    assertEquals("12:34:56", time.toString());
  }

  public void testInternalPrecision() {
    long millis = 1283895273475L;
    Time today = new Time(millis);
    Time after = new Time(today.getTime() + 1);
    Time before = new Time(today.getTime() - 1);

    // Note that Times internally retain millisecond precision
    assertTrue(after.after(today));
    assertTrue(before.before(today));
  }
}


text:
#ifndef  UBP_PLATFORM_MOUDLES_MQ_EXPORT_HPP_
#define  UBP_PLATFORM_MOUDLES_MQ_EXPORT_HPP_

//////////////////////////////////////////////////////////////////////////
// 定义此宏是为了解决WINDOWS平台单实例类对象在dll和exe中并非同一实例的bug
// dll中需要export,使用时需要import
//////////////////////////////////////////////////////////////////////////
#ifdef WIN32
#ifdef MQ_EXPORT
#define MQ_IMPORT_EXPORT __declspec(dllexport)
#define MQ_IMPORT_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) \
    template class __declspec (dllexport) SINGLETON_TYPE<CLASS, LOCK>;
#else//NOT MQ_EXPORT
#define MQ_IMPORT_EXPORT __declspec(dllimport)
#define MQ_IMPORT_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) \
    extern template class SINGLETON_TYPE <CLASS, LOCK>;
#endif//MQ_EXPORT
#else//NOT WIN32
#define MQ_IMPORT_EXPORT
#define MQ_IMPORT_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK)
#endif//WIN32

#endif  //UBP_PLATFORM_MOUDLES_MQ_EXPORT_HPP_


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZE_UTIL_ENABLEIF_H_
#define _BLAZE_UTIL_ENABLEIF_H_

namespace blaze {

//=================================================================================================
//
//  CLASS DEFINITION
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Substitution Failure Is Not An Error (SFINAE) class.
// \ingroup util
//
// The EnableIfTrue class template is an auxiliary tool for an intentional application of the
// Substitution Failure Is Not An Error (SFINAE) principle. It allows a function template or a
// class template specialization to include or exclude itself from a set of matching functions
// or specializations based on properties of its template arguments. For instance, it can be
// used to restrict the selection of a function template to specific data types. The following
// example illustrates this in more detail.

   \code
   template< typename Type >
   void process( Type t ) { ... }
   \endcode

// Due to the general formulation of this function, it will always be a possible candidate for
// every possible argument. However, with the EnableIfTrue class it is for example possible to
// restrict the valid argument types to built-in, numeric data types.

   \code
   template< typename Type >
   typename EnableIfTrue< IsNumeric<Type>::value >::Type process( Type t ) { ... }
   \endcode

// In case the given data type is not a built-in, numeric data type, the access to the nested
// type defintion \a Type of the EnableIfTrue template will fail. However, due to the SFINAE
// principle, this will only result in a compilation error in case the compiler cannot find
// another valid function.\n
// Note that in this application of the EnableIfTrue template the default for the nested type
// definition \a Type is used, which corresponds to \a void. Via the second template argument
// it is possible to explicitly specify the type of \a Type:

   \code
   // Explicity specifying the default
   typename EnableIfTrue< IsNumeric<Type>::value, void >::Type

   // In case the given data type is a boolean data type, the nested type definition
   // 'Type' is set to float
   typename EnableIfTrue< IsBoolean<Type>::value, float >::Type
   \endcode

// For more information on the EnableIfTrue/EnableIf functionality, see the Boost library
// documentation of the enable_if family at:
//
//           \a http://www.boost.org/doc/libs/1_60_0/libs/utility/enable_if.html.
*/
template< bool Condition     // Compile time condition
        , typename T=void >  // The type to be instantiated
struct EnableIfTrue
{
   //**********************************************************************************************
   using Type = T;  //!< The instantiated type.
   //**********************************************************************************************
};
//*************************************************************************************************

//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief EnableIfTrue specialization for failed constraints.
// \ingroup util
//
// This specialization of the EnableIfTrue template is selected if the first template parameter
// (the compile time condition) evaluates to \a false. This specialization does not contains a
// nested type definition \a Type and therefore always results in a compilation error in case
// \a Type is accessed. However, due to the SFINAE principle the compilation process is not
// necessarily stopped if another, valid instantiation is found by the compiler.
*/
template< typename T >  // The type to be instantiated
struct EnableIfTrue<false,T>
{};
/*! \endcond */
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Auxiliary type for the EnableIfTrue class template.
// \ingroup util
//
// The EnableIfTrue_ alias declaration provides a convenient shortcut to access the nested \a Type
// of the EnableIfTrue class template. For instance, given the type \a T the following two type
// definitions are identical:

   \code
   using Type1 = typename EnableIfTrue< IsBuiltin<T>::value >::Type;
   using Type2 = EnableIfTrue_< IsBuiltin<T>::value >;
   \endcode
*/
template< bool Condition     // Compile time condition
        , typename T=void >  // The type to be instantiated
using EnableIfTrue_ = typename EnableIfTrue<Condition,T>::Type;
//*************************************************************************************************

//=================================================================================================
//
//  CLASS DEFINITION
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Substitution Failure Is Not An Error (SFINAE) class.
// \ingroup util
//
// The EnableIf class template is an auxiliary tool for an intentional application of the
// Substitution Failure Is Not An Error (SFINAE) principle. It allows a function template
// or a class template specialization to include or exclude itself from a set of matching
// functions or specializations based on properties of its template arguments. For instance,
// it can be used to restrict the selection of a function template to specific data types.
// The following example illustrates this in more detail.

   \code
   template< typename Type >
   void process( Type t ) { ... }
   \endcode

// Due to the general formulation of this function, it will always be a possible candidate
// for every possible argument. However, with the EnableIf class it is for example possible
// to restrict the valid argument types to built-in, numeric data types.

   \code
   template< typename Type >
   typename EnableIf< IsNumeric<Type> >::Type process( Type t ) { ... }
   \endcode

// In case the given data type is not a built-in, numeric data type, the access to the nested
// type defintion \a Type of the EnableIf template will fail. However, due to the SFINAE
// principle, this will only result in a compilation error in case the compiler cannot find
// another valid function.\n
// Note that in this application of the EnableIf template the default for the nested type
// definition \a Type is used, which corresponds to \a void. Via the second template argument
// it is possible to explicitly specify the type of \a Type:

   \code
   // Explicity specifying the default
   typename EnableIf< IsNumeric<Type>, void >::Type

   // In case the given data type is a boolean data type, the nested type definition
   // 'Type' is set to float
   typename EnableIf< IsBoolean<Type>, float >::Type
   \endcode

// Note that in contrast to the EnableIfTrue template, the EnableIf template expects a type as
// first template argument that has a nested type definition \a value. Therefore the EnableIf
// template is the more convenient choice for all kinds of type traits.
//
// For more information on the EnableIfTrue/EnableIf functionality, see the Boost library
// documentation of the enable_if family at:
//
//           \a http://www.boost.org/doc/libs/1_60_0/libs/utility/enable_if.html.
*/
template< typename Condition  // Compile time condition
        , typename T=void >   // The type to be instantiated
struct EnableIf
   : public EnableIfTrue<Condition::value,T>
{};
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Auxiliary alias declaration for the EnableIf class template.
// \ingroup util
//
// The EnableIf_ alias declaration provides a convenient shortcut to access the nested \a Type
// of the EnableIf class template. For instance, given the type \a T the following two type
// definitions are identical:

   \code
   using Type1 = typename EnableIf< IsBuiltin<T> >::Type;
   using Type2 = EnableIf_< IsBuiltin<T> >;
   \endcode
*/
template< typename Condition  // Compile time condition
        , typename T=void >   // The type to be instantiated
using EnableIf_ = typename EnableIf<Condition,T>::Type;
//*************************************************************************************************

} // namespace blaze

#endif


text:
package com.sksamuel.scapegoat.inspections

// for protected on objects
class OptionGetGetOrElse {

}


text:
package freemind.modes.mindmapmode.actions;

import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import freemind.main.HtmlTools;
import freemind.modes.MindMapNode;
import freemind.modes.mindmapmode.MindMapController;
import freemind.view.mindmapview.MapView;

public class JoinNodesAction extends AbstractAction {
	private final MindMapController controller;

	public JoinNodesAction(MindMapController controller) {
		super(controller.getText("join_nodes"));
		this.controller = controller;
	}

	public void actionPerformed(ActionEvent e) {
		MindMapNode selectedNode = controller.getView().getSelected()
				.getModel();
		ArrayList selectedNodes = controller.getView()
				.getSelectedNodesSortedByY();
		joinNodes(selectedNode, selectedNodes);
	}

	public void joinNodes(MindMapNode selectedNode, List selectedNodes) {
		String newContent = "";
		// Make sure the selected node do not have children
		final MapView mapView = controller.getView();
		for (Iterator it = selectedNodes.iterator(); it.hasNext();) {
			MindMapNode node = (MindMapNode) it.next();
			if (node.hasChildren()) {
				JOptionPane.showMessageDialog(mapView,
						controller.getText("cannot_join_nodes_with_children"),
						"FreeMind", JOptionPane.WARNING_MESSAGE);
				return;
			}
		}

		// Join
		boolean isHtml = false;
		for (Iterator it = selectedNodes.iterator(); it.hasNext();) {
			final MindMapNode node = (MindMapNode) it.next();
			final String nodeContent = node.toString();
			final boolean isHtmlNode = HtmlTools.isHtmlNode(nodeContent);
			newContent = addContent(newContent, isHtml, nodeContent, isHtmlNode);
			if (node != selectedNode) {
				controller.deleteNode(node);
			}
			isHtml = isHtml || isHtmlNode;
		}

		mapView.selectAsTheOnlyOneSelected(mapView.getNodeView(selectedNode));
		controller.setNodeText(selectedNode, newContent);
	}

	final static Pattern BODY_START = Pattern.compile("",
			Pattern.CASE_INSENSITIVE);
	final static Pattern BODY_END = Pattern.compile("",
			Pattern.CASE_INSENSITIVE);

	private String addContent(String content, boolean isHtml,
			String nodeContent, boolean isHtmlNode) {
		if (isHtml) {
			final String start[] = BODY_END.split(content, -2);
			content = start[0];
			if (!isHtmlNode) {
				final String end[] = BODY_START.split(content, 2);
				nodeContent = end[0] + "
" + nodeContent + "
";
			}
		}
		if (isHtmlNode & !content.equals("")) {
			final String end[] = BODY_START.split(nodeContent, 2);
			nodeContent = end[1];
			if (!isHtml) {
				content = end[0] + "
" + content + "
";
			}
		}
		if (!(isHtml || isHtmlNode || content.equals(""))) {
			content += " ";
		}
		content += nodeContent;
		return content;
	}
}