text:
using namespace wi::graphics;
using namespace wi::enums;

namespace wi::image
{
	static Sampler samplers[SAMPLER_COUNT];
	static Shader vertexShader;
	static Shader pixelShader;
	static BlendState blendStates[BLENDMODE_COUNT];
	static RasterizerState rasterizerState;
	static DepthStencilState depthStencilStates[STENCILMODE_COUNT][STENCILREFMODE_COUNT];
	enum STRIP_MODE
	{
		STRIP_OFF,
		STRIP_ON,
		STRIP_MODE_COUNT,
	};
	static PipelineState imagePSO[BLENDMODE_COUNT][STENCILMODE_COUNT][STENCILREFMODE_COUNT][STRIP_MODE_COUNT];
	static thread_local Texture backgroundTexture;
	static thread_local wi::Canvas canvas;

	void SetBackground(const Texture& texture)
	{
		backgroundTexture = texture;
	}

	void SetCanvas(const wi::Canvas& current_canvas)
	{
		canvas = current_canvas;
	}

	void Draw(const Texture* texture, const Params& params, CommandList cmd)
	{
		GraphicsDevice* device = wi::graphics::GetDevice();

		const Sampler* sampler = &samplers[SAMPLER_LINEAR_CLAMP];

		if (params.quality == QUALITY_NEAREST)
		{
			if (params.sampleFlag == SAMPLEMODE_MIRROR)
				sampler = &samplers[SAMPLER_POINT_MIRROR];
			else if (params.sampleFlag == SAMPLEMODE_WRAP)
				sampler = &samplers[SAMPLER_POINT_WRAP];
			else if (params.sampleFlag == SAMPLEMODE_CLAMP)
				sampler = &samplers[SAMPLER_POINT_CLAMP];
		}
		else if (params.quality == QUALITY_LINEAR)
		{
			if (params.sampleFlag == SAMPLEMODE_MIRROR)
				sampler = &samplers[SAMPLER_LINEAR_MIRROR];
			else if (params.sampleFlag == SAMPLEMODE_WRAP)
				sampler = &samplers[SAMPLER_LINEAR_WRAP];
			else if (params.sampleFlag == SAMPLEMODE_CLAMP)
				sampler = &samplers[SAMPLER_LINEAR_CLAMP];
		}
		else if (params.quality == QUALITY_ANISOTROPIC)
		{
			if (params.sampleFlag == SAMPLEMODE_MIRROR)
				sampler = &samplers[SAMPLER_ANISO_MIRROR];
			else if (params.sampleFlag == SAMPLEMODE_WRAP)
				sampler = &samplers[SAMPLER_ANISO_WRAP];
			else if (params.sampleFlag == SAMPLEMODE_CLAMP)
				sampler = &samplers[SAMPLER_ANISO_CLAMP];
		}

		ImageConstants image = {};
		image.buffer_index = -1;
		image.buffer_offset = 0;
		image.texture_base_index = device->GetDescriptorIndex(texture, SubresourceType::SRV);
		image.texture_mask_index = device->GetDescriptorIndex(params.maskMap, SubresourceType::SRV);
		if (params.isBackgroundEnabled())
		{
			image.texture_background_index = device->GetDescriptorIndex(&backgroundTexture, SubresourceType::SRV);
		}
		else
		{
			image.texture_background_index = -1;
		}
		image.sampler_index = device->GetDescriptorIndex(sampler);
		if (image.sampler_index < 0)
			return;

		XMFLOAT4 color = params.color;
		const float darken = 1 - params.fade;
		color.x *= darken;
		color.y *= darken;
		color.z *= darken;
		color.w *= params.opacity;

		XMHALF4 packed_color;
		packed_color.x = XMConvertFloatToHalf(color.x);
		packed_color.y = XMConvertFloatToHalf(color.y);
		packed_color.z = XMConvertFloatToHalf(color.z);
		packed_color.w = XMConvertFloatToHalf(color.w);

		image.packed_color.x = uint(packed_color.v);
		image.packed_color.y = uint(packed_color.v >> 32ull);

		image.flags = 0;
		if (params.isExtractNormalMapEnabled())
		{
			image.flags |= IMAGE_FLAG_EXTRACT_NORMALMAP;
		}
		if (params.isHDR10OutputMappingEnabled())
		{
			image.flags |= IMAGE_FLAG_OUTPUT_COLOR_SPACE_HDR10_ST2084;
		}
		if (params.isLinearOutputMappingEnabled())
		{
			image.flags |= IMAGE_FLAG_OUTPUT_COLOR_SPACE_LINEAR;
			image.hdr_scaling = params.hdr_scaling;
		}
		if (params.isFullScreenEnabled())
		{
			image.flags |= IMAGE_FLAG_FULLSCREEN;
		}

		image.border_soften = params.border_soften;

		STRIP_MODE strip_mode = STRIP_ON;
		uint32_t index_count = 0;

		if (params.isFullScreenEnabled())
		{
			// full screen triangle, no vertex buffer:
			image.buffer_index = -1;
			image.buffer_offset = 0;
		}
		else
		{
			// vertex buffer:
			XMMATRIX S = XMMatrixScaling(params.scale.x * params.siz.x, params.scale.y * params.siz.y, 1);
			XMMATRIX M = XMMatrixRotationZ(params.rotation);

			if (params.customRotation != nullptr)
			{
				M = M * (*params.customRotation);
			}

			M = M * XMMatrixTranslation(params.pos.x, params.pos.y, params.pos.z);

			if (params.customProjection != nullptr)
			{
				S = XMMatrixScaling(1, -1, 1) * S; // reason: screen projection is Y down (like UV-space) and that is the common case for image rendering. But custom projections will use the "world space"
				M = M * (*params.customProjection);
			}
			else
			{
				// Asserts will check that a proper canvas was set for this cmd with wi::image::SetCanvas()
				//	The canvas must be set to have dpi aware rendering
				assert(canvas.width > 0);
				assert(canvas.height > 0);
				assert(canvas.dpi > 0);
				M = M * canvas.GetProjection();
			}

			XMVECTOR V[4];
			float4 corners[4];
			for (int i = 0; i < arraysize(params.corners); ++i)
			{
				V[i] = XMVectorSet(params.corners[i].x - params.pivot.x, params.corners[i].y - params.pivot.y, 0, 1);
				V[i] = XMVector2Transform(V[i], S);
				XMStoreFloat4(corners + i, XMVector2Transform(V[i], M)); // division by w will happen on GPU
			}

			image.b0 = XMHALF2(corners[0].x, corners[0].y).v;
			image.b1 = XMHALF2(corners[1].x - corners[0].x, corners[1].y - corners[0].y).v;
			image.b2 = XMHALF2(corners[2].x - corners[0].x, corners[2].y - corners[0].y).v;
			image.b3 = XMHALF2(corners[0].x - corners[1].x - corners[2].x + corners[3].x, corners[0].y - corners[1].y - corners[2].y + corners[3].y).v;

			if (params.isCornerRoundingEnabled())
			{
				// The rounded corner mode will use a triangle fan structure (implemrnted by indexed triangle list):
				strip_mode = STRIP_OFF;
				image.flags |= IMAGE_FLAG_CORNER_ROUNDING;
				size_t vertex_count = 1; // start with center vertex
				const int min_segment_count = 2;
				for (int i = 0; i < arraysize(params.corners_rounding); ++i)
				{
					int segments = std::max(min_segment_count, params.corners_rounding[i].segments);
					vertex_count += segments;
					index_count += segments * 3;
				}
				index_count += 3; // closing triangle
				const size_t vb_size = sizeof(float4) * vertex_count;
				const size_t ib_size = sizeof(uint16_t) * index_count;
				GraphicsDevice::GPUAllocation mem = device->AllocateGPU(vb_size + ib_size, cmd);
				image.buffer_index = device->GetDescriptorIndex(&mem.buffer, SubresourceType::SRV);
				image.buffer_offset = (uint)mem.offset;
				device->BindIndexBuffer(&mem.buffer, IndexBufferFormat::UINT16, mem.offset + vb_size, cmd);
				float4* vertices = (float4*)mem.data;
				uint16_t* indices = (uint16_t*)((uint8_t*)mem.data + vb_size);
				uint32_t vi = 0;
				uint32_t ii = 0;
				XMStoreFloat4(vertices + vi, XMVector2Transform((V[0] + V[1] + V[2] + V[3]) * 0.25f, M)); // center vertex
				vi++;
				for (int i = 0; i < arraysize(params.corners_rounding); ++i)
				{
					Params::Rounding rounding;
					XMVECTOR A;
					XMVECTOR B;
					XMVECTOR C;
					switch (i)
					{
					default:
					case 0:
						rounding = params.corners_rounding[0];
						A = V[2];
						B = V[0];
						C = V[1];
						break;
					case 1:
						rounding = params.corners_rounding[1];
						A = V[0];
						B = V[1];
						C = V[3];
						break;
					case 2:
						rounding = params.corners_rounding[3];
						A = V[1];
						B = V[3];
						C = V[2];
						break;
					case 3:
						rounding = params.corners_rounding[2];
						A = V[3];
						B = V[2];
						C = V[0];
						break;
					}
					rounding.segments = std::max(min_segment_count, rounding.segments);
					const XMVECTOR BA = A - B;
					const XMVECTOR BC = C - B;
					const XMVECTOR BA_length = XMVector2Length(BA);
					const XMVECTOR BC_length = XMVector2Length(BC);
					const XMVECTOR radius = XMVectorReplicate(rounding.radius);
					const XMVECTOR start = B + BA / BA_length * XMVectorMin(radius, BA_length * 0.5f);
					const XMVECTOR end = B + BC / BC_length * XMVectorMin(radius, BC_length * 0.5f);

					for (int j = 0; j < rounding.segments; ++j)
					{
						float t = float(j) / float(rounding.segments - 1);
						XMVECTOR bezier = wi::math::GetQuadraticBezierPos(start, B, end, t);
						XMStoreFloat4(vertices + vi, XMVector2Transform(bezier, M));
						indices[ii++] = 0;
						indices[ii++] = vi - 1;
						indices[ii++] = vi;
						vi++;
					}
				}
				// closing the triangle fan:
				indices[ii++] = 0;
				indices[ii++] = vi - 1;
				indices[ii++] = 1;
			}
			else
			{
				// Non rounded image will simply use a 4 vertex triangle strip (simple quad)
				GraphicsDevice::GPUAllocation mem = device->AllocateGPU(sizeof(float4) * 4, cmd);
				image.buffer_index = device->GetDescriptorIndex(&mem.buffer, SubresourceType::SRV);
				image.buffer_offset = (uint)mem.offset;
				std::memcpy(mem.data, corners, sizeof(corners));
			}
		}

		if (params.isMirrorEnabled())
		{
			image.flags |= IMAGE_FLAG_MIRROR;
		}

		const TextureDesc& desc = texture->GetDesc();
		const float inv_width = 1.0f / float(desc.width);
		const float inv_height = 1.0f / float(desc.height);

		XMFLOAT4 texMulAdd;
		if (params.isDrawRectEnabled())
		{
			texMulAdd.x = params.drawRect.z * inv_width;	// drawRec.width: mul
			texMulAdd.y = params.drawRect.w * inv_height;	// drawRec.heigh: mul
			texMulAdd.z = params.drawRect.x * inv_width;	// drawRec.x: add
			texMulAdd.w = params.drawRect.y * inv_height;	// drawRec.y: add
		}
		else
		{
			texMulAdd = XMFLOAT4(1, 1, 0, 0);	// disabled draw rect
		}
		texMulAdd.z += params.texOffset.x * inv_width;	// texOffset.x: add
		texMulAdd.w += params.texOffset.y * inv_height;	// texOffset.y: add
		XMHALF4 half_texMulAdd;
		half_texMulAdd.x = XMConvertFloatToHalf(texMulAdd.x);
		half_texMulAdd.y = XMConvertFloatToHalf(texMulAdd.y);
		half_texMulAdd.z = XMConvertFloatToHalf(texMulAdd.z);
		half_texMulAdd.w = XMConvertFloatToHalf(texMulAdd.w);
		image.texMulAdd.x = uint(half_texMulAdd.v);
		image.texMulAdd.y = uint(half_texMulAdd.v >> 32ull);

		XMFLOAT4 texMulAdd2;
		if (params.isDrawRect2Enabled())
		{
			texMulAdd2.x = params.drawRect2.z * inv_width;	// drawRec.width: mul
			texMulAdd2.y = params.drawRect2.w * inv_height;	// drawRec.heigh: mul
			texMulAdd2.z = params.drawRect2.x * inv_width;	// drawRec.x: add
			texMulAdd2.w = params.drawRect2.y * inv_height;	// drawRec.y: add
		}
		else
		{
			texMulAdd2 = XMFLOAT4(1, 1, 0, 0);	// disabled draw rect
		}
		texMulAdd2.z += params.texOffset2.x * inv_width;	// texOffset.x: add
		texMulAdd2.w += params.texOffset2.y * inv_height;	// texOffset.y: add
		XMHALF4 half_texMulAdd2;
		half_texMulAdd2.x = XMConvertFloatToHalf(texMulAdd2.x);
		half_texMulAdd2.y = XMConvertFloatToHalf(texMulAdd2.y);
		half_texMulAdd2.z = XMConvertFloatToHalf(texMulAdd2.z);
		half_texMulAdd2.w = XMConvertFloatToHalf(texMulAdd2.w);
		image.texMulAdd2.x = uint(half_texMulAdd2.v);
		image.texMulAdd2.y = uint(half_texMulAdd2.v >> 32ull);

		device->EventBegin("Image", cmd);

		uint32_t stencilRef = params.stencilRef;
		if (params.stencilRefMode == STENCILREFMODE_USER)
		{
			stencilRef = wi::renderer::CombineStencilrefs(STENCILREF_EMPTY, (uint8_t)stencilRef);
		}
		device->BindStencilRef(stencilRef, cmd);

		device->BindPipelineState(&imagePSO[params.blendFlag][params.stencilComp][params.stencilRefMode][strip_mode], cmd);

		device->BindDynamicConstantBuffer(image, CBSLOT_IMAGE, cmd);

		if (params.isFullScreenEnabled())
		{
			device->Draw(3, 0, cmd); // full screen triangle
		}
		else
		{
			switch (strip_mode)
			{
			case wi::image::STRIP_OFF:
				device->DrawIndexed(index_count, 0, 0, cmd); // corner rounding with indexed geometry
				break;
			case wi::image::STRIP_ON:
			default:
				device->Draw(4, 0, cmd); // simple quad
				break;
			}
		}

		device->EventEnd(cmd);
	}

	void LoadShaders()
	{
		wi::renderer::LoadShader(ShaderStage::VS, vertexShader, "imageVS.cso");
		wi::renderer::LoadShader(ShaderStage::PS, pixelShader, "imagePS.cso");

		GraphicsDevice* device = wi::graphics::GetDevice();

		PipelineStateDesc desc;
		desc.vs = &vertexShader;
		desc.ps = &pixelShader;
		desc.rs = &rasterizerState;

		for (int j = 0; j < BLENDMODE_COUNT; ++j)
		{
			desc.bs = &blendStates[j];
			for (int k = 0; k < STENCILMODE_COUNT; ++k)
			{
				for (int m = 0; m < STENCILREFMODE_COUNT; ++m)
				{
					desc.dss = &depthStencilStates[k][m];

					for (int n = 0; n < STRIP_MODE_COUNT; ++n)
					{
						switch (n)
						{
						default:
						case STRIP_ON:
							desc.pt = PrimitiveTopology::TRIANGLESTRIP;
							break;
						case STRIP_OFF:
							desc.pt = PrimitiveTopology::TRIANGLELIST;
							break;
						}
						device->CreatePipelineState(&desc, &imagePSO[j][k][m][n]);
					}

				}
			}
		}
	}

	void Initialize()
	{
		wi::Timer timer;

		GraphicsDevice* device = wi::graphics::GetDevice();

		RasterizerState rs;
		rs.fill_mode = FillMode::SOLID;
		rs.cull_mode = CullMode::NONE;
		rs.front_counter_clockwise = false;
		rs.depth_bias = 0;
		rs.depth_bias_clamp = 0;
		rs.slope_scaled_depth_bias = 0;
		rs.depth_clip_enable = true;
		rs.multisample_enable = false;
		rs.antialiased_line_enable = false;
		rasterizerState = rs;

		for (int i = 0; i < STENCILREFMODE_COUNT; ++i)
		{
			DepthStencilState dsd;
			dsd.depth_enable = false;
			dsd.stencil_enable = false;
			depthStencilStates[STENCILMODE_DISABLED][i] = dsd;

			dsd.stencil_enable = true;
			switch (i)
			{
			case STENCILREFMODE_ENGINE:
				dsd.stencil_read_mask = STENCILREF_MASK_ENGINE;
				break;
			case STENCILREFMODE_USER:
				dsd.stencil_read_mask = STENCILREF_MASK_USER;
				break;
			default:
				dsd.stencil_read_mask = STENCILREF_MASK_ALL;
				break;
			}
			dsd.stencil_write_mask = 0;
			dsd.front_face.stencil_pass_op = StencilOp::KEEP;
			dsd.front_face.stencil_fail_op = StencilOp::KEEP;
			dsd.front_face.stencil_depth_fail_op = StencilOp::KEEP;
			dsd.back_face.stencil_pass_op = StencilOp::KEEP;
			dsd.back_face.stencil_fail_op = StencilOp::KEEP;
			dsd.back_face.stencil_depth_fail_op = StencilOp::KEEP;

			dsd.front_face.stencil_func = ComparisonFunc::EQUAL;
			dsd.back_face.stencil_func = ComparisonFunc::EQUAL;
			depthStencilStates[STENCILMODE_EQUAL][i] = dsd;

			dsd.front_face.stencil_func = ComparisonFunc::LESS;
			dsd.back_face.stencil_func = ComparisonFunc::LESS;
			depthStencilStates[STENCILMODE_LESS][i] = dsd;

			dsd.front_face.stencil_func = ComparisonFunc::LESS_EQUAL;
			dsd.back_face.stencil_func = ComparisonFunc::LESS_EQUAL;
			depthStencilStates[STENCILMODE_LESSEQUAL][i] = dsd;

			dsd.front_face.stencil_func = ComparisonFunc::GREATER;
			dsd.back_face.stencil_func = ComparisonFunc::GREATER;
			depthStencilStates[STENCILMODE_GREATER][i] = dsd;

			dsd.front_face.stencil_func = ComparisonFunc::GREATER_EQUAL;
			dsd.back_face.stencil_func = ComparisonFunc::GREATER_EQUAL;
			depthStencilStates[STENCILMODE_GREATEREQUAL][i] = dsd;

			dsd.front_face.stencil_func = ComparisonFunc::NOT_EQUAL;
			dsd.back_face.stencil_func = ComparisonFunc::NOT_EQUAL;
			depthStencilStates[STENCILMODE_NOT][i] = dsd;

			dsd.front_face.stencil_func = ComparisonFunc::ALWAYS;
			dsd.back_face.stencil_func = ComparisonFunc::ALWAYS;
			depthStencilStates[STENCILMODE_ALWAYS][i] = dsd;
		}

		BlendState bd;
		bd.render_target[0].blend_enable = true;
		bd.render_target[0].src_blend = Blend::SRC_ALPHA;
		bd.render_target[0].dest_blend = Blend::INV_SRC_ALPHA;
		bd.render_target[0].blend_op = BlendOp::ADD;
		bd.render_target[0].src_blend_alpha = Blend::ONE;
		bd.render_target[0].dest_blend_alpha = Blend::INV_SRC_ALPHA;
		bd.render_target[0].blend_op_alpha = BlendOp::ADD;
		bd.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL;
		bd.independent_blend_enable = false;
		blendStates[BLENDMODE_ALPHA] = bd;

		bd.render_target[0].blend_enable = true;
		bd.render_target[0].src_blend = Blend::ONE;
		bd.render_target[0].dest_blend = Blend::INV_SRC_ALPHA;
		bd.render_target[0].blend_op = BlendOp::ADD;
		bd.render_target[0].src_blend_alpha = Blend::ONE;
		bd.render_target[0].dest_blend_alpha = Blend::INV_SRC_ALPHA;
		bd.render_target[0].blend_op_alpha = BlendOp::ADD;
		bd.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL;
		bd.independent_blend_enable = false;
		blendStates[BLENDMODE_PREMULTIPLIED] = bd;

		bd.render_target[0].blend_enable = false;
		bd.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL;
		bd.independent_blend_enable = false;
		blendStates[BLENDMODE_OPAQUE] = bd;

		bd.render_target[0].blend_enable = true;
		bd.render_target[0].src_blend = Blend::SRC_ALPHA;
		bd.render_target[0].dest_blend = Blend::ONE;
		bd.render_target[0].blend_op = BlendOp::ADD;
		bd.render_target[0].src_blend_alpha = Blend::ZERO;
		bd.render_target[0].dest_blend_alpha = Blend::ONE;
		bd.render_target[0].blend_op_alpha = BlendOp::ADD;
		bd.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL;
		bd.independent_blend_enable = false;
		blendStates[BLENDMODE_ADDITIVE] = bd;

		bd.render_target[0].blend_enable = true;
		bd.render_target[0].src_blend = Blend::ZERO;
		bd.render_target[0].dest_blend = Blend::SRC_COLOR;
		bd.render_target[0].blend_op = BlendOp::ADD;
		bd.render_target[0].src_blend_alpha = Blend::ZERO;
		bd.render_target[0].dest_blend_alpha = Blend::SRC_ALPHA;
		bd.render_target[0].blend_op_alpha = BlendOp::ADD;
		bd.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL;
		bd.independent_blend_enable = false;
		blendStates[BLENDMODE_MULTIPLY] = bd;

		SamplerDesc samplerDesc;
		samplerDesc.filter = Filter::MIN_MAG_MIP_LINEAR;
		samplerDesc.address_u = TextureAddressMode::MIRROR;
		samplerDesc.address_v = TextureAddressMode::MIRROR;
		samplerDesc.address_w = TextureAddressMode::MIRROR;
		samplerDesc.mip_lod_bias = 0.0f;
		samplerDesc.max_anisotropy = 0;
		samplerDesc.comparison_func = ComparisonFunc::NEVER;
		samplerDesc.border_color = SamplerBorderColor::TRANSPARENT_BLACK;
		samplerDesc.min_lod = 0;
		samplerDesc.max_lod = std::numeric_limits<float>::max();
		device->CreateSampler(&samplerDesc, &samplers[SAMPLER_LINEAR_MIRROR]);

		samplerDesc.filter = Filter::MIN_MAG_MIP_LINEAR;
		samplerDesc.address_u = TextureAddressMode::CLAMP;
		samplerDesc.address_v = TextureAddressMode::CLAMP;
		samplerDesc.address_w = TextureAddressMode::CLAMP;
		device->CreateSampler(&samplerDesc, &samplers[SAMPLER_LINEAR_CLAMP]);

		samplerDesc.filter = Filter::MIN_MAG_MIP_LINEAR;
		samplerDesc.address_u = TextureAddressMode::WRAP;
		samplerDesc.address_v = TextureAddressMode::WRAP;
		samplerDesc.address_w = TextureAddressMode::WRAP;
		device->CreateSampler(&samplerDesc, &samplers[SAMPLER_LINEAR_WRAP]);

		samplerDesc.filter = Filter::MIN_MAG_MIP_POINT;
		samplerDesc.address_u = TextureAddressMode::MIRROR;
		samplerDesc.address_v = TextureAddressMode::MIRROR;
		samplerDesc.address_w = TextureAddressMode::MIRROR;
		device->CreateSampler(&samplerDesc, &samplers[SAMPLER_POINT_MIRROR]);

		samplerDesc.filter = Filter::MIN_MAG_MIP_POINT;
		samplerDesc.address_u = TextureAddressMode::WRAP;
		samplerDesc.address_v = TextureAddressMode::WRAP;
		samplerDesc.address_w = TextureAddressMode::WRAP;
		device->CreateSampler(&samplerDesc, &samplers[SAMPLER_POINT_WRAP]);

		samplerDesc.filter = Filter::MIN_MAG_MIP_POINT;
		samplerDesc.address_u = TextureAddressMode::CLAMP;
		samplerDesc.address_v = TextureAddressMode::CLAMP;
		samplerDesc.address_w = TextureAddressMode::CLAMP;
		device->CreateSampler(&samplerDesc, &samplers[SAMPLER_POINT_CLAMP]);

		samplerDesc.filter = Filter::ANISOTROPIC;
		samplerDesc.address_u = TextureAddressMode::CLAMP;
		samplerDesc.address_v = TextureAddressMode::CLAMP;
		samplerDesc.address_w = TextureAddressMode::CLAMP;
		samplerDesc.max_anisotropy = 16;
		device->CreateSampler(&samplerDesc, &samplers[SAMPLER_ANISO_CLAMP]);

		samplerDesc.filter = Filter::ANISOTROPIC;
		samplerDesc.address_u = TextureAddressMode::WRAP;
		samplerDesc.address_v = TextureAddressMode::WRAP;
		samplerDesc.address_w = TextureAddressMode::WRAP;
		samplerDesc.max_anisotropy = 16;
		device->CreateSampler(&samplerDesc, &samplers[SAMPLER_ANISO_WRAP]);

		samplerDesc.filter = Filter::ANISOTROPIC;
		samplerDesc.address_u = TextureAddressMode::MIRROR;
		samplerDesc.address_v = TextureAddressMode::MIRROR;
		samplerDesc.address_w = TextureAddressMode::MIRROR;
		samplerDesc.max_anisotropy = 16;
		device->CreateSampler(&samplerDesc, &samplers[SAMPLER_ANISO_MIRROR]);

		static wi::eventhandler::Handle handle = wi::eventhandler::Subscribe(wi::eventhandler::EVENT_RELOAD_SHADERS, [](uint64_t userdata) { LoadShaders(); });
		LoadShaders();

		wi::backlog::post("wi::image Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)");
	}

}


text:
class PDFDoc;
class Gfx8BitFont;
class SplashBitmap;
class Splash;
class SplashPath;
class SplashFontEngine;
class SplashFont;
class T3FontCache;
struct T3FontCacheTag;
struct T3GlyphStack;
struct SplashTransparencyGroup;

//------------------------------------------------------------------------
// Splash dynamic pattern
//------------------------------------------------------------------------

class SplashUnivariatePattern: public SplashPattern {
public:

  SplashUnivariatePattern(SplashColorMode colorMode, GfxState *state, GfxUnivariateShading *shading);

  virtual ~SplashUnivariatePattern();

  virtual GBool getColor(int x, int y, SplashColorPtr c);

  virtual GBool testPosition(int x, int y);

  virtual GBool isStatic() { return gFalse; }

  virtual GBool getParameter(double xs, double ys, double *t) = 0;

  virtual GfxUnivariateShading *getShading() { return shading; }

  virtual GBool isCMYK() { return gfxMode == csDeviceCMYK; }

protected:
  Matrix ictm;
  double t0, t1, dt;
  GfxUnivariateShading *shading;
  GfxState *state;
  SplashColorMode colorMode;
  GfxColorSpaceMode gfxMode;
};

class SplashAxialPattern: public SplashUnivariatePattern {
public:

  SplashAxialPattern(SplashColorMode colorMode, GfxState *state, GfxAxialShading *shading);

  virtual SplashPattern *copy() { return new SplashAxialPattern(colorMode, state, (GfxAxialShading *) shading); }

  virtual ~SplashAxialPattern();

  virtual GBool getParameter(double xs, double ys, double *t);

private:
  double x0, y0, x1, y1;
  double dx, dy, mul;
};

// see GfxState.h, GfxGouraudTriangleShading
class SplashGouraudPattern: public SplashGouraudColor {
public:

  SplashGouraudPattern(GBool bDirectColorTranslation, GfxState *state, GfxGouraudTriangleShading *shading, SplashColorMode mode);

  virtual SplashPattern *copy() { return new SplashGouraudPattern(bDirectColorTranslation, state, shading, mode); }

  virtual ~SplashGouraudPattern();

  virtual GBool getColor(int x, int y, SplashColorPtr c) { return gFalse; }

  virtual GBool testPosition(int x, int y) { return gFalse; }

  virtual GBool isStatic() { return gFalse; }

  virtual GBool isCMYK() { return gfxMode == csDeviceCMYK; }

  virtual GBool isParameterized() { return shading->isParameterized(); }
  virtual int getNTriangles() { return shading->getNTriangles(); }
  virtual  void getTriangle(int i, double *x0, double *y0, double *color0,
                            double *x1, double *y1, double *color1,
                            double *x2, double *y2, double *color2)
  { return shading->getTriangle(i, x0, y0, color0, x1, y1, color1, x2, y2, color2); }

  virtual void getParameterizedColor(double t, SplashColorMode mode, SplashColorPtr c);

private:
  GfxGouraudTriangleShading *shading;
  GfxState *state;
  GBool bDirectColorTranslation;
  SplashColorMode mode;
  GfxColorSpaceMode gfxMode;
};

// see GfxState.h, GfxRadialShading
class SplashRadialPattern: public SplashUnivariatePattern {
public:

  SplashRadialPattern(SplashColorMode colorMode, GfxState *state, GfxRadialShading *shading);

  virtual SplashPattern *copy() { return new SplashRadialPattern(colorMode, state, (GfxRadialShading *) shading); }

  virtual ~SplashRadialPattern();

  virtual GBool getParameter(double xs, double ys, double *t);

private:
  double x0, y0, r0, dx, dy, dr;
  double a, inva;
};

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

// number of Type 3 fonts to cache
#define splashOutT3FontCacheSize 8

//------------------------------------------------------------------------
// SplashOutputDev
//------------------------------------------------------------------------

class SplashOutputDev: public OutputDev {
public:

  // Constructor.
  SplashOutputDev(SplashColorMode colorModeA, int bitmapRowPadA,
		  GBool reverseVideoA, SplashColorPtr paperColorA,
		  GBool bitmapTopDownA = gTrue,
		  GBool allowAntialiasA = gTrue,
		  SplashThinLineMode thinLineMode = splashThinLineDefault,
      GBool overprintPreviewA = globalParams->getOverprintPreview());

  // Destructor.
  virtual ~SplashOutputDev();

  //----- get info about output device

  // Does this device use tilingPatternFill()?  If this returns false,
  // tiling pattern fills will be reduced to a series of other drawing
  // operations.
  virtual GBool useTilingPatternFill() { return gTrue; }

  // Does this device use functionShadedFill(), axialShadedFill(), and
  // radialShadedFill()?  If this returns false, these shaded fills
  // will be reduced to a series of other drawing operations.
  virtual GBool useShadedFills(int type)
  { return (type >= 2 && type <= 5) ? gTrue : gFalse; }

  // Does this device use upside-down coordinates?
  // (Upside-down means (0,0) is the top left corner of the page.)
  virtual GBool upsideDown() { return bitmapTopDown ^ bitmapUpsideDown; }

  // Does this device use drawChar() or drawString()?
  virtual GBool useDrawChar() { return gTrue; }

  // Does this device use beginType3Char/endType3Char?  Otherwise,
  // text in Type 3 fonts will be drawn with drawChar/drawString.
  virtual GBool interpretType3Chars() { return gTrue; }

  //----- initialization and control

  // Start a page.
  virtual void startPage(int pageNum, GfxState *state, XRef *xref);

  // End a page.
  virtual void endPage();

  //----- save/restore graphics state
  virtual void saveState(GfxState *state);
  virtual void restoreState(GfxState *state);

  //----- update graphics state
  virtual void updateAll(GfxState *state);
  virtual void updateCTM(GfxState *state, double m11, double m12,
			 double m21, double m22, double m31, double m32);
  virtual void updateLineDash(GfxState *state);
  virtual void updateFlatness(GfxState *state);
  virtual void updateLineJoin(GfxState *state);
  virtual void updateLineCap(GfxState *state);
  virtual void updateMiterLimit(GfxState *state);
  virtual void updateLineWidth(GfxState *state);
  virtual void updateStrokeAdjust(GfxState *state);
  virtual void updateFillColorSpace(GfxState *state);
  virtual void updateStrokeColorSpace(GfxState *state);
  virtual void updateFillColor(GfxState *state);
  virtual void updateStrokeColor(GfxState *state);
  virtual void updateBlendMode(GfxState *state);
  virtual void updateFillOpacity(GfxState *state);
  virtual void updateStrokeOpacity(GfxState *state);
  virtual void updateFillOverprint(GfxState *state);
  virtual void updateStrokeOverprint(GfxState *state);
  virtual void updateOverprintMode(GfxState *state);
  virtual void updateTransfer(GfxState *state);

  //----- update text state
  virtual void updateFont(GfxState *state);

  //----- path painting
  virtual void stroke(GfxState *state);
  virtual void fill(GfxState *state);
  virtual void eoFill(GfxState *state);
  virtual GBool tilingPatternFill(GfxState *state, Gfx *gfx, Catalog *catalog, Object *str,
				  double *pmat, int paintType, int tilingType, Dict *resDict,
				  double *mat, double *bbox,
				  int x0, int y0, int x1, int y1,
				  double xStep, double yStep);
  virtual GBool axialShadedFill(GfxState *state, GfxAxialShading *shading, double tMin, double tMax);
  virtual GBool radialShadedFill(GfxState *state, GfxRadialShading *shading, double tMin, double tMax);
  virtual GBool gouraudTriangleShadedFill(GfxState *state, GfxGouraudTriangleShading *shading);

  //----- path clipping
  virtual void clip(GfxState *state);
  virtual void eoClip(GfxState *state);
  virtual void clipToStrokePath(GfxState *state);

  //----- text drawing
  virtual void drawChar(GfxState *state, double x, double y,
			double dx, double dy,
			double originX, double originY,
			CharCode code, int nBytes, Unicode *u, int uLen);
  virtual GBool beginType3Char(GfxState *state, double x, double y,
			       double dx, double dy,
			       CharCode code, Unicode *u, int uLen);
  virtual void endType3Char(GfxState *state);
  virtual void beginTextObject(GfxState *state);
  virtual void endTextObject(GfxState *state);

  //----- image drawing
  virtual void drawImageMask(GfxState *state, Object *ref, Stream *str,
			     int width, int height, GBool invert,
			     GBool interpolate, GBool inlineImg);
  virtual void setSoftMaskFromImageMask(GfxState *state,
					Object *ref, Stream *str,
					int width, int height, GBool invert,
					GBool inlineImg, double *baseMatrix);
  virtual void unsetSoftMaskFromImageMask(GfxState *state, double *baseMatrix);
  virtual void drawImage(GfxState *state, Object *ref, Stream *str,
			 int width, int height, GfxImageColorMap *colorMap,
			 GBool interpolate, int *maskColors, GBool inlineImg);
  virtual void drawMaskedImage(GfxState *state, Object *ref, Stream *str,
			       int width, int height,
			       GfxImageColorMap *colorMap,
			       GBool interpolate,
			       Stream *maskStr, int maskWidth, int maskHeight,
			       GBool maskInvert, GBool maskInterpolate);
  virtual void drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str,
				   int width, int height,
				   GfxImageColorMap *colorMap,
				   GBool interpolate,
				   Stream *maskStr,
				   int maskWidth, int maskHeight,
				   GfxImageColorMap *maskColorMap,
				   GBool maskInterpolate);

  //----- Type 3 font operators
  virtual void type3D0(GfxState *state, double wx, double wy);
  virtual void type3D1(GfxState *state, double wx, double wy,
		       double llx, double lly, double urx, double ury);

  //----- transparency groups and soft masks
  virtual GBool checkTransparencyGroup(GfxState *state, GBool knockout);
  virtual void beginTransparencyGroup(GfxState *state, double *bbox,
				      GfxColorSpace *blendingColorSpace,
				      GBool isolated, GBool knockout,
				      GBool forSoftMask);
  virtual void endTransparencyGroup(GfxState *state);
  virtual void paintTransparencyGroup(GfxState *state, double *bbox);
  virtual void setSoftMask(GfxState *state, double *bbox, GBool alpha,
			   Function *transferFunc, GfxColor *backdropColor);
  virtual void clearSoftMask(GfxState *state);

  //----- special access

  // Called to indicate that a new PDF document has been loaded.
  void startDoc(PDFDoc *docA);

  void setPaperColor(SplashColorPtr paperColorA);

  GBool isReverseVideo() { return reverseVideo; }
  void setReverseVideo(GBool reverseVideoA) { reverseVideo = reverseVideoA; }

  // Get the bitmap and its size.
  SplashBitmap *getBitmap() { return bitmap; }
  int getBitmapWidth();
  int getBitmapHeight();

  // Returns the last rasterized bitmap, transferring ownership to the
  // caller.
  SplashBitmap *takeBitmap();

  // Set this flag to true to generate an upside-down bitmap (useful
  // for Windows BMP files).
  void setBitmapUpsideDown(GBool f) { bitmapUpsideDown = f; }

  // Get the Splash object.
  Splash *getSplash() { return splash; }

  // Get the modified region.
  void getModRegion(int *xMin, int *yMin, int *xMax, int *yMax);

  // Clear the modified region.
  void clearModRegion();

  SplashFont *getCurrentFont() { return font; }

  // If <skipTextA> is true, don't draw horizontal text.
  // If <skipRotatedTextA> is true, don't draw rotated (non-horizontal) text.
  void setSkipText(GBool skipHorizTextA, GBool skipRotatedTextA)
    { skipHorizText = skipHorizTextA; skipRotatedText = skipRotatedTextA; }

  int getNestCount() { return nestCount; }

#if 1 //~tmp: turn off anti-aliasing temporarily
  virtual GBool getVectorAntialias();
  virtual void setVectorAntialias(GBool vaa);
#endif

  void setFreeTypeHinting(GBool enable, GBool enableSlightHinting);

protected:
  void doUpdateFont(GfxState *state);

private:
  GBool univariateShadedFill(GfxState *state, SplashUnivariatePattern *pattern, double tMin, double tMax);

  void setupScreenParams(double hDPI, double vDPI);
  SplashPattern *getColor(GfxGray gray);
  SplashPattern *getColor(GfxRGB *rgb);
#if SPLASH_CMYK
  SplashPattern *getColor(GfxCMYK *cmyk);
  SplashPattern *getColor(GfxColor *deviceN);
#endif
  void setOverprintMask(GfxColorSpace *colorSpace, GBool overprintFlag,
			int overprintMode, GfxColor *singleColor, GBool grayIndexed = gFalse);
  SplashPath *convertPath(GfxState *state, GfxPath *path,
			  GBool dropEmptySubpaths);
  void drawType3Glyph(GfxState *state, T3FontCache *t3Font,
		      T3FontCacheTag *tag, Guchar *data);
  static GBool imageMaskSrc(void *data, SplashColorPtr line);
  static GBool imageSrc(void *data, SplashColorPtr colorLine,
			Guchar *alphaLine);
  static GBool alphaImageSrc(void *data, SplashColorPtr line,
			     Guchar *alphaLine);
  static GBool maskedImageSrc(void *data, SplashColorPtr line,
			      Guchar *alphaLine);
  static GBool tilingBitmapSrc(void *data, SplashColorPtr line,
			     Guchar *alphaLine);

  GBool keepAlphaChannel;	// don't fill with paper color, keep alpha channel

  SplashColorMode colorMode;
  int bitmapRowPad;
  GBool bitmapTopDown;
  GBool bitmapUpsideDown;
  GBool allowAntialias;
  GBool vectorAntialias;
  GBool overprintPreview;
  GBool enableFreeTypeHinting;
  GBool enableSlightHinting;
  GBool reverseVideo;		// reverse video mode
  SplashColor paperColor;	// paper color
  SplashScreenParams screenParams;
  GBool skipHorizText;
  GBool skipRotatedText;

  PDFDoc *doc;			// the current document
  XRef *xref;       // the xref of the current document

  SplashBitmap *bitmap;
  Splash *splash;
  SplashFontEngine *fontEngine;

  T3FontCache *			// Type 3 font cache
    t3FontCache[splashOutT3FontCacheSize];
  int nT3Fonts;			// number of valid entries in t3FontCache
  T3GlyphStack *t3GlyphStack;	// Type 3 glyph context stack
  GBool haveT3Dx;		// set after seeing a d0/d1 operator

  SplashFont *font;		// current font
  GBool needFontUpdate;		// set when the font needs to be updated
  SplashPath *textClipPath;	// clipping path built with text object

  SplashTransparencyGroup *	// transparency group stack
    transpGroupStack;
  SplashBitmap *maskBitmap; // for image masks in pattern colorspace
  int nestCount;
};

#endif

redpajama_set_name: RedPajamaGithub


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.atmosphere</groupId>
        <artifactId>vibe-platform-parent</artifactId>
        <version>3.0.0-Beta1-SNAPSHOT</version>
    </parent>
    <artifactId>vibe-platform-test</artifactId>
    <name>Vibe Platform/Test</name>
    <dependencies>
        <dependency>
            <groupId>org.atmosphere</groupId>
            <artifactId>vibe-platform-action</artifactId>
        </dependency>
        <dependency>
            <groupId>org.atmosphere</groupId>
            <artifactId>vibe-platform-http</artifactId>
        </dependency>
        <dependency>
            <groupId>org.atmosphere</groupId>
            <artifactId>vibe-platform-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-client</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty.websocket</groupId>
            <artifactId>websocket-client</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <scope>compile</scope>
        </dependency>
    </dependencies>
</project>


text:
package tw.edu.nccu.cs.exercise.two;

public class SimpleRaceAdapter implements Raceable {

    @Override
    public int run() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public int getTotalDistance() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void throwBox() {
        // TODO Auto-generated method stub

    }

    @Override
    public void fireRocket() {
        // TODO Auto-generated method stub

    }

    @Override
    public void sayYa() {
        // TODO Auto-generated method stub

    }

}


text:
AlphaAdminTemplate
==================

A Bootstarp3 Responsive Admin Template.

This project is a practice for Jade&Less&Bootstrap.


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Xb.Db
{
    public class ResultTable : IDisposable
    {
        public string[] ColumnNames { get; private set; }
        public List<ResultRow> Rows { get; private set; }
        public int ColumnCount { get; private set; }
        public int RowCount { get; private set; }

        private Dictionary<string, int> _columnNameIndexes;

        public ResultTable(DbDataReader reader)
        {
            if (reader == null
                || reader.IsClosed)
            {
                throw new ArgumentException("Xb.Db.ResultTable: reader null or closed.");
            }

            var colNames = new List<string>();
            this._columnNameIndexes = new Dictionary<string, int>();
            for (var i = 0; i < reader.FieldCount; i++)
            {
                var name = reader.GetName(i);
                colNames.Add(name);
                this._columnNameIndexes.Add(name, i);
            }

            this.ColumnNames = colNames.ToArray();

            this.ColumnCount = this.ColumnNames.Length;

            //Rows
            this.Rows = new List<ResultRow>();
            while (reader.Read())
                this.Rows.Add(new ResultRow(this, reader));

            this.RowCount = this.Rows.Count;
        }

        public int GetColumnIndex(string columnName)
        {
            return this._columnNameIndexes[columnName];
        }

        public Dictionary<string, object>[] GetSerializable()
        {
            var result = new Dictionary<string, object>[this.RowCount];
            for (var i = 0; i < this.RowCount; i++)
            {
                result[i] = new Dictionary<string, object>();
                for (var j = 0; j < this.ColumnCount; j++)
                    result[i].Add(this.ColumnNames[j], this.Rows[i][j]);
            }

            return result;
        }

        public ResultRow NewRow()
        {
            return new ResultRow(this);
        }

        public void Dispose()
        {
            foreach (var row in this.Rows)
                row.Dispose();

            this.Rows = null;
            this._columnNameIndexes = null;
            this.ColumnNames = null;
        }
    }
}


text:
<?php
declare(strict_types=1);

namespace Networking\InitCmsBundle\Block;

use Sonata\BlockBundle\Block\Service\AbstractBlockService;
use Symfony\Component\HttpFoundation\Response;
use Sonata\BlockBundle\Block\BlockContextInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Twig\Environment;

/**
 * Class OnlineUsersBlockService.
 *
 * @author info@networking.ch
 */
class VersionBlockService extends AbstractBlockService
{
    /**
     * @var string
     */
    protected $projectDir;

    /**
     * VersionBlockService constructor.
     *
     * @param Environment $twig
     * @param             $projectDir
     */
    public function __construct(Environment $twig, $projectDir)
    {
        $this->projectDir = $projectDir;
        parent::__construct($twig);

    }

    /**
     * {@inheritdoc}
     */
    public function execute(
        BlockContextInterface $blockContext,
        ?Response $response = null
    ): Response {
        $version = 'master';

        if (file_exists($this->projectDir.'/composer.lock')) {
            $content = file_get_contents($this->projectDir.'/composer.lock');
            $content = json_decode($content, true);
            foreach ($content['packages'] as $package) {
                if ('networking/init-cms-bundle' === $package['name']) {
                    $version = $package['version'];
                }
            }
        }

        return $this->renderResponse(
            $blockContext->getTemplate(),
            [
                'block' => $blockContext->getBlock(),
                'version' => $version,
            ],
            $response
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'Version Block';
    }

    /**
     * {@inheritdoc}
     */
    public function configureSettings(OptionsResolver $resolver): void
    {
        $resolver->setDefaults(
            [
                'template' => '@NetworkingInitCms/Block/block_version.html.twig',
            ]
        );
    }
}


text:
mod attrs;
mod config_type;
mod item_enum;
mod item_struct;
mod utils;

use std::str::FromStr;

use proc_macro::TokenStream;
use syn::parse_macro_input;

#[proc_macro_attribute]
pub fn config_type(_args: TokenStream, input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as syn::Item);
    let output = config_type::define_config_type(&input);

    #[cfg(feature = "debug-with-rustfmt")]
    {
        utils::debug_with_rustfmt(&output);
    }

    TokenStream::from(output)
}

/// Used to conditionally output the TokenStream for tests that need to be run on nightly only.
///
/// ```rust
/// # use rustfmt_config_proc_macro::nightly_only_test;
///
/// #[nightly_only_test]
/// #[test]
/// fn test_needs_nightly_rustfmt() {
///   assert!(true);
/// }
/// ```
#[proc_macro_attribute]
pub fn nightly_only_test(_args: TokenStream, input: TokenStream) -> TokenStream {
    // if CFG_RELEASE_CHANNEL is not set we default to nightly, hence why the default is true
    if option_env!("CFG_RELEASE_CHANNEL").map_or(true, |c| c == "nightly" || c == "dev") {
        input
    } else {
        // output an empty token stream if CFG_RELEASE_CHANNEL is not set to "nightly" or "dev"
        TokenStream::from_str("").unwrap()
    }
}

/// Used to conditionally output the TokenStream for tests that need to be run on stable only.
///
/// ```rust
/// # use rustfmt_config_proc_macro::stable_only_test;
///
/// #[stable_only_test]
/// #[test]
/// fn test_needs_stable_rustfmt() {
///   assert!(true);
/// }
/// ```
#[proc_macro_attribute]
pub fn stable_only_test(_args: TokenStream, input: TokenStream) -> TokenStream {
    // if CFG_RELEASE_CHANNEL is not set we default to nightly, hence why the default is false
    if option_env!("CFG_RELEASE_CHANNEL").map_or(false, |c| c == "stable") {
        input
    } else {
        // output an empty token stream if CFG_RELEASE_CHANNEL is not set or is not 'stable'
        TokenStream::from_str("").unwrap()
    }
}

/// Used to conditionally output the TokenStream for tests that should be run as part of rustfmts
/// test suite, but should be ignored when running in the rust-lang/rust test suite.
#[proc_macro_attribute]
pub fn rustfmt_only_ci_test(_args: TokenStream, input: TokenStream) -> TokenStream {
    if option_env!("RUSTFMT_CI").is_some() {
        input
    } else {
        let mut token_stream = TokenStream::from_str("#[ignore]").unwrap();
        token_stream.extend(input);
        token_stream
    }
}


text:
'use strict';

/* Services */

var itemcatServices = angular.module('itemcatServices', ['ngResource']);

itemcatServices.factory('Phone', ['$resource',
  function($resource){
    return $resource('data/:phoneId.json', {}, {
      query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
    });
  }]);


text:
package com.opengamma.analytics.financial.instrument.annuity;

import javax.time.calendar.Period;
import javax.time.calendar.ZonedDateTime;

import org.apache.commons.lang.Validate;

import com.opengamma.analytics.financial.instrument.index.IndexSwap;
import com.opengamma.analytics.financial.instrument.payment.CapFloorCMSDefinition;
import com.opengamma.analytics.financial.schedule.ScheduleCalculator;
import com.opengamma.financial.convention.daycount.DayCount;

/**
 * A wrapper class for a AnnuityDefinition containing CMS cap/floor Definition.
 */
public class AnnuityCapFloorCMSDefinition extends AnnuityDefinition<CapFloorCMSDefinition> {

  /**
   * Constructor from a list of CMS coupons.
   * @param payments The CMS coupons.
   */
  public AnnuityCapFloorCMSDefinition(final CapFloorCMSDefinition[] payments) {
    super(payments);
  }

  /**
   * CMS cap/floor (or leg of CMS caplet/floorlet) constructor from standard description. The cap/floor are fixing in advance and payment in arrears.
   * The CMS fixing is done at a standard lag before the coupon start. The date are computed from the settlement date (stub last) with a short stub is necessary.
   * @param settlementDate The settlement date.
   * @param maturityDate The annuity maturity date.
   * @param notional The notional.
   * @param index The CMS index.
   * @param paymentPeriod The payment period of the coupons.
   * @param dayCount The day count of the coupons.
   * @param isPayer Payer (true) / receiver (false) fleg.
   * @param strike The common strike.
   * @param isCap The cap (true) / floor (false) flag.
   * @return The CMS coupon leg.
   */
  public static AnnuityCapFloorCMSDefinition from(final ZonedDateTime settlementDate, final ZonedDateTime maturityDate, final double notional, final IndexSwap index, final Period paymentPeriod,
      final DayCount dayCount, final boolean isPayer, final double strike, final boolean isCap) {
    Validate.notNull(settlementDate, "settlement date");
    Validate.notNull(maturityDate, "maturity date");
    Validate.notNull(index, "index");
    Validate.isTrue(notional > 0, "notional <= 0");
    Validate.notNull(paymentPeriod, "Payment period");
    final ZonedDateTime[] paymentDatesUnadjusted = ScheduleCalculator.getUnadjustedDateSchedule(settlementDate, maturityDate, paymentPeriod, true, false);
    final ZonedDateTime[] paymentDates = ScheduleCalculator.getAdjustedDateSchedule(paymentDatesUnadjusted, index.getIborIndex().getBusinessDayConvention(), index.getIborIndex().getCalendar(), false);
    final double sign = isPayer ? -1.0 : 1.0;
    final CapFloorCMSDefinition[] coupons = new CapFloorCMSDefinition[paymentDates.length];
    coupons[0] = CapFloorCMSDefinition.from(paymentDates[0], settlementDate, paymentDates[0], dayCount.getDayCountFraction(settlementDate, paymentDates[0]), sign * notional, index, strike, isCap);
    for (int loopcpn = 1; loopcpn < paymentDates.length; loopcpn++) {
      coupons[loopcpn] = CapFloorCMSDefinition.from(paymentDates[loopcpn], paymentDates[loopcpn - 1], paymentDates[loopcpn],
          dayCount.getDayCountFraction(paymentDates[loopcpn - 1], paymentDates[loopcpn]), sign * notional, index, strike, isCap);
    }
    return new AnnuityCapFloorCMSDefinition(coupons);
  }

}


text:
set -o xtrace

pub run test:test


text:
'use strict'

module.exports = {
  // https://tools.ietf.org/html/rfc4511#section-4.1.1
  // Message identifiers are an integer between (0, maxint).
  MAX_MSGID: Math.pow(2, 31) - 1
}


text:
	bags.lua
		Generic methods for accessing bag slot information
--]]

local ADDON, Addon = ...

--[[ Slot Type ]]--

function Addon:IsBackpack(slot)
	return slot == BACKPACK_CONTAINER
end

function Addon:IsBackpackBag(bagSlot)
  return bagSlot > 0 and bagSlot < (NUM_BAG_SLOTS + 1)
end

function Addon:IsBank(slot)
  return slot == BANK_CONTAINER
end

function Addon:IsReagents(slot)
	return slot == REAGENTBANK_CONTAINER
end

function Addon:IsBankBag(slot)
  return slot > NUM_BAG_SLOTS and slot < (NUM_BAG_SLOTS + NUM_BANKBAGSLOTS + 1)
end

--[[ Bag State ]]--

function Addon:GetBagInfo(...)
 	return self.Cache:GetBagInfo(...)
end

function Addon:IsBagCached(...)
  return self.Cache:GetBagType(...)
end

function Addon:IsBagLocked(player, bag)
	if not self:IsBackpack(bag) and not self:IsBank(bag) then
    	local slot, size, cached = select(4, self:GetBagInfo(player, bag))
		return not cached and IsInventoryItemLocked(slot)
	end
end

function Addon:GetBagSize(player, bag)
  	return select(5, self:GetBagInfo(player, bag))
end

function Addon:IsBagShown(frame, bag)
	local hidden = frame:GetProfile().hiddenBags
	if not frame:GetProfile().exclusiveReagent or bag == REAGENTBANK_CONTAINER or hidden[REAGENTBANK_CONTAINER] then
		return not hidden[bag]
	end
end

function Addon:BagToInventorySlot(...)
  return select(4, self:GetBagInfo(...))
end

--[[ Bag Type ]]--

Addon.BAG_TYPES = {
	[0x00008] = 'leather',
	[0x00010] = 'inscribe',
	[0x00020] = 'herb',
	[0x00040] = 'enchant',
	[0x00080] = 'engineer',
	[0x00200] = 'gem',
	[0x00400] = 'mine',
 	[0x08000] = 'tackle',
 	[0x10000] = 'refrige',
 	[-1] = 'reagent'
}

function Addon:GetBagType(...)
	return Addon.BAG_TYPES[self:GetBagFamily(...)] or 'normal'
end

function Addon:GetBagFamily(player, bag)
	if self:IsBank(bag) or self:IsBackpack(bag) then
		return 0
	elseif self:IsReagents(bag) then
		return -1
	end

	local link = self:GetBagInfo(player, bag)
	if link then
		return GetItemFamily(link)
	end
end


text:
app.controller('VagasController', function($scope, CandidatoService){
  $scope.title = "Vagas Controller - Candidato";
});


text:
using System;
using System.Windows.Data;

namespace Nuance.Radiology.DNSProfileChecker.Converters
{
	public sealed class ProcessingProfileConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			if (value == null)
				return "Current processing profile: NONE";
			return string.Format("Current processing profile: {0}", value);
		}

		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			throw new NotImplementedException();
		}
	}
}


text:
<TITLE>Review for Austin Powers: The Spy Who Shagged Me (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Austin Powers: The Spy Who Shagged Me (1999)

reviewed by
Harvey S. Karten

AUSTIN POWERS 2: THE SPY WHO SHAGGED ME

 Reviewed by Harvey Karten, Ph.D.
 New Line Cinema
 Director:  M. Jay Roach
 Writer:  Mike Myers, Michael McCullers
 Cast: Mike Myers, Heather Graham, Robert Wagner, Gia
Carides, Seth Green, Cindy Margolis, Kristen Johnston, Rob
Lowe

   A movie need not have a tightly-wound, unified plot to
work.  One recent film--a critically underrated box office flop
--functioned like a series of Saturday Night Live sketches and
was laugh-a-minute funny throughout.  I speak of Mike
Judge's Dilbert-like "Office Space," which should have been a
hoot for those in the audience who make their living in
offices.  Mike Judge arrays in their cubicles crunching
numbers and doing assorted jobs which are not in the least
as meaningful as the genuinely productive deeds that
muscular guys accomplish on the street with their drills,
hammers, and saws.  The basis for its rich humor is its
grounding in reality.  Although as distorted as a Hirschfield
caricature, "Office Space" reveals the emotional truths that
inhabit the souls of so many guys and gals who trudge to
their metal desks in Kafkaesque rooms shuffling papers that
only wind up in the circular file.

   "Austin Powers 2: The Spy Who Shagged Me," similarly a
series of sketches, has virtually no basis in reality.  Even that
defect could be compensated for if the humor were not so
sophomoric, repetitive, just plain unfunny.  Despite the
abundant scatological references and allusions to the penis,
"Austin Powers 2" cannot even boast of its potential to offend
anyone to the left of the Ayatollahs.  Too bad the script is not
up to the acting ability of Mike Myers, who wowed his
aficionados in the (also underrated) "So I Married an Ax
Murderer," which found the humorist in multiple roles as well.
He was almost unrecognizable when he affected a deep
Scottish brogue in the guise of his own father.

   Where "Office Space" holds a thesis--that work is a
travesty that kills the human spirit--"Austin Powers 2" simply
relies on scattershot gags loosely tied together by two
doctrines: 1) that most advertising and a great deal of TV are
largely ridiculous.  Then again, we knew that ever since we
were 4 years old and began spoofing the silly commercials
ourselves.  2) Much is made of the paradox that the private
parts of the human body are at once the source of sexual
turn-ons and the root of the most vulgar of excretory activity.

   The film jumps freely back and forth from 1999 to 1969 as
Dr. Evil (Mike Myers in his glabrous guise) plots to destroy
master spy Austin Powers (Mike Myers in his Carnaby Street
aspect).  Powers had been freeze-dried and, thawed out in
the 90s is now honeymooning with his bride, Vanessa
(Elizabeth Hurley), who turns out to be other than the person
he expected.  In the catchies scene of the entire work,
Vanessa asks, "Do you smoke after sex"? Powers replies, "I
don't know.  I never look."  The way Powers discovers that
his wife is a fembot is a gem.  While Powers ducks the
fussilades aimed at him by his stripped-down wife,  Dr. Evil
enters his time machine to return to 1969 with the aim of
stealing Powers' "mojo," which, loosely translated, is the
groovy guy's libido.

   Unlike "International Man of Mystery," this version treats
the eponymous spy as a all-around swinger and idol and not
as the nerdy oddball he portrayed two years ago.  Largely a
send-up of the James Bond series, the movie shows our hero
fixing a cup of coffee not in the manner of Sean Connery
(who could make a cappuccino in one-quarter the time of the
typical Starbuck's clerk today) but mistakenly pouring the
contents of a cup of stool sample into his cup and later
comparing the taste to that of almonds.

   There are some cute cameos, as of Burt Bacharach and
Elvis Costello, of Woody Harrelson and of Tim Robbins, but
the biggest surprise of all is in the actor who plays a
repulsive 400-pound Scotsman known as Fat Bastard.
Heather Graham as Bond's CIA-based girl friend does not
have the sophistication or dazzling good looks of Liz Hurley,
but she has the talent for vaudevillian touches.  And Mike
Myers continues to charm.  I feel bad for him that he lacks a
more resonant script: the guy's a comic genius who can
charm the pants off even an adult audience.  But this time
around he's in yet another vehicle that does not adequately
exploit his flair for comedy, particularly his almost unique
ability to assume multiple roles with vaudevillian abandon.

Rated PG-13.  Running Time: 90 minutes.  (C) 1999
Harvey Karten

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
import * as $ from 'jquery'
import Window from './Window'
import { Dispatcher } from '../Controller'
import { Action, ActionKind } from '../Actions'
import { Value } from 'interprete-pl'
import { Resizeable } from '../DragManager'

export default class OutputPanel implements Resizeable {
    parent: JQuery
    container: JQuery
    private output: Window
    private dispatcher: Dispatcher
    private bar: JQuery
    private step_button: JQuery
    private stop_button: JQuery
    container_index: number
    panel_index: number

    constructor(container: JQuery, d: Dispatcher) {
        this.parent = container
        this.dispatcher = d

        this.container = $('

')

        const bar = this.create_title_bar()

        this.bar = bar

        this.step_button.click(() => { this.dispatcher.dispatch({ kind: ActionKind.Step }) })
        this.stop_button.click(() => { this.dispatcher.dispatch({ kind: ActionKind.StopExecutionUser }) })

        const output_container = $('

')

        this.output = new Window(output_container, this.dispatcher)

        this.container.append(bar).append(output_container)
    }

    create_title_bar() {
        const bar = $('

')
        const icon = $('')
        const title = $('SALIDA')

        this.step_button = $('<button class="green-button icon-button"></button>')
        this.stop_button = $('<button class="red-button icon-button"></button>')

        bar.append(icon, title, this.step_button, this.stop_button)

        this.hide_controls()

        return bar
    }

    show_controls() {
        this.step_button.show()
        this.stop_button.show()
    }

    hide_controls() {
        this.step_button.hide()
        this.stop_button.hide()
    }

    write(v: Value) {
        this.output.write(v)
    }

    read() {
        this.output.read()
    }

    clear() {
        this.output.clear()
    }
}


text:
<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;

use \App\User;
use \App\Comments;
use \App\Like;
use PhpParser\Comment;

class CommentFactory extends Model {

	public function getComment($id) {
		return Comments::find($id);
	}

	public function deleteComment($id) {
		return Comments::destroy($id);
	}

	public function createComment($userId, $propositionId, $body) {

		return Comments::create([
				"commenter_id" => $userId,
				"proposition_id" => $propositionId,
				"body" => $body,
		]);
	}

	public function findLikeById($likeId) {
		return Like::find($likeId);
	}

	public function getLikesByComment(Comments $comment) {
		return Like::where('comment_id','=',$comment->commentId())->orderBy('updated_at', 'DESC')->get();
	}

	public function findLikeByUserAndComment(User $user, Comments $comment) {
		return Like::where('comment_id','=',$comment->commentId())->where('user_id','=',$user->userId())->get()->first();
	}

	public function getNumberOfLikes(Comments $comment) {
		return Like::where('comment_id','=',$comment->commentId())->count();
	}

	public function userHasLiked(Comments $comment, User $user) {
		return Like::where('comment_id','=',$comment->commentId())->where('user_id','=',$user->userId())->count();
	}

	// Like comment
	public function likeComment(User $user, Comments $comment) {
		return Like::firstOrCreate([
				"user_id" => $user->userId(),
				"comment_id" => $comment->commentId(),
		]);
	}

	// Remove like
	public function removeLike(Like $like) {
		return Like::destroy($like->likeId());
	}

}


text:
<title>Type - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.7">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Pseudo-Ops.html#Pseudo-Ops" title="Pseudo Ops">
<link rel="prev" href="Title.html#Title" title="Title">
<link rel="next" href="Uleb128.html#Uleb128" title="Uleb128">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Uleb128,
Previous: Title,
Up: Pseudo Ops

7.111 .type

This directive is used to set the type of a symbol.

COFF Version

For COFF targets, this directive is permitted only within
.def/.endef pairs.  It is used like this:

     .type <var>int</var>

This records the integer <var>int</var> as the type attribute of a symbol table
entry.

ELF Version

For ELF targets, the .type directive is used like this:

     .type <var>name</var> , <var>type description</var>

This sets the type of symbol <var>name</var> to be either a
function symbol or an object symbol.  There are five different syntaxes
supported for the <var>type description</var> field, in order to provide
compatibility with various other assemblers.

Because some of the characters used in these syntaxes (such as @ and
#) are comment characters for some architectures, some of the syntaxes
below do not work on all architectures.  The first variant will be accepted by
the GNU assembler on all architectures so that variant should be used for
maximum portability, if you do not need to assemble your code with other
assemblers.

The syntaxes supported are:

       .type <name> STT_<TYPE_IN_UPPER_CASE>
       .type <name>,#<type>
       .type <name>,@<type>
       .type <name>,%>type>
       .type <name>,"<type>"

The types supported are:

STT_FUNC
function
Mark the symbol as being a function name.

STT_OBJECT
object
Mark the symbol as being a data object.

STT_TLS
tls_object
Mark the symbol as being a thead-local data object.

STT_COMMON
common
Mark the symbol as being a common data object.

Note: Some targets support extra types in addition to those listed above.


text:
const regExp = /(?:https?:\/\/(?:www\.)?)?(?:twitter\.com\/)(?:#!\/)?(\w+)\/status(es)?\/(\d+)/i;

module.exports = function(md) {
    var defaultRender = md.renderer.rules.link_open || function(tokens, idx, options, env, self) {
        return self.renderToken(tokens, idx, options);
    };

    md.renderer.rules.link_open = function(tokens, idx, options, env, self) {
        var openToken = tokens[idx];
        var hrefIndex = openToken.attrIndex('href');

        // Ensure we have an "href" attribute
        if (hrefIndex !== -1) {
            var href = openToken.attrs[hrefIndex][1];

            // Ensure we have an "href" attribute value
            if (href) {
                var textToken = tokens[idx + 1];

                // Ensure we have a text token and the text matches the URL pattern instead of [text](http://example.com/)
                if (textToken && textToken.content && regExp.test(textToken.content)) {
                    var matches = href.match(regExp);

                    if (matches && matches[1] && matches[3]) {
                        var username = matches[1];
                        var status = matches[3];

                        textToken.content = '';
                        tokens[idx + 2].hidden = true;

                        return `<blockquote class="twitter-tweet" lang="en"><a href="https://twitter.com/${username}/status/${status}"></a></blockquote><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>`;
                    }
                }
            }
        }

        return defaultRender(tokens, idx, options, env, self);
    };
};


text:
<?php
namespace bbn\Db;

use bbn;
use bbn\Db;
use bbn\X;
use bbn\Str;

class Sync2 extends bbn\Models\Cls\Db
{

  use bbn\Models\Tts\Singleton,
      bbn\Models\Tts\Dbconfig,
      bbn\Models\Tts\Optional;
  /**
   * @var db The current DB connection
   */
  protected $current_connection;

  /**
   * @var array The sync connection information
   */
  protected $sync_connection;

  /**
   * @var bool
   **/
  protected $has_history = false;

  /**
   * @var array The tables to be synchronized in the current DB.
   */
  protected $tables = [];

  /**
   * @var string The name of the sync table.
   */
  protected $sync_table = 'dbsync';

  /** @var array */
  protected $methods = [];

  /**
   * @var array The default configuration for the sync database.
   */
  protected static $default_cfg = [
    'engine' => 'sqlite',
    'host' => 'localhost',
    'db' => 'dbsync'
  ];

  /**
   * @var array The synchronization database structure.
   */
  protected static $default_class_cfg = [
    'table' => 'dbsync',
    'tables' => [
      'dbsync' => 'dbsync'
    ],
    'arch' => [
      'dbsync' => [
        'id' => 'id',
        'tab' => 'tab',
        'action' => 'action',
        'rows' => 'rows',
        'vals' => 'vals'
      ]
    ]
  ];

  /**
   * @var bool Remains false until the function is initiated.
   */
  private $is_init = false;

  /**
   * @var bool
   */
  private $is_checked;

  /**
   * @var bool
   */
  private static $all_disabled = false;

  /**
   * @var bool
   */
  private $disabled = false;

  /**
   * @var int The max number of times the rows is error status will be tried before abandonning.
   */
  private $max_retry = 5;

  public function __construct(Db $db, array $tables, array $sync_cfg = null, array $arch = [])
  {
    parent::__construct($db);
    Singleton::init($this);
    $this->_init_class_cfg($arch);
    $this->opt = bbn\Appui\Option::getInstance();
    if ($this->opt) {
      self::retrieverInit($this);
    }
  }

  /**
   * @param bbn\Db $db
   * @param array $sync_cfg
   * @param array  $tables
   * @param string  $sync_table
   * @return void
   */
  public function init(db $db, array $sync_cfg = [], array $tables = [], string $sync_table = ''): void
  {
    if ($this->is_init) {
      throw new \Exception("Impossible to init twice the dbsync class");
    }
    $this->current_connection = $db;

    if (!empty($sync_table)) {
      $this->sync_table = $sync_table;
    }
    if (!Str::checkName($this->sync_table)) {
      throw new \Exception(X::_("Table name not allowed"));
    }
    if (empty($sync_cfg)) {
      $this->sync_connection = new Db(self::$default_cfg);
    }
    elseif (isset($sync_cfg['connection'])) {
      if (is_object($sync_cfg['connection']) && (is_a($sync_cfg['connection'], '\\bbn\\Db')
          || is_subclass_of($sync_cfg['connection'], '\\bbn\\Db'))
      ) {
        $this->sync_connection = $sync_cfg['connection'];
      }
      else {
        throw new \Exception(X::_("Invalid connection given to the synchronization class"));
      }
    }
    elseif (isset($sync_cfg['engine'])) {
      if (($sync_cfg['engine'] === 'sqlite')
          || ($sync_cfg['engine'] !== $this->current_connection->getEngine())
      ) {
        $this->sync_connection = new Db($sync_cfg);
      }
      elseif (isset($sync_cfg['db']) && !isset($sync_cfg['user'])) {
        $this->sync_connection =& $this->current_connection;
        $this->sync_table = $this->sync_connection->tfn($this->sync_table, $sync_cfg['db']);
      }
    }
    elseif (isset($sync_cfg['db']) && !isset($sync_cfg['user'])) {
      $this->sync_connection =& $this->current_connection;
      $this->sync_table = $this->sync_connection->tfn($this->sync_table, $sync_cfg['db']);
    }
    $this->tables = $tables;
    $this->is_init = true;
    if (\count($this->tables) === 0) {
      $this->tables = $this->current_connection->getTables();
    }
    if (\is_array($this->tables)) {
      foreach ($this->tables as $i => $t){
        $this->tables[$i] = $this->current_connection->tableFullName($t);
      }
      $this->current_connection->setTrigger(
        '\\bbn\Db\\sync::trigger',
        ['delete', 'update', 'insert'],
        ['before', 'after'],
        $this->tables
      );
    }
  }

  public function isInit()
  {
    return $this->is_init;
  }

  public function createTable()
  {
    if (\is_array($this->sync_connection)) {
      $this->sync_connection = new bbn\Db($this->sync_connection);
    }
    if (class_exists('\\bbn\\Appui\\History') && bbn\Appui\History::$is_used) {
      $this->has_history = 1;
    }
    /** @todo Replace with DB functions */
    if ($this->sync_connection->getEngine() === 'sqlite') {
      $this->sync_connection->exec(
        sprintf(
          'CREATE TABLE "%s" (
            "id" INTEGER PRIMARY KEY  NOT NULL ,
            "db" TEXT NOT NULL ,
            "tab" TEXT NOT NULL ,
            "chrono" REAL NOT NULL,
            "action" TEXT NOT NULL,
            "rows" TEXT,"vals" TEXT,
            "state" INTEGER NOT NULL DEFAULT (0)
          );
          CREATE INDEX "db" "dbsync" ("db");
          CREATE INDEX "tab" "dbsync" ("tab");
          CREATE INDEX "chrono" "dbsync" ("chrono");
          CREATE INDEX "action" "dbsync" ("action");
          CREATE INDEX "state" "dbsync" ("state");',
          $this->table_sync
        )
      );
    }
    elseif ($this->sync_connection->getEngine() === 'mysql') {
      $this->sync_connection->exec(
        sprintf(
          "CREATE TABLE IF NOT EXISTS `%s` (
            `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
            `db` varchar(50) NOT NULL,
            `tab` varchar(50) NOT NULL,
            `chrono` decimal(14,4) unsigned NOT NULL,
            `action` varchar(20) NOT NULL,
            `rows` text,
            `vals` longtext,
            `state` int(10) NOT NULL DEFAULT '0'
          ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
          ALTER TABLE `dbsync`
            ADD PRIMARY KEY (`id`),
            ADD KEY `db` (`db`),
            ADD KEY `tab` (`tab`),
            ADD KEY `chrono` (`chrono`),
            ADD KEY `action` (`action`),
            ADD KEY `state` (`state`);",
            $this->table_sync
        )
      );
    }
  }

  /**
   * Checks if the initialization has been all right - performs it only once.
   *
   * @return bool
   */
  public function check(): bool
  {
    if (!isset($this->is_checked)) {
      $this->is_checked = \is_object($this->current_connection)
        && \is_object($this->sync_connection)
        && $this->current_connection->check()
        && $this->sync_connection->check();
    }
    return $this->is_checked;
  }

  /**
   * Disable the sync trigger.
   *
   * @return void
   */
  public function disable(): void
  {
    $this->disabled = true;
  }

  /**
   * Enable the sync trigger.
   *
   * @return void
   */
  public function enable(): void
  {
    $this->disabled = false;
  }

  /**
   * Writes new rows in the sync table after a writing operation has happened.
   *
   * @param array $cfg Configuration array
   * @return array Resulting configuration
   */
  public function trigger(array $cfg): array
  {
    /** @todo I would like to understand... */
    if (!isset($cfg['run'])) {
      $cfg['run'] = 1;
    }
    if (!isset($cfg['trig'])) {
      $cfg['run'] = 1;
    }
    if (!$this->disabled
        && $this->check()
        && (count($cfg['tables']) === 1)
        && ($table = $this->current_connection->tfn(current($cfg['tables'])))
        && \in_array($table, $this->tables, true)
    ) {
      if ($cfg['moment'] === 'after') {
        // Case where we actually delete or restore through the $hcol column
        $values = [];
        if (X::hasProps($cfg, ['fields', 'values'], true)) {
          foreach ($cfg['fields'] as $i => $f) {
            $values[$f] = $cfg['values'][$i];
          }
        }
        $this->sync_connection->insert(
          $this->sync_table, [
          'db' => $this->current_connection->getCurrent(),
          'tab' => $this->current_connection->tsn($table),
          'action' => $cfg['kind'],
          'chrono' => microtime(true),
          'rows' => empty($cfg['where']) ? '[]' : X::jsonBase64Encode($cfg['where']),
          'vals' => empty($values) ? '[]' : X::jsonBase64Encode($values)
          ]
        );
      }
    }
    return $cfg;
  }

  public static function callback1(callable $f)
  {
    self::addMethod('cbf1', $f);
  }

  public static function callback2(callable $f)
  {
    self::addMethod('cbf2', $f);
  }

  public function deleteCompleted(float $start = null)
  {
    if (!self::isInit()) {
      die("DB sync is not initiated");
    }
    if (!$start
        || !($start = $this->sync_connection->selectOne(
          $this->sync_table, 'MIN(chrono)', [
          ['db', 'NOT LIKE', $this->current_connection->getCurrent()],
          'state' => 0
          ]
        ))
    ) {
      $start = time();
    }
    // Deleting the entries prior to this sync we produced and have been seen by the twin process
    return $this->sync_connection->delete(
      $this->sync_table, [
      'db' => $this->current_connection->getCurrent(),
      'state'=> 1,
      ['chrono', '<', $start]
      ]
    );
  }

  public function currentRowCfg($row): array
  {

  }

  public function destRowCfg($row): array
  {

  }

  // Looking at the rows from the other DB with status = 0 and setting them to 1
  // Comparing the new rows with the ones from this DB
  // Deleting the rows from this DB which have state = 1
  public function sync(bbn\Db $db, $dbs='', $sync_table='', $num_try = 0)
  {
    if (!self::isInit()) {
      die("DB sync is not initiated");
    }
    self::disable();
    $mode_db = $this->current_connection->getErrorMode();
    $mode_dbs = $this->sync_connection->getErrorMode();
    $this->current_connection->setErrorMode("continue");
    $this->sync_connection->setErrorMode("continue");

    $num_try++;

    $to_log = [
      'deleted_sync' => 0,
      'deleted_real' => 0,
      'updated_sync' => 0,
      'updated_real' => 0,
      'inserted_sync' => 0,
      'inserted_real' => 0,
      'num_problems' => 0,
      'problems' => []
    ];

    $to_log['deleted_sync'] = self::deleteCompleted();

    $retry = false;

    // Selecting the entries inserted
    $ds = $this->sync_connection->rselectAll(
      $this->sync_table, ['id', 'tab', 'vals', 'chrono'], [
      ['db', '!=', $this->current_connection->getCurrent()],
      ['state', '=', 0],
      ['action', 'LIKE', 'INSERT']
      ], [
      'chrono' => 'ASC',
      'id' => 'ASC'
      ]
    );
    // They just have to be inserted
    foreach ($ds as $i => $d){
      if (isset($this->methods['cbf1'])) {
        self::cbf1($d);
      }
      $vals = X::jsonBase64Decode($d['vals']);
      if (!\is_array($vals)) {
        $to_log['num_problems']++;
        $to_log['problems'][] = "Hey, look urgently at the row $d[id]!";
      }
      elseif ($this->current_connection->insert($d['tab'], $vals)) {
        if (isset($this->methods['cbf2'])) {
          self::cbf2($d);
        }
        $to_log['inserted_sync']++;
        $this->sync_connection->update($this->sync_table, ["state" => 1], ["id" => $d['id']]);
      }
      elseif ($this->current_connection->select($d['tab'], [], $vals)) {
        $this->sync_connection->update($this->sync_table, ["state" => 1], ["id" => $d['id']]);
      }
      else{
        if ($num_try > $this->max_retry) {
          $to_log['num_problems']++;
          $to_log['problems'][] = "Problem while syncing (insert), check data with status 5 and ID ".$d['id'];
          $this->sync_connection->update($this->sync_table, ["state" => 5], ["id" => $d['id']]);
        }
        $retry = 1;
      }
    }

    // Selecting the entries modified and deleted in the twin DB,
    // ordered by table and rows (so the same go together)
    $ds = $this->sync_connection->rselectAll(
      $this->sync_table, ['id', 'tab', 'action', 'rows', 'vals', 'chrono'], [
      ['db', '!=', $this->current_connection->getCurrent()],
      ['state', '=', 0],
      ['rows', '!=', '[]'],
      ['action', '!=', 'insert']
      ], [
      'tab' => 'ASC',
      'rows' => 'ASC',
      'chrono' => 'ASC',
      'id' => 'ASC'
      ]
    );
    foreach ($ds as $i => $d){
      // Executing the first callback
      $d['rows'] = X::jsonBase64Decode($d['rows']);
      $d['vals'] = X::jsonBase64Decode($d['vals']);
      if (isset($this->methods['cbf1'])) {
        self::cbf1($d);
      }
      // Proceeding to the actions: delete is before
      if (strtolower($d['action']) === 'delete') {
        if ($this->current_connection->delete($d['tab'], $d['rows'])) {
          $this->sync_connection->update($this->sync_table, ["state" => 1], ["id" => $d['id']]);
          $to_log['deleted_real']++;
        }
        elseif (!$this->current_connection->select($d['tab'], [], $d['rows'])) {
          $this->sync_connection->update($this->sync_table, ["state" => 1], ["id" => $d['id']]);
        }
        else{
          if ($num_try > $this->max_retry) {
            $this->sync_connection->update($this->sync_table, ["state" => 5], ["id" => $d['id']]);
            $to_log['num_problems']++;
            $to_log['problems'][] = "Problem while syncing (delete), check data with status 5 and ID ".$d['id'];
          }
          $retry = 1;
        }
      }
      // Checking if there is another change done to this record and when in the twin DB
      $next_time = (
              isset($ds[$i+1]) &&
              ($ds[$i+1]['tab'] === $d['tab']) &&
              ($ds[$i+1]['rows'] === $d['rows'])
            ) ? $ds[$i+1]['chrono'] : microtime();
      // Looking for the actions done on this specific record in our database
      // between the twin change and the next (or now if there is no other change)
      $each = $this->sync_connection->rselectAll(
        $this->sync_table, ['id', 'chrono', 'action', 'vals'], [
        ['db', '=', $this->current_connection->getCurrent()],
        ['tab', '=', $d['tab']],
        ['rows', '=', $d['rows']],
        ['chrono', '>=', $d['chrono']],
        ['chrono', '<', $next_time],
        ]
      );
      if (\count($each) > 0) {
        $to_log['num_problems']++;
        $to_log['problems'][] = "Conflict!";
        $to_log['problems'][] = $d;
        foreach ($each as $e){
          $e['vals'] = X::jsonBase64Decode($e['vals']);
          // If it's deleted locally and updated on the twin we restore
          if (strtolower($e['action']) === 'delete') {
            if (strtolower($d['action']) === 'update') {
              if (!$this->current_connection->insertUpdate(
                $d['tab'],
                X::mergeArrays(
                  $e['vals'],
                  $d['vals']
                )
              )
              ) {
                $to_log['num_problems']++;
                $to_log['problems'][] = "insert_update number 1 had a problem";
              }
            }
          }
          // If it's updated locally and deleted in the twin we restore
          elseif (strtolower($e['action']) === 'update') {
            if (strtolower($d['action']) === 'delete') {
              if (!$this->current_connection->insertUpdate($d['tab'], X::mergeArrays($d['vals'], $e['vals']))) {
                $to_log['num_problems']++;
                $to_log['problems'][] = "insert_update had a problem";
              }
            }
            // If it's updated locally and in the twin we merge the values for the update
            elseif (strtolower($d['action']) === 'update') {
              $d['vals'] = X::mergeArrays($d['vals'], $e['vals']);
            }
          }
        }
      }
      // Proceeding to the actions update is after in case we needed to restore
      if (strtolower($d['action']) === 'update') {
        X::log(X::mergeArrays($d['rows'], $d['vals']), 'synct');
        if ($this->current_connection->update($d['tab'], $d['vals'], $d['rows'])) {
          $this->sync_connection->update($this->sync_table, ["state" => 1], ["id" => $d['id']]);
          $to_log['updated_real']++;
        }
        elseif ($this->current_connection->count($d['tab'], X::mergeArrays($d['rows'], $d['vals']))) {
          $this->sync_connection->update($this->sync_table, ["state" => 1], ["id" => $d['id']]);
        }
        else{
          if ($num_try > $this->max_retry) {
            $this->sync_connection->update($this->sync_table, ["state" => 5], ["id" => $d['id']]);
            $to_log['num_problems']++;
            $to_log['problems'][] = "Problem while syncing (update), check data with status 5 and ID ".$d['id'];
          }
          $retry = 1;
        }
      }
      // Callback number 2
      if (isset($this->methods['cbf2'])) {
        self::cbf2($d);
      }
    }

    $res = [];
    foreach ($to_log as $k => $v){
      if (!empty($v)) {
        $res[$k] = $v;
      }
    }
    $this->current_connection->setErrorMode($mode_db);
    $this->sync_connection->setErrorMode($mode_dbs);
    self::enable();
    if ($retry && ( $num_try <= $this->max_retry )) {
      $res = X::mergeArrays($res, self::sync($db, $dbs, $sync_table, $num_try));
    }
    return $res;
  }
}


text:
using namespace std;
using namespace boost;
using namespace IECore;
using namespace Gaffer;

void GafferTest::testRandomPerf()
{
	ContextPtr base = new Context();
	InternedString varName = "varName";

	Gaffer::RandomPtr random = new Gaffer::Random();
	random->seedVariablePlug()->setValue( varName.string() );

	Context::EditableScope scope( base.get() );
	for( int i = 0; i < 100000; ++i )
	{
		scope.set( varName, &i );
		random->outColorPlug()->getValue();
	}
}


text:
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);

client
  .calls('CA42ed11f93dc08b952027ffbc406d0868')
  .feedback()
  .fetch()
  .then(feedback => console.log(feedback.dateCreated));


text:
pub use self::decoder::AvifDecoder;
#[cfg(feature = "avif-encoder")]
pub use self::encoder::{AvifEncoder, ColorSpace};

#[cfg(feature = "avif-decoder")]
mod decoder;
#[cfg(feature = "avif-encoder")]
mod encoder;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.pjay</groupId>
	<artifactId>hystrix-sentenceservice-solution-reactive</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>hystrix-sentenceservice-solution-reactive</name>
	<description>Microservices with spring cloud</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<!-- We can't have two parent POMs, so use DependencyManagement to show Maven where the Spring Cloud dependencies are. -->
	<!-- http://projects.spring.io/spring-cloud/ -->
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-starter-parent</artifactId>
				<version>Camden.SR6</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<dependencies>

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-ribbon</artifactId>
		</dependency>

	    <dependency>
	        <groupId>org.springframework.cloud</groupId>
	        <artifactId>spring-cloud-starter-feign</artifactId>
	    </dependency>

	    <dependency>
	        <groupId>org.springframework.cloud</groupId>
	        <artifactId>spring-cloud-starter-hystrix</artifactId>
	    </dependency>

	    <dependency>
	        <groupId>org.springframework.cloud</groupId>
	        <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
	    </dependency>

	    <dependency>
    		<groupId>io.reactivex</groupId>
    		<artifactId>rxjava</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<!-- Allow for automatic restarts when classpath contents change. -->
	    <dependency>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-devtools</artifactId>
	        <optional>true</optional>
	    </dependency>

	    <!-- Not sure if we need this dependency, hence commenting it. This is present in lab7 tutorial from instructor -->
		<!-- <dependency>
			<groupId>org.apache.ant</groupId>
			<artifactId>ant</artifactId>
			<version>1.9.3</version>
		</dependency>

		<dependency>
			<groupId>net.wimpi</groupId>
			<artifactId>telnetd-x</artifactId>
			<version>2.1.1</version>
		</dependency> -->

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


text:
from django.core.files import File
from django.core.files.images import get_image_dimensions
from django.test import TestCase
from django.utils.translation import ugettext_lazy as _

from feincms.module.medialibrary.models import MediaFile

class ThumbnailTest(TestCase):
    def setUp(self):
        from extensions import media_variation
        MediaFile.register_extension(media_variation)
        mediafile = MediaFile(file=File(open('feinheit/media_variations/fixtures/elephant_test_image.jpeg')))
        mediafile.save()
        self.image = mediafile

    def test_setup(self):
        self.assertEqual(self.image.type, 'image')
        self.assertEqual(get_image_dimensions(self.image.file), (404, 346))

    def test_processing(self):
        self.assertEqual(self.image.variations.all().count(), 0)

        thumbnail = self.image.get_variation('image-thumbnail', {'height' : 34, 'width' : 40})
        self.assertEqual(get_image_dimensions(thumbnail.file), (40, 34))
        self.assertEqual(self.image.variations.all().count(), 1)

        # get_variation only creates a variation if it does not exists
        self.image.get_variation('image-thumbnail', {'width' : 40, 'height' : 34})
        self.assertEqual(self.image.variations.all().count(), 1)

        cropscale = self.image.get_variation('image-cropscale', {'height' : 20, 'width' : 20})
        self.assertEqual(get_image_dimensions(cropscale.file), (20, 20))
        self.assertEqual(self.image.variations.all().count(), 2)

        #blur
        blur = self.image.get_variation('image-blur', {'amount' : 10 })
        self.assertEqual(get_image_dimensions(blur.file), (404, 346))
        self.assertEqual(self.image.variations.all().count(), 3)

        #blur crop
        cropblur = self.image.get_variation('image-cropblur', {'amount' : 10, 'height' : 20, 'width' : 20 })
        self.assertEqual(get_image_dimensions(cropblur.file), (20, 20))
        self.assertEqual(self.image.variations.all().count(), 4)

    def test_templatetags(self):
        from templatetags.mediavariation_thumbnail import thumbnail, cropscale

        thumbnail(self.image)
        thumbnail_url = thumbnail(self.image, '24x40q50')
        self.assertEqual(type(thumbnail_url), unicode)
        self.assertTrue('24x40q50' in thumbnail_url)

        cropscale(self.image)
        cropscale_url = cropscale(self.image, '24x40q50')
        self.assertEqual(type(cropscale_url), unicode)
        self.assertTrue('24x40q50' in cropscale_url)

        ## this test crashes, because in the test enviroment, thumbnail_url has a ../ prefix. in
        ## realworld, it hasnt
        #response = self.client.get('/' + thumbnail_url)
        #self.assertEqual(response.status_code, 200)

    def test_preselection(self):
        from models import MediaVariation
        MediaVariation.register_preselection(
            ('cropscale50x50', _('50px Square Thumbnail'), 'image-cropscale', {'height' : 50, 'width' : 50}),
            ('thumbnail150x99999', _('Max 150px wide image'), 'image-thumbnail', {'height' : 150, 'width' : 99999}),
        )
        processed = self.image.get_variation('cropscale50x50')
        self.assertEqual(get_image_dimensions(processed.file), (50, 50))
        self.assertEqual(processed.processor, 'image-cropscale')
        self.assertEqual(processed.options, {'height' : 50, 'width' : 50})

        from templatetags.mediavariation_thumbnail import mediavariation
        variation_url = mediavariation(self.image, 'cropscale50x50')
        self.assertEqual(type(variation_url), unicode)
        self.assertTrue('50x50' in variation_url)

    def test_autocreation(self):
        from models import MediaVariation
        MediaVariation.register_preselection(
            ('cropscale50x50', _('50px Square Thumbnail'), 'image-cropscale', {'height' : 50, 'width' : 50}),
            ('thumbnail150x99999', _('Max 150px wide image'), 'image-thumbnail', {'height' : 150, 'width' : 99999}),
        )
        from extensions import auto_creation
        MediaFile.register_extension(auto_creation)
        MediaFile.register_variation_auto_creation('cropscale50x50', 'thumbnail150x99999')
        self.assertEqual(MediaFile.variation_auto_creation, ['cropscale50x50', 'thumbnail150x99999'])
        processed = self.image.get_variation('cropscale50x50')
        self.assertEqual(get_image_dimensions(processed.file), (50, 50))


text:
layout: post
title: Application for Extension of Period of Stay Guide
---

日本語版は[こちら]({% post_url 2020-12-19-在留期間更新許可申請ガイド %})!

~~~

Recently I've been through the process to extend my VISA here in Japan.
It can be a pretty smooth process if you know how it is,
*but* exhaustive if you don't.

While I was doing my extension,
I wish there were a Senpai that could guide me through the process.
Unfortunately, there weren't.
And I had some problems.
(To be more exact, the problem was in the documents my company issued.
So there is a chance that the person in charge at your company don't know the necessary documents.)

Here I'll share with you my experience,
and will be especially focused on the needed documents.
I hope you have a smooth extension process!

# Necessary documents

## Application for Extension of Period of Stay

[Download](http://www.moj.go.jp/content/001290202.pdf)

### Applicant

You can fill this application at the Immigration Office.
If you want to fill it beforehand,
you will need to fill the following pages of the PDF:

- **Page 1:** For applicant, part 1
- **Page 3:** For applicant, part 2

### Organization

It is necessary for the company to fill and stamp its seal beforehand.
Be sure to have this before going there.

- **Page 4:** For organization, part 1
- **Page 5:** For organization, part 2
- **Page 7:** For organization, part 4

Even if the company doesn't fill page 6,
it is needed to print and submit it, so be careful.

## Photo

3x4 cm, it will be attached to the application and submitted.
It is possible to attach (glue) at the Immigration Office.

## Passport and Residence Card

## Withholding tax slip of the last year

In Japanese:

- Kyuuyo Shotoku no Gensen Choushuuhyou - きゅうよ しょとく の げんせん ちょうしゅうひょう

You receive this document once every year from the company.

Seems that the company's stamp is needed.
Be on the safe side and ask for the stamp beforehand.
Submit the document's copy.

## Tax payment certificate

There are two certificates you need:

- Jyuuminzei no Kazei Shoumeisho - じゅうみんぜい の かぜい しょうめいしょ
- Nouzei Shoumeisho - のうぜい しょうめいしょ

It must have the latest information, with a period of 1 year.
You may get this document at your City Office. You pay a fee to get it.

## Certificate of employment

Ask the company.

---

# Reference

**In Japanese:**

- [Procedure](http://www.moj.go.jp/ONLINE/IMMIGRATION/16-3.html)
- [Application](http://www.moj.go.jp/ONLINE/IMMIGRATION/16-3-1.html)
- [Documents](http://www.moj.go.jp/nyuukokukanri/kouhou/nyuukokukanri07_00095.html)

**In English:**

I found those while typing this. Seems to be incomplete.

- [Procedure](http://www.immi-moj.go.jp/english/tetuduki/kanri/shyorui/03.html)
- [Application](http://www.immi-moj.go.jp/english/tetuduki/kanri/shyorui/03-format.html)
- [Documents](http://www.immi-moj.go.jp/english/tetuduki/kanri/shyorui/Table3-2.html)


text:
<?php
namespace DDPro\Admin\Tests\Fields;

use Mockery as m;

class NumberTest extends \PHPUnit_Framework_TestCase {

    /**
     * The Validator mock
     *
     * @var Mockery
     */
    protected $validator;

    /**
     * The Config mock
     *
     * @var Mockery
     */
    protected $config;

    /**
     * The DB mock
     *
     * @var Mockery
     */
    protected $db;

    /**
     * The FieldFactory mock
     *
     * @var Mockery
     */
    protected $field;

    /**
     * Set up function
     */
    public function setUp()
    {
        $this->validator = m::mock('DDPro\Admin\Validator');
        $this->config = m::mock('DDPro\Admin\Config\Model\Config');
        $this->db = m::mock('Illuminate\Database\DatabaseManager');
        $options = array('field_name' => 'field', 'type' => 'number');
        $this->field = m::mock('DDPro\Admin\Fields\Number', array($this->validator, $this->config, $this->db, $options))->makePartial();
    }

    /**
     * Tear down function
     */
    public function tearDown()
    {
        m::close();
    }

    public function testSetFilter()
    {
        $this->validator->shouldReceive('arrayGet')->times(3);
        $this->field->shouldReceive('getFilterValue')->times(3)
                    ->shouldReceive('getOption')->times(5);
        $this->field->setFilter(null);
    }

    public function testFillModel()
    {
        $model = new \stdClass();
        $this->field->shouldReceive('getOption')->once()->andReturn('field')
                    ->shouldReceive('parseNumber')->once()->andReturn('flerp');
        $this->field->fillModel($model, 'test');
        $this->assertEquals($model->field, 'flerp');
    }

    public function testFillModelNullInput()
    {
        $model = new \stdClass();
        $this->field->shouldReceive('getOption')->once()->andReturn('field')
                    ->shouldReceive('parseNumber')->never();
        $this->field->fillModel($model, null);
        $this->assertEquals($model->field, null);
    }

    public function testParseNumber()
    {
        $this->field->shouldReceive('getOption')->times(2)->andReturn('[', ']');
        $this->assertEquals($this->field->parseNumber('1]454]432[23'), '1454432.23');
    }

}


text:
<?php

namespace Webgrf\BibtexBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Doctrine\Common\Persistence\ObjectManager;

use Webgrf\BibtexBundle\Entity\Entry;

class BibtexToEntryTransformer implements DataTransformerInterface {

    private $container;

    public function __construct($container) {
        $this->container = $container;
    }

    /**
     * Transforms an object (entry) to a string (bibtex).
     *
     * @param  Issue|null $issue
     * @return string
     */
    public function transform($entry) {
        var_dump("transform");
        //var_dump($entry);

        if (null === $entry)// || !$entry->getBibtex())
            return "";

        $bibtex = $this->container->get("bibtex.entry")->get($entry);
        $entry->setBibtex($bibtex);
        return $entry;
    }

    /**
     * Transforms a string (bibtex) to an object (entry).
     *
     * @param  string $number
     * @return Issue|null
     * @throws TransformationFailedException if object (issue) is not found.
     */
    public function reverseTransform($entry) {
        var_dump("reverse");
        //var_dump($entry);

        if (!$entry)
            return null;

        try {
            $this->container->get("bibtex.entry")->set($entry);
        } catch (Exeception $e) {
            throw new TransformationFailedException($e->getMessage());
        }

        /*
        $issue = $this->om
                ->getRepository('AcmeTaskBundle:Issue')
                ->findOneBy(array('number' => $number))
        ;

        if (null === $issue) {
            throw new TransformationFailedException(sprintf(
                            'An issue with number "%s" does not exist!', $number
            ));
        }*/

        return $entry;
    }

}


text:
FROM jboss/wildfly:latest

ADD ./mysql-connector-java-5.1.32.jar ./config_wildfly.sh /opt/jboss/wildfly/
RUN  sed -i_back 's/\r//g' /opt/jboss/wildfly/config_wildfly.sh

USER root
RUN groupadd -r wildfly-logs -g 433 && \
useradd -u 431 -r -g wildfly-logs -s /sbin/nologin -c "WildFly container logs" wildfly-logs

RUN mkdir -p /opt/jboss/wildfly/standalone/deployments
RUN chown wildfly-logs:wildfly-logs /opt/jboss/wildfly/standalone/deployments

RUN ["/opt/jboss/wildfly/config_wildfly.sh"]
RUN rm -rf  /opt/jboss/wildfly/standalone/configuration/standalone_xml_history
CMD ["/opt/jboss/wildfly/bin/standalone.sh", "--debug", "-b", "0.0.0.0", "-bmanagement", "0.0.0.0"]

expose 8080
expose 8787
expose 9990


text:
package org.srplib.reflection;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import org.srplib.reflection.ReflectionUtils;

/**
 * An empty implementation of {@link InvocationHandler}.
 *
 *
The main purpose is easy creation of null value objects.

 *
 * @author Anton Pechinsky
 */
public class EmptyInvocationHandler implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        // do nothing since this is an empty implementation

        Class returnType = method.getReturnType();

        return ReflectionUtils.getInitValue(returnType);
    }

}


text:
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201505](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201505.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public string Zone { get; set; }
```

### Property Value
Type: System.String

## See also
- [WebPartPageWebPart](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201505.WebPartPageWebPart.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201505](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201505.md)