text:
using namespace ciri;

//static void setVSync(bool sync)
//{
//	// Function pointer for the wgl extention function we need to enable/disable
//	// vsync
//	typedef BOOL (APIENTRY *PFNWGLSWAPINTERVALPROC)( int );
//	PFNWGLSWAPINTERVALPROC wglSwapIntervalEXT = 0;
//
//	const char *extensions = (char*)glGetString( GL_EXTENSIONS );
//
//	if( false && strstr( extensions, "WGL_EXT_swap_control" ) == 0 )
//	{
//		return;
//	}
//	else
//	{
//		wglSwapIntervalEXT = (PFNWGLSWAPINTERVALPROC)wglGetProcAddress( "wglSwapIntervalEXT" );
//
//		if( wglSwapIntervalEXT )
//			wglSwapIntervalEXT(sync);
//	}
//}

GLGraphicsDevice::GLGraphicsDevice()
	: IGraphicsDevice(), _isValid(false), _window(nullptr), _hdc(0), _hglrc(0), _defaultWidth(0), _defaultHeight(0),
		_currentFbo(0), _shaderExt(".glsl"), _dummyVao(0), _constantBufferCount(0) {
	// configure mrt draw buffers
	for( int i = 0; i < MAX_MRTS; ++i ) {
		_drawBuffers[i] = GL_COLOR_ATTACHMENT0 + i;
	}
}

GLGraphicsDevice::~GLGraphicsDevice() {
	destroy();
}

bool GLGraphicsDevice::create( const std::shared_ptr<IWindow>& window ) {
	if( _isValid ) {
		return false;
	}

	_window = window;

	_defaultWidth = window->getWidth();
	_defaultHeight = window->getHeight();

	if( !configureGlew() ) {
		destroy();
		return false;
	}

	if( !configureGl(static_cast<HWND>(window->getNativeHandle())) ) {
		destroy();
		return false;
	}

	_isValid = true;

	// apply a fullsize viewport
	setViewport(Viewport(0, 0, window->getWidth(), window->getHeight(), 0.0f, 1.0f));

	// set default states
	restoreDefaultStates();

	return true;
}

void GLGraphicsDevice::destroy() {
	if( !_isValid ) {
		return;
	}

	// clean default state pointers
	_defaultBlendAdditive = nullptr;
	_defaultBlendAlpha = nullptr;
	_defaultBlendNonPremul = nullptr;
	_defaultBlendOpaque = nullptr;
	_defaultRasterNone = nullptr;
	_defaultRasterClockwise = nullptr;
	_defaultRasterCounterClockwise = nullptr;
	_defaultDepthStencilDefault = nullptr;
	_defaultDepthStencilDepthRead = nullptr;
	_defaultDepthStencilNone = nullptr;

	// clean fbo
	if( 0 != _currentFbo ) {
		glDeleteFramebuffers(1, &_currentFbo);
		_currentFbo = 0;
	}

	// delete dummy vao
	if( _dummyVao != 0 ) {
		glDeleteVertexArrays(1, &_dummyVao);
		_dummyVao = 0;
	}

	// make rendering context not current
	wglMakeCurrent(0, 0);

	// delete the gl context
	if( _hglrc ) { wglDeleteContext(_hglrc); _hglrc = 0; }

	// delete device context
	if( _hdc ) { DeleteDC(_hdc); _hdc = 0; }

	_isValid = false;
}

void GLGraphicsDevice::present() {
	if( !_isValid ) {
		return;
	}

	SwapBuffers(_hdc);
}

void GLGraphicsDevice::setViewport( const Viewport& vp ) {
	// todo: if has valid context, can apply

	glViewport(vp.x(), vp.y(), vp.width(), vp.height());
	glDepthRange(vp.minDepth(), vp.maxDepth());

	_activeViewport = vp;
}

const Viewport& GLGraphicsDevice::getViewport() const {
	return _activeViewport;
}

std::shared_ptr<IShader> GLGraphicsDevice::createShader() {
	if( !_isValid ) {
		return nullptr;
	}

	std::shared_ptr<GLShader> shader = std::make_shared<GLShader>();
	return shader;
}

std::shared_ptr<IVertexBuffer> GLGraphicsDevice::createVertexBuffer() {
	if( !_isValid ) {
		return nullptr;
	}
	std::shared_ptr<GLVertexBuffer> buffer = std::make_shared<GLVertexBuffer>();
	return buffer;
}

std::shared_ptr<IIndexBuffer> GLGraphicsDevice::createIndexBuffer() {
	if( !_isValid ) {
		return nullptr;
	}

	std::shared_ptr<GLIndexBuffer> buffer = std::make_shared<GLIndexBuffer>();
	return buffer;
}

std::shared_ptr<IConstantBuffer> GLGraphicsDevice::createConstantBuffer() {
	if( !_isValid ) {
		return nullptr;
	}

	// note: using a hardcoded index means they cannot be removed.
	// todo: implement a better system that allows for reuse of deleted indices
	//       such as some kind of lookup table to see if a buffer is dead upon request.
	//       e.g. .....(getNextFreeConstantBufferIndex())...
	std::shared_ptr<GLConstantBuffer> buffer = std::make_shared<GLConstantBuffer>(_constantBufferCount);
	_constantBufferCount += 1;
	return buffer;
}

std::shared_ptr<ITexture2D> GLGraphicsDevice::createTexture2D( int width, int height, TextureFormat::Format format, int flags, void* pixels ) {
	if( !_isValid ) {
		return nullptr;
	}

	if( width <= 0 || height <= 0 ) {
		return nullptr;
	}

	std::shared_ptr<GLTexture2D> glTexture = std::make_shared<GLTexture2D>(flags);
	if( failed(glTexture->setData(0, 0, width, height, pixels, format)) ) {
		glTexture.reset();
		glTexture = nullptr;
		return nullptr;
	}

	return glTexture;
}

std::shared_ptr<ITexture3D> GLGraphicsDevice::createTexture3D( int width, int height, int depth, TextureFormat::Format format, int flags, void* pixels ) {
	if( !_isValid ) {
		return nullptr;
	}

	if( width <= 0 || height <= 0 || depth <= 0 ) {
		return nullptr;
	}

	std::shared_ptr<GLTexture3D> glTexture = std::make_shared<GLTexture3D>(flags);
	if( failed(glTexture->setData(width, height, depth, pixels, format)) ) {
		glTexture.reset();
		glTexture = nullptr;
		return nullptr;
	}

	return glTexture;
}

std::shared_ptr<ITextureCube> GLGraphicsDevice::createTextureCube( int width, int height, void* posx, void* negx, void* posy, void* negy, void* posz, void* negz ) {
	if( width <= 0 || height <= 0 ) {
		return nullptr;
	}

	if( nullptr==posx || nullptr==negx || nullptr==posy || nullptr==negy || nullptr==posz || nullptr==negz ) {
		return nullptr;
	}

	std::shared_ptr<GLTextureCube> glCube = std::make_shared<GLTextureCube>();
	if( failed(glCube->set(width, height, posx, negx, posy, negy, posz, negz)) ) {
		glCube.reset();
		glCube = nullptr;
		return nullptr;
	}

	return glCube;
}

std::shared_ptr<ISamplerState> GLGraphicsDevice::createSamplerState( const SamplerDesc& desc ) {
	if( !_isValid ) {
		return nullptr;
	}

	std::shared_ptr<GLSamplerState> glSampler = std::make_shared<GLSamplerState>();
	if( !glSampler->create(desc) ) {
		glSampler.reset();
		glSampler = nullptr;
		return nullptr;
	}
	return glSampler;
}

std::shared_ptr<IRenderTarget2D> GLGraphicsDevice::createRenderTarget2D( int width, int height, TextureFormat::Format format, DepthStencilFormat depthFormat ) {
	if( !_isValid ) {
		return nullptr;
	}

	std::shared_ptr<GLTexture2D> texture = std::static_pointer_cast<GLTexture2D>(this->createTexture2D(width, height, format, TextureFlags::RenderTarget, nullptr));
	if( nullptr == texture ) {
		return nullptr;
	}
	std::shared_ptr<GLTexture2D> depthTexture = (DepthStencilFormat::None==depthFormat) ? nullptr : std::static_pointer_cast<GLTexture2D>(this->createTexture2D(width, height, TextureFormat::fromDepthStencilFormat(depthFormat), TextureFlags::RenderTarget, nullptr));
	//if( nullptr == depthTexture ) { // todo: only run this check if trying to make the texture
		//return nullptr;
	//}
	std::shared_ptr<GLRenderTarget2D> glTarget = std::make_shared<GLRenderTarget2D>();
	if( !glTarget->create(texture, depthTexture) ) {
		texture.reset();
		return nullptr;
	}
	return glTarget;
}

std::shared_ptr<IRasterizerState> GLGraphicsDevice::createRasterizerState( const RasterizerDesc& desc ) {
	if( !_isValid ) {
		return nullptr;
	}

	std::shared_ptr<GLRasterizerState> glRaster = std::make_shared<GLRasterizerState>();
	if( !glRaster->create(desc) ) {
		glRaster.reset();
		glRaster = nullptr;
		return nullptr;
	}
	return glRaster;
}

std::shared_ptr<IDepthStencilState> GLGraphicsDevice::createDepthStencilState( const DepthStencilDesc& desc ) {
	if( !_isValid ) {
		return nullptr;
	}

	std::shared_ptr<GLDepthStencilState> glState = std::make_shared<GLDepthStencilState>();
	if( !glState->create(desc) ) {
		glState.reset();
		glState = nullptr;
		return nullptr;
	}
	return glState;
}

std::shared_ptr<IBlendState> GLGraphicsDevice::createBlendState( const BlendDesc& desc ) {
	if( !_isValid ) {
		return nullptr;
	}

	std::shared_ptr<GLBlendState> glState = std::make_shared<GLBlendState>();
	if( !glState->create(desc) ) {
		glState.reset();
		glState = nullptr;
		return nullptr;
	}
	return glState;
}

void GLGraphicsDevice::applyShader( const std::shared_ptr<IShader>& shader ) {
	if( !_isValid ) {
		return;
	}

	if( nullptr == shader ) {
		glUseProgram(0);
		_activeShader.reset();
		return;
	}

	if( !shader->isValid() ) {
		_activeShader.reset();
		return;
	}

	const std::shared_ptr<GLShader> glShader = std::static_pointer_cast<GLShader>(shader);
	glUseProgram(glShader->getProgram());
	_activeShader = glShader;
}

void GLGraphicsDevice::setVertexBuffer( const std::shared_ptr<IVertexBuffer>& buffer ) {
	if( !_isValid ) {
		return;
	}

	// todo: see if there's a way to have the vertex attribute values stores separately from the buffers themselves akin
	//       to directx's input layouts.  maybe through an extension or something core to 4.2+ ?

	// gl needs a bound vertex buffer in order to set vertex attrib pointers, therefore we need a valid shader bound.
	// i want to change this because it means you can't set a vertex buffer before setting a shader, which is odd...
	if( _activeShader.expired() ) {
		return;
	}

	if( nullptr == buffer ) {
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		return;
	}

	const std::shared_ptr<GLVertexBuffer> glBuffer = std::static_pointer_cast<GLVertexBuffer>(buffer);
	const GLuint vbo = glBuffer->getVbo();
	if( 0 == vbo ) {
		return;
	}
	glBindBuffer(GL_ARRAY_BUFFER, vbo);

	// apply vertex attribute pointers based on the shader's vertex declaration
	int offset = 0;
	const std::vector<VertexElement>& elements = _activeShader.lock()->getVertexDeclaration().getElements();
	for( unsigned int i = 0; i < elements.size(); ++i ) {
		const VertexElement& currElement = elements[i];

		GLenum type;
		switch( currElement.getFormat() ) {
			case VertexFormat::Float:
			case VertexFormat::Float2:
			case VertexFormat::Float3:
			case VertexFormat::Float4: {
				type = GL_FLOAT;
			}
		}

		glEnableVertexAttribArray(i);
		glVertexAttribPointer(i, currElement.getMultiplicity(), type, GL_FALSE, _activeShader.lock()->getVertexDeclaration().getStride(), (const void*)offset);

		offset += currElement.getSize(); // sizeof(datatype) * numberOfThem;
	}

	_activeVertexBuffer = glBuffer;
}

void GLGraphicsDevice::setIndexBuffer( const std::shared_ptr<IIndexBuffer>& buffer ) {
	if( !_isValid ) {
		return;
	}

	if( nullptr == buffer ) {
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
		return;
	}

	const std::shared_ptr<GLIndexBuffer> glBuffer = std::static_pointer_cast<GLIndexBuffer>(buffer);
	const GLuint evbo = glBuffer->getEvbo();
	if( 0 == evbo ) {
		//_activeIndexBuffer.reset();
		return; // todo: error
	}
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, evbo);

	_activeIndexBuffer = glBuffer;
}

void GLGraphicsDevice::setTexture2D( int index, const std::shared_ptr<ITexture2D>& texture, ShaderStage::Stage shaderStage ) {
	if( !_isValid ) {
		return;
	}

	if( index < 0 ) {
		return;
	}

	const std::shared_ptr<GLTexture2D> glTexture = std::static_pointer_cast<GLTexture2D>(texture);
	glActiveTexture(GL_TEXTURE0 + index);
	glBindTexture(GL_TEXTURE_2D, (texture != nullptr) ? glTexture->getTextureId() : 0);
}

void GLGraphicsDevice::setTexture3D( int index, const std::shared_ptr<ITexture3D>& texture, ShaderStage::Stage shaderStage ) {
	if( !_isValid ) {
		return;
	}

	if( index < 0 ) {
		return;
	}

	const std::shared_ptr<GLTexture3D> glTexture = std::static_pointer_cast<GLTexture3D>(texture);
	glActiveTexture(GL_TEXTURE0 + index);
	glBindTexture(GL_TEXTURE_3D, (texture != nullptr) ? glTexture->getTextureId() : 0);
}

void GLGraphicsDevice::setTextureCube( int index, const std::shared_ptr<ITextureCube>& texture, ShaderStage::Stage shaderStage ) {
	if( !_isValid ) {
		return;
	}

	const std::shared_ptr<GLTextureCube> glTexture = std::static_pointer_cast<GLTextureCube>(texture);
	glActiveTexture(GL_TEXTURE0 + index);
	glBindTexture(GL_TEXTURE_CUBE_MAP, (glTexture != nullptr) ? glTexture->getTextureId() : 0);
}

void GLGraphicsDevice::setSamplerState( int index, const std::shared_ptr<ISamplerState>& state, ShaderStage::Stage shaderStage ) {
	if( !_isValid ) {
		return;
	}

	const std::shared_ptr<GLSamplerState> glSampler = std::static_pointer_cast<GLSamplerState>(state);
	glBindSampler(index, (state != nullptr) ? glSampler->getSamplerId() : 0);
}

void GLGraphicsDevice::setBlendState( const std::shared_ptr<IBlendState>& state ) {
	if( !_isValid ) {
		return;
	}

	if( nullptr == state ) {
		restoreDefaultBlendState();
		return;
	}

	const std::shared_ptr<GLBlendState> glState = std::static_pointer_cast<GLBlendState>(state);
	const BlendDesc desc = glState->getDesc();

	// enable blending
	if( desc.blendingEnabled() ) {
		glEnable(GL_BLEND);
	} else {
		glDisable(GL_BLEND);
	}

	// blend color
	glBlendColor(desc.blendFactor[0], desc.blendFactor[1], desc.blendFactor[2], desc.blendFactor[3]);

	// blend equations
	glBlendEquationSeparate(ciriToGlBlendFunction(desc.colorFunc), ciriToGlBlendFunction(desc.alphaFunc));

	// blend functions
	glBlendFuncSeparate(ciriToGlBlendMode(desc.srcColorBlend, false), ciriToGlBlendMode(desc.dstColorBlend, false), ciriToGlBlendMode(desc.srcAlphaBlend, true), ciriToGlBlendMode(desc.dstAlphaBlend, true));

	// color write mask
	const GLboolean redMask   = (desc.colorMask & static_cast<int>(BlendColorMask::Red)) != 0;
	const GLboolean greenMask = (desc.colorMask & static_cast<int>(BlendColorMask::Green)) != 0;
	const GLboolean blueMask  = (desc.colorMask & static_cast<int>(BlendColorMask::Blue)) != 0;
	const GLboolean alphaMask = (desc.colorMask & static_cast<int>(BlendColorMask::Alpha)) != 0;
	glColorMask(redMask, greenMask, blueMask, alphaMask);
}

void GLGraphicsDevice::drawArrays( PrimitiveTopology topology, int vertexCount, int startIndex ) {
	if( !_isValid ) {
		return;
	}

	// cannot draw with no active shader
	if( _activeShader.expired() ) {
		return;
	}

	// cannot draw with no active vertex buffer
	if( _activeVertexBuffer.expired() ) {
		return;
	}

	// vertex count must be greater than 0!
	if( vertexCount <= 0 ) {
		return;
	}

	// start index must be greater than zero and less than vertex count
	//if( startIndex < 0 || startIndex >= vertexCount ) {
	//	return;
	//}

	glDrawArrays(ciriToGlTopology(topology), startIndex, vertexCount);
}

void GLGraphicsDevice::drawIndexed( PrimitiveTopology topology, int indexCount ) {
	if( !_isValid ) {
		return;
	}

	// cannot draw with no active shader
	if( _activeShader.expired() ) {
		return;
	}

	// cannot draw without a valid vertex and index buffer
	if( _activeVertexBuffer.expired() || _activeIndexBuffer.expired() ) {
		return;
	}

	// index count must be greater than 0
	if( indexCount <= 0 ) {
		return; // todo: error
	}

	glDrawElements(ciriToGlTopology(topology), indexCount, GL_UNSIGNED_INT, 0);
}

void GLGraphicsDevice::setRenderTargets( IRenderTarget2D** renderTargets, int numRenderTargets ) {
	if( !_isValid ) {
		return;
	}

	// create and bind a framebuffer
	if( 0 == _currentFbo ) { glGenFramebuffers(1, &_currentFbo); }
	glBindFramebuffer(GL_FRAMEBUFFER, _currentFbo);

	// attach all render target textures incl. first occurrence of a depth stencil
	bool isDepthStencilBound = false;
	for( int i = 0; i < numRenderTargets; ++i ) {
		const std::shared_ptr<GLTexture2D>& texture = std::static_pointer_cast<GLTexture2D>(renderTargets[i]->getTexture());
		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, texture->getTextureId(), 0);

		if( !isDepthStencilBound && renderTargets[i]->getDepth() != nullptr ) {
			isDepthStencilBound = true;
			const auto glDepth = std::static_pointer_cast<GLTexture2D>(renderTargets[i]->getDepth());
			const GLenum DepthAttachmentType = TextureFormat::hasStencil(glDepth->getFormat()) ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT;
			glFramebufferTexture2D(GL_FRAMEBUFFER, DepthAttachmentType , GL_TEXTURE_2D, glDepth->getTextureId(), 0);
		}
	}

	// configure draw buffers
	glDrawBuffers(numRenderTargets, _drawBuffers);

	// set viewport (use 0's size)
	setViewport(Viewport(0, 0, renderTargets[0]->getTexture()->getWidth(), renderTargets[0]->getTexture()->getHeight()));
}

void GLGraphicsDevice::restoreDefaultRenderTargets() {
	if( !_isValid ) {
		return;
	}

	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	setViewport(Viewport(0, 0, _defaultWidth, _defaultHeight));
}

ErrorCode GLGraphicsDevice::resize() {
	if( !_isValid ) {
		return ErrorCode::CIRI_UNKNOWN_ERROR;
	}

	// todo: check for erroneous sizes

	// get new window size
	const int width = _window->getWidth();
	const int height = _window->getHeight();

	// don't resize if the same size
	if( width == _defaultWidth && height == _defaultHeight ) {
		return ErrorCode::CIRI_OK; // not incorrect; just ignore it
	}

	// update default width and height
	_defaultWidth = width;
	_defaultHeight = height;

	// bind backbuffer and resize the viewport
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	setViewport(Viewport(0, 0, _defaultWidth, _defaultHeight));

	return ErrorCode::CIRI_OK;
}

ErrorCode GLGraphicsDevice::resizeTexture2D( const std::shared_ptr<ITexture2D>& texture, int width, int height ) {
	if( !_isValid ) {
		return ErrorCode::CIRI_UNKNOWN_ERROR;
	}

	if( width <= 0 || height <= 0 || nullptr == texture ) {
		return ErrorCode::CIRI_INVALID_ARGUMENT;
	}

	const std::shared_ptr<GLTexture2D> glTexture = std::static_pointer_cast<GLTexture2D>(texture);

	// check for texture that isn't created
	if( 0 == glTexture->getTextureId() ) {
		return ErrorCode::CIRI_UNKNOWN_ERROR;
	}

	glTexture->destroy();
	return glTexture->setData(0, 0, width, height, nullptr, glTexture->getFormat());
}

ErrorCode GLGraphicsDevice::resizeRenderTarget2D( const std::shared_ptr<IRenderTarget2D>& target, int width, int height ) {
	if( !_isValid ) {
		return ErrorCode::CIRI_UNKNOWN_ERROR;
	}

	if( width <= 0 || height <= 0 || nullptr == target ) {
		return ErrorCode::CIRI_INVALID_ARGUMENT;
	}

	const std::shared_ptr<GLRenderTarget2D> glTarget = std::static_pointer_cast<GLRenderTarget2D>(target);

	// check for texture that isn't created
	if( nullptr == glTarget->getTexture() ) {
		return ErrorCode::CIRI_UNKNOWN_ERROR;
	}

	// store texture's format for re-creation
	const TextureFormat::Format textureFormat = glTarget->getTexture()->getFormat();

	glTarget->destroy();
	const std::shared_ptr<GLTexture2D> glTexture = std::static_pointer_cast<GLTexture2D>(createTexture2D(width, height, textureFormat, TextureFlags::RenderTarget, nullptr));
	if( nullptr == glTexture ) {
		return ErrorCode::CIRI_UNKNOWN_ERROR;
	}
	const std::shared_ptr<GLTexture2D> glDepth = nullptr; // todo
	return glTarget->create(glTexture, glDepth) ? ErrorCode::CIRI_OK : ErrorCode::CIRI_UNKNOWN_ERROR;
}

void GLGraphicsDevice::setClearColor( float r, float g, float b, float a ) {
	if( !_isValid ) {
		return;
	}

	glClearColor(r, g, b, a);
}

void GLGraphicsDevice::setClearDepth( float depth ) {
	if( !_isValid ) {
		return;
	}
	glClearDepth(depth);
}

void GLGraphicsDevice::setClearStencil( int stencil ) {
	if( !_isValid ) {
		return;
	}
	glClearStencil(stencil);
}

void GLGraphicsDevice::clear( int flags ) {
	if( !_isValid ) {
		return;
	}

	GLbitfield clearFlags = 0;
	if( flags & ClearFlags::Color ) {
		clearFlags |= GL_COLOR_BUFFER_BIT;
	}
	if( flags & ClearFlags::Depth ) {
		clearFlags |= GL_DEPTH_BUFFER_BIT;
	}
	if( flags & ClearFlags::Stencil ) {
		clearFlags |= GL_STENCIL_BUFFER_BIT;
	}
	glClear(clearFlags);
}

void GLGraphicsDevice::setRasterizerState( const std::shared_ptr<IRasterizerState>& state ) {
	if( !_isValid ) {
		return;
	}

	if( nullptr == state ) {
		restoreDefaultRasterizerState();
		return;
	}

	const std::shared_ptr<GLRasterizerState> glRaster = std::static_pointer_cast<GLRasterizerState>(state);
	if( !_activeRasterizerState.expired() && (glRaster == _activeRasterizerState.lock()) ) {
		return;
	}
	_activeRasterizerState = glRaster;
	const RasterizerDesc& desc = glRaster->getDesc();

	// cull mode
	if( CullMode::None == desc.cullMode ) {
		glDisable(GL_CULL_FACE);
	} else {
		glEnable(GL_CULL_FACE);
		glCullFace(GL_BACK);
		if( CullMode::Clockwise == desc.cullMode ) {
			glFrontFace(GL_CCW);
		} else {
			glFrontFace(GL_CW);
		}
	}
	// fill mode
	if( FillMode::Solid == desc.fillMode ) {
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	} else {
		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	}
	// scissor test
	if( desc.scissorTestEnable ) {
		glEnable(GL_SCISSOR_TEST);
	} else {
		glDisable(GL_SCISSOR_TEST);
	}
	// depth bias and slope scale depth bioas
	if( desc.depthBias != 0.0f || desc.slopeScaleDepthBias != 0.0f ) {
		glEnable(GL_POLYGON_OFFSET_FILL);
		glPolygonOffset(desc.slopeScaleDepthBias, desc.depthBias);
	} else {
		glDisable(GL_POLYGON_OFFSET_FILL);
	}
	// todo: only if depth clamping is supported (how?)
	// depth clipping
	if( desc.depthClipEnable ) { // inverted??
		glEnable(GL_DEPTH_CLAMP);
	} else {
		glDisable(GL_DEPTH_CLAMP);
	}
	// todo: msaa
}

void GLGraphicsDevice::setDepthStencilState( const std::shared_ptr<IDepthStencilState>& state ) {
	if( !_isValid ) {
		return;
	}

	if( nullptr == state ) {
		restoreDefaultDepthStencilState();
		return;
	}

	const std::shared_ptr<GLDepthStencilState> glState = std::static_pointer_cast<GLDepthStencilState>(state);
	if( !_activeDepthStencilState.expired() && (glState == _activeDepthStencilState.lock()) ) {
		return;
	}
	_activeDepthStencilState = glState;
	const DepthStencilDesc& desc = glState->getDesc();

	// enable depth
	if( desc.depthEnable ) {
		glEnable(GL_DEPTH_TEST);
	} else {
		glDisable(GL_DEPTH_TEST);
	}

	// depth func
	glDepthFunc(ciriToGlComparisonFunc(desc.depthFunc));

	// depth write
	glDepthMask(desc.depthWriteMask);

	// enable stencil
	if( desc.stencilEnable ) {
		glEnable(GL_STENCIL_TEST);
	} else {
		glDisable(GL_STENCIL_TEST);
	}

	// stencil funcs and ops
	if( desc.twoSidedStencil ) {
		glStencilFuncSeparate(GL_FRONT, ciriToGlComparisonFunc(desc.frontStencilFunc), desc.stencilRef, desc.stencilReadMask);
		glStencilFuncSeparate(GL_BACK, ciriToGlComparisonFunc(desc.backStencilFunc), desc.stencilRef, desc.stencilReadMask);
		glStencilOpSeparate(GL_FRONT, ciriToGlStencilOp(desc.frontStencilFailOp), ciriToGlStencilOp(desc.frontStencilDepthFailOp), ciriToGlStencilOp(desc.frontStencilPassOp));
		glStencilOpSeparate(GL_BACK, ciriToGlStencilOp(desc.backStencilFailOp), ciriToGlStencilOp(desc.backStencilDepthFailOp), ciriToGlStencilOp(desc.backStencilPassOp));
	} else {
		glStencilFunc(ciriToGlComparisonFunc(desc.frontStencilFunc), desc.stencilRef, desc.stencilReadMask);
		glStencilOp(ciriToGlStencilOp(desc.frontStencilFailOp), ciriToGlStencilOp(desc.frontStencilDepthFailOp), ciriToGlStencilOp(desc.frontStencilPassOp));
	}

	// stencil write mask
	glStencilMask(desc.stencilWriteMask);
}

void GLGraphicsDevice::setShaderExt( const char* ext ) {
	_shaderExt = ext;
}

const char* GLGraphicsDevice::getShaderExt() const {
	return _shaderExt.c_str();
}

std::shared_ptr<IWindow> GLGraphicsDevice::getWindow() const {
	return _window;
}

const char* GLGraphicsDevice::getGpuName() const {
	return _gpuName.c_str();
}

const char* GLGraphicsDevice::getApiInfo() const {
	return _apiInfo.c_str();
}

GraphicsApiType GLGraphicsDevice::getApiType() const {
	return GraphicsApiType::OpenGL;
}

ErrorCode GLGraphicsDevice::restoreDefaultStates() {
	// restore blend state
	ErrorCode status = restoreDefaultBlendState();
	if( failed(status) ) {
		return status;
	}
	// restore rasterizer state
	status = restoreDefaultRasterizerState();
	if( failed(status) ) {
		return status;
	}
	// restore depth stencil state
	status = restoreDefaultDepthStencilState();
	if( failed(status) ) {
		return status;
	}
	return ErrorCode::CIRI_OK;
}

ErrorCode GLGraphicsDevice::restoreDefaultBlendState() {
	setBlendState(getDefaultBlendOpaque());
	return ErrorCode::CIRI_OK;
}

ErrorCode GLGraphicsDevice::restoreDefaultRasterizerState() {
	setRasterizerState(getDefaultRasterCounterClockwise());
	return ErrorCode::CIRI_OK;
}

ErrorCode GLGraphicsDevice::restoreDefaultDepthStencilState() {
	setDepthStencilState(getDefaultDepthStencilDefault());
	return ErrorCode::CIRI_OK;
}

std::shared_ptr<IBlendState> GLGraphicsDevice::getDefaultBlendAdditive() {
	if( nullptr == _defaultBlendAdditive ) {
		BlendDesc desc;
		desc.srcColorBlend = BlendMode::SourceAlpha;
		desc.srcAlphaBlend = BlendMode::SourceAlpha;
		desc.dstColorBlend = BlendMode::One;
		desc.dstAlphaBlend = BlendMode::One;
		_defaultBlendAdditive = createBlendState(desc);
	}
	return _defaultBlendAdditive;
}

std::shared_ptr<IBlendState> GLGraphicsDevice::getDefaultBlendAlpha() {
	if( nullptr == _defaultBlendAlpha ) {
		BlendDesc desc;
		desc.srcColorBlend = BlendMode::One;
		desc.srcAlphaBlend = BlendMode::One;
		desc.dstColorBlend = BlendMode::InverseSourceAlpha;
		desc.dstAlphaBlend = BlendMode::InverseSourceAlpha;
		_defaultBlendAlpha = createBlendState(desc);
	}
	return _defaultBlendAlpha;
}

std::shared_ptr<IBlendState> GLGraphicsDevice::getDefaultBlendNonPremul() {
	if( nullptr == _defaultBlendNonPremul ) {
		BlendDesc desc;
		desc.srcColorBlend = BlendMode::SourceAlpha;
		desc.srcAlphaBlend = BlendMode::SourceAlpha;
		desc.dstColorBlend = BlendMode::InverseSourceAlpha;
		desc.dstAlphaBlend = BlendMode::InverseSourceAlpha;
		_defaultBlendNonPremul = createBlendState(desc);
	}
	return _defaultBlendNonPremul;
}

std::shared_ptr<IBlendState> GLGraphicsDevice::getDefaultBlendOpaque() {
	if( nullptr == _defaultBlendOpaque ) {
		BlendDesc desc;
		desc.srcColorBlend = BlendMode::One;
		desc.srcAlphaBlend = BlendMode::One;
		desc.dstColorBlend = BlendMode::Zero;
		desc.dstAlphaBlend = BlendMode::Zero;
		_defaultBlendOpaque = createBlendState(desc);
	}
	return _defaultBlendOpaque;
}

std::shared_ptr<IRasterizerState> GLGraphicsDevice::getDefaultRasterNone() {
	if( nullptr == _defaultRasterNone ) {
		RasterizerDesc desc;
		desc.cullMode = CullMode::None;
		_defaultRasterNone = createRasterizerState(desc);
	}
	return _defaultRasterNone;
}

std::shared_ptr<IRasterizerState> GLGraphicsDevice::getDefaultRasterClockwise() {
	if( nullptr == _defaultRasterClockwise ) {
		RasterizerDesc desc;
		desc.cullMode = CullMode::Clockwise;
		_defaultRasterClockwise = createRasterizerState(desc);
	}
	return _defaultRasterClockwise;
}

std::shared_ptr<IRasterizerState> GLGraphicsDevice::getDefaultRasterCounterClockwise() {
	if( nullptr == _defaultRasterCounterClockwise ){
		RasterizerDesc desc;
		desc.cullMode = CullMode::CounterClockwise;
		_defaultRasterCounterClockwise = createRasterizerState(desc);
	}
	return _defaultRasterCounterClockwise;
}

std::shared_ptr<IDepthStencilState> GLGraphicsDevice::getDefaultDepthStencilDefault() {
	if( nullptr == _defaultDepthStencilDefault ) {
		DepthStencilDesc desc;
		desc.depthEnable = true;
		desc.depthWriteMask = true;
		_defaultDepthStencilDefault = createDepthStencilState(desc);
	}
	return _defaultDepthStencilDefault;
}

std::shared_ptr<IDepthStencilState> GLGraphicsDevice::getDefaultDepthStencilDepthRead() {
	if( nullptr == _defaultDepthStencilDepthRead ) {
		DepthStencilDesc desc;
		desc.depthEnable = true;
		desc.depthWriteMask = false;
		_defaultDepthStencilDepthRead = createDepthStencilState(desc);
	}
	return _defaultDepthStencilDepthRead;
}

std::shared_ptr<IDepthStencilState> GLGraphicsDevice::getDefaultDepthStencilNone() {
	if( nullptr == _defaultDepthStencilNone ) {
		DepthStencilDesc desc;
		desc.depthEnable = false;
		desc.depthWriteMask = false;
		_defaultDepthStencilNone = createDepthStencilState(desc);
	}
	return _defaultDepthStencilNone;
}

bool GLGraphicsDevice::configureGl( HWND hwnd ) {
	// get the window's device context
	_hdc = GetDC(hwnd);

	// choose the pixel format
	const int pixelFormatAttribs[] = {
		WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
		WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
		WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
		WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
		WGL_COLOR_BITS_ARB, 32,
		WGL_DEPTH_BITS_ARB, 24,
		WGL_STENCIL_BITS_ARB, 8,
		WGL_SAMPLE_BUFFERS_ARB, 1,
		WGL_SAMPLES_ARB, 1,
		0
	};
	int pixelFormat;
	UINT numPixelFormats;
	if( !wglChoosePixelFormatARB(_hdc, pixelFormatAttribs, NULL, 1, &pixelFormat, &numPixelFormats) ) {
		return false;
	}

	// set the pixel format (pfd is redundant
	PIXELFORMATDESCRIPTOR pfd;
	memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
	if( !SetPixelFormat(_hdc, pixelFormat, &pfd) ) {
		return false;
	}

	// create the newer opengl context
	int contextFlags = 0;// WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
	#ifdef _DEBUG
		contextFlags |= WGL_CONTEXT_DEBUG_BIT_ARB;
	#endif
	const int contextAttribs[] = {
		WGL_CONTEXT_MAJOR_VERSION_ARB, 4, // need 4.2 for shader uniform location binding
		WGL_CONTEXT_MINOR_VERSION_ARB, 2,
		WGL_CONTEXT_FLAGS_ARB, contextFlags,
		WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
		//WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, // not using VAOs; core requires?
		0
	};
	_hglrc = wglCreateContextAttribsARB(_hdc, NULL, contextAttribs);
	if( !_hglrc ) {
		return false;
	}

	// make the new context current
	if( !wglMakeCurrent(_hdc, _hglrc) ) {
		return false;
	}

	// configure opengl debug output
	#ifdef _DEBUG
	if( glDebugMessageCallback != NULL ) {
		glDebugMessageCallback(debugContextCb, this);
	}
	if( glDebugMessageCallbackARB != NULL ) {
		glDebugMessageCallbackARB(debugContextCb, this);
	}
	if( glDebugMessageCallbackAMD != NULL ) {
		glDebugMessageCallbackAMD(debugContextAmdCb, this);
	}
	#endif

	// get gpu information
	const std::string vendor = reinterpret_cast<const char*>(glGetString(GL_VENDOR));
	const std::string renderer = reinterpret_cast<const char*>(glGetString(GL_RENDERER));
	_gpuName = vendor + " " + renderer;
	const std::string glVersion = reinterpret_cast<const char*>(glGetString(GL_VERSION));
	const std::string glslVersion = reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION));
	_apiInfo = "OpenGL " + glVersion + "; GLSL " + glslVersion;

	// default clear color
	glClearColor(0.39f, 0.58f, 0.93f, 1.0f);
	// default clear values
	glClearDepth(1.0f);
	glClearStencil(0);

	// *cough*
	// gimmie dat dank core profile (temp hack, unless it works)
	// *cough*
	glGenVertexArrays(1, &_dummyVao);
	glBindVertexArray(_dummyVao);

	return true;
}

// i shit you the fuck not, we even need a fake wndproc because of the SetPixelFormat thing mentioned below...
static LRESULT WINAPI FakeWndProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam ) {
	return DefWindowProc(hwnd, msg, wparam, lparam);
}

bool GLGraphicsDevice::configureGlew() {
	// note: because Microsoft APIs are so nice to work with, we must create a fake window to initialize a fake GL context and GLEW because you can't set the pixel format more than once

	// create a dummy window
	const char* className = "CIRI_DUMMY";

	// create a dummy window
	WNDCLASSEX wc;
	wc.cbSize = sizeof(WNDCLASSEX);
	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc = (WNDPROC)FakeWndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = GetModuleHandle(NULL);
	wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
	wc.hIconSm = wc.hIcon;
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
	wc.lpszMenuName = NULL;
	wc.lpszClassName = className;
	if( !RegisterClassEx(&wc) ) {
		return false;
	}
	HINSTANCE inst = GetModuleHandle(NULL);
	HWND hwnd = CreateWindow(className, className, WS_OVERLAPPEDWINDOW, 0, 0, CW_USEDEFAULT, CW_DEFAULT, NULL, NULL, GetModuleHandle(NULL), NULL);

	// get window's HDC
	HDC hdc = GetDC(hwnd);

	// choose a pixel format
	PIXELFORMATDESCRIPTOR pfd;
	memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
	pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
	pfd.nVersion = 1;
	pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
	pfd.iPixelType = PFD_TYPE_RGBA;
	pfd.cColorBits = 32;
	pfd.cDepthBits = 24;
	pfd.cStencilBits = 8;
	pfd.iLayerType = PFD_MAIN_PLANE;
	const int pixelFormat = ChoosePixelFormat(hdc, &pfd);
	if( 0 == pixelFormat ) {
		DestroyWindow(hwnd);
		return false;
	}
	if( !SetPixelFormat(hdc, pixelFormat, &pfd) ) {
		return false;
	}

	// create an opengl 2.1 or older context
	HGLRC fakeHglrc = wglCreateContext(hdc);
	if( !fakeHglrc ) {
		DestroyWindow(hwnd);
		return false;
	}
	if( !wglMakeCurrent(hdc, fakeHglrc) ) {
		DestroyWindow(hwnd);
		return false;
	}

	// initialize GLEW
	if( glewInit() != GLEW_OK ) {
		DestroyWindow(hwnd);
		return false;
	}

	// delete the fake context and window
	wglMakeCurrent(NULL, NULL);
	wglDeleteContext(fakeHglrc);
	DeleteDC(hdc);
	DestroyWindow(hwnd);

	return true;
}

void APIENTRY GLGraphicsDevice::debugContextCb( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam ) {
	if( GL_DEBUG_SEVERITY_NOTIFICATION == severity ) {
		return;
	}

	std::stringstream ss;
	switch( severity ) {
		case GL_DEBUG_SEVERITY_HIGH: {
			ss << "OpenGL Error (HIGH): ";
			break;
		}
		case GL_DEBUG_SEVERITY_MEDIUM: {
			ss << "OpenGL Error (MEDIUM): ";
			break;
		}
		case GL_DEBUG_SEVERITY_LOW: {
			ss << "OpenGL Error (LOW): ";
			break;
		}
		case GL_DEBUG_SEVERITY_NOTIFICATION: {
			ss << "OpenGL Notification: ";
			break;
		}
		default: {
			break;
		}
	}
	ss << message << "\n";
	OutputDebugString(ss.str().c_str());
	printf(ss.str().c_str());
}

void APIENTRY GLGraphicsDevice::debugContextAmdCb( GLuint id, GLenum category, GLenum severity, GLsizei length, const GLchar* message, void* userParam ) {
	std::stringstream ss;
	switch( severity ) {
		case GL_DEBUG_SEVERITY_HIGH_AMD: {
				ss << "OpenGL Error (HIGH): ";
			break;
		}
		case GL_DEBUG_SEVERITY_MEDIUM_AMD: {
				ss << "OpenGL Error (MEDIUM): ";
			break;
		}
		case GL_DEBUG_SEVERITY_LOW_AMD: {
				ss << "OpenGL Error (LOW): ";
			break;
		}
		case GL_DEBUG_SEVERITY_NOTIFICATION: {
				ss << "OpenGL Notification: ";
			break;
		}
		default: {
			break;
		}
	}
	ss << message << "\n";
	OutputDebugString(ss.str().c_str());
	printf(ss.str().c_str());
}

//void GLGraphicsDevice::restoreDefaultBlendState() {
//	if( !_isValid ) {
//		return;
//	}

//	// disable blending
//	glDisable(GL_BLEND);
//	// blend color (http://docs.gl/gl4/glBlendColor)
//	glBlendColor(0.0f, 0.0f, 0.0f, 0.0f);
//	// blend equations (http://docs.gl/gl4/glBlendEquationSeparate)
//	glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
//	// blend functions (http://docs.gl/gl4/glBlendFuncSeparate)
//	glBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_ZERO);
//	// color write mask (http://docs.gl/gl4/glColorMask)
//	glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
//}

namespace ciri {
std::shared_ptr<IGraphicsDevice> createGraphicsDevice() {
	return std::shared_ptr<IGraphicsDevice>(new GLGraphicsDevice());
}
}


text:
CREATE USER 'blackuser'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

GRANT SELECT ,
INSERT ,
UPDATE ,
DELETE ,
USAGE  ,
LOCK TABLES ON `rbl` . * TO 'blackuser'@'localhost';

ALTER USER 'blackuser'@'localhost' WITH MAX_QUERIES_PER_HOUR 0  MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: Leetcode 255
category: 算法
tags: 算法
keywords: 算法,排序,Sort,Algorithm
---

### Leetcode 255. Verify Preorder Sequence in Binary Search Tree

- 知识点复习
  - 前序遍历:根节点->左子树->右子树
  - 中序遍历:左子树->根节点->右子树
  - 后序遍历:左子树->右子树->根节点

- Question Describe:
  - Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.
  - You may assume each number in the sequence is unique.

- Idea to Solve This Problem:
  - Preorder Definition: root, left, right
  - The key to this problem is the "last_pop"

```java
  public boolean verifyPreorder(int[] preorder) {
      if(preorder.length==0) return true;
      int last_pop = Integer.MIN_VALUE;
      boolean result =true;
      Stack<Integer> stack =new Stack<Integer>();
      for(int i=0;i<preorder.length;i++){
            if(stack.isEmpty()){
                    stack.push(preorder[i]);
                  }
            else if(!stack.isEmpty() && preorder[i] < stack.peek()){
                    if(preorder[i] < last_pop){
                              result = false;
                            }
                    stack.push(preorder[i]);
                  }
            else if(!stack.isEmpty() && preorder[i] > stack.peek()){
                    while(!stack.isEmpty() && stack.peek()<preorder[i]){
                              last_pop = stack.pop();
                            }
                    stack.push(preorder[i]);
                  }
          }
      return result;
    }
```


text:
using System;
using System.Collections.Generic;
using Android.Runtime;

namespace Com.Squareup.Okhttp.Internal.Spdy {

	// Metadata.xml XPath class reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='Ping']"
	[global::Android.Runtime.Register ("com/squareup/okhttp/internal/spdy/Ping", DoNotGenerateAcw=true)]
	public sealed partial class Ping : global::Java.Lang.Object {

		internal static IntPtr java_class_handle;
		internal static IntPtr class_ref {
			get {
				return JNIEnv.FindClass ("com/squareup/okhttp/internal/spdy/Ping", ref java_class_handle);
			}
		}

		protected override IntPtr ThresholdClass {
			get { return class_ref; }
		}

		protected override global::System.Type ThresholdType {
			get { return typeof (Ping); }
		}

		internal Ping (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}

		static IntPtr id_roundTripTime;
		// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='Ping']/method[@name='roundTripTime' and count(parameter)=0]"
		[Register ("roundTripTime", "()J", "")]
		public long RoundTripTime ()
		{
			if (id_roundTripTime == IntPtr.Zero)
				id_roundTripTime = JNIEnv.GetMethodID (class_ref, "roundTripTime", "()J");
			return JNIEnv.CallLongMethod  (Handle, id_roundTripTime);
		}

		static IntPtr id_roundTripTime_JLjava_util_concurrent_TimeUnit_;
		// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='Ping']/method[@name='roundTripTime' and count(parameter)=2 and parameter[1][@type='long'] and parameter[2][@type='java.util.concurrent.TimeUnit']]"
		[Register ("roundTripTime", "(JLjava/util/concurrent/TimeUnit;)J", "")]
		public long RoundTripTime (long p0, global::Java.Util.Concurrent.TimeUnit p1)
		{
			if (id_roundTripTime_JLjava_util_concurrent_TimeUnit_ == IntPtr.Zero)
				id_roundTripTime_JLjava_util_concurrent_TimeUnit_ = JNIEnv.GetMethodID (class_ref, "roundTripTime", "(JLjava/util/concurrent/TimeUnit;)J");
			long __ret = JNIEnv.CallLongMethod  (Handle, id_roundTripTime_JLjava_util_concurrent_TimeUnit_, new JValue (p0), new JValue (p1));
			return __ret;
		}

	}
}


text:
#ifndef itkSampleClassifierFilter_h
#define itkSampleClassifierFilter_h

#include <vector>

#include "itkMembershipSample.h"
#include "itkMembershipFunctionBase.h"
#include "itkDecisionRule.h"
#include "itkProcessObject.h"
#include "itkSimpleDataObjectDecorator.h"

namespace itk
{
namespace Statistics
{
/**
 *\class SampleClassifierFilter
 *
 *  \brief Sample classification class
 *
 *  This filter takes as input a Sample and produces as output a
 *  classification in the form of a MembershipSample object.
 *
 * \ingroup ITKStatistics
 */

template <typename TSample>
class ITK_TEMPLATE_EXPORT SampleClassifierFilter : public ProcessObject
{
public:
  ITK_DISALLOW_COPY_AND_MOVE(SampleClassifierFilter);

  /** Standard class type alias */
  using Self = SampleClassifierFilter;
  using Superclass = ProcessObject;
  using Pointer = SmartPointer<Self>;
  using ConstPointer = SmartPointer<const Self>;

  /** Standard macros */
  itkTypeMacro(SampleClassifierFilter, ProcessObject);
  itkNewMacro(Self);

  /** Type of the input Sample */
  using SampleType = TSample;

  /** type alias Output type */
  using MembershipSampleType = MembershipSample<SampleType>;
  using MembershipSampleObjectPointer = typename MembershipSampleType::Pointer;

  /** type alias from SampleType object */
  using MeasurementType = typename SampleType::MeasurementType;
  using MeasurementVectorType = typename SampleType::MeasurementVectorType;

  /** type alias for the MembershipFunction */
  using MembershipFunctionType = MembershipFunctionBase<MeasurementVectorType>;
  using MembershipFunctionPointer = typename MembershipFunctionType::ConstPointer;
  using MembershipFunctionVectorType = std::vector<MembershipFunctionPointer>;
  using MembershipFunctionVectorObjectType = SimpleDataObjectDecorator<MembershipFunctionVectorType>;
  using MembershipFunctionVectorObjectPointer = typename MembershipFunctionVectorObjectType::Pointer;

  /** type alias for membership functions weight proprtion */
  using MembershipFunctionsWeightsArrayType = Array<double>;

  using MembershipFunctionsWeightsArrayObjectType = SimpleDataObjectDecorator<MembershipFunctionsWeightsArrayType>;
  using MembershipFunctionsWeightsArrayPointer = typename MembershipFunctionsWeightsArrayObjectType::Pointer;

  using ClassLabelType = IdentifierType;
  using ClassLabelVectorType = std::vector<ClassLabelType>;
  using ClassLabelVectorObjectType = SimpleDataObjectDecorator<ClassLabelVectorType>;
  using ClassLabelVectorObjectPointer = ClassLabelVectorObjectType::Pointer;

  /** type of the decision rule */
  using DecisionRuleType = DecisionRule;
  using DecisionRulePointer = DecisionRuleType::ConstPointer;

  /** Sets the input sample that will be classified by this filter. */
  using Superclass::SetInput;
  void
  SetInput(const SampleType * sample);

  const SampleType *
  GetInput() const;

  /** Returns the classification result */
  const MembershipSampleType *
  GetOutput() const;

  /** Number of classes. This must match the number of labels and membership
   * functions provided by the user, otherwise an exception will be thrown at
   */
  itkSetMacro(NumberOfClasses, unsigned int);
  itkGetConstMacro(NumberOfClasses, unsigned int);

  /** Set/Get the decision rule. */
  itkSetConstObjectMacro(DecisionRule, DecisionRuleType);
  itkGetConstObjectMacro(DecisionRule, DecisionRuleType);

  /** Sets input vector of class labels. The length of this vector must match
   * the number of classes, otherwise an exception will be thrown at run time.
   * */
  void
  SetClassLabels(const ClassLabelVectorObjectType * classLabels);

  /** Sets input vector of membership functions. The length of this vector must match
   * the number of classes, otherwise an exception will be thrown at run time.
   * */
  void
  SetMembershipFunctions(const MembershipFunctionVectorObjectType * membershipFunctions);

  /** Sets array of weights for the membership functions */
  void
  SetMembershipFunctionsWeightsArray(const MembershipFunctionsWeightsArrayObjectType * weightsArray);

protected:
  SampleClassifierFilter();
  ~SampleClassifierFilter() override = default;
  void
  PrintSelf(std::ostream & os, Indent indent) const override;

  /** Starts the classification process */
  void
  GenerateData() override;

  /** Make a DataObject of the correct type to used as the specified
   * output. This method
   * is automatically called when DataObject::DisconnectPipeline() is
   * called.
   * \sa ProcessObject
   */
  using DataObjectPointerArraySizeType = ProcessObject::DataObjectPointerArraySizeType;
  using Superclass::MakeOutput;
  DataObjectPointer
  MakeOutput(DataObjectPointerArraySizeType idx) override;

private:
  unsigned int m_NumberOfClasses;

  /** Decision Rule */
  DecisionRulePointer m_DecisionRule;
}; // end of class
} // end of namespace Statistics
} // end of namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#  include "itkSampleClassifierFilter.hxx"
#endif

#endif


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/Base_controller.php';

class Upload extends Base_controller {
    private $dir_path="";
    private $dir_tmp="";
    function __construct()
    {
        // Construct the parent class
        parent::__construct();
        $this->dir_path='./app/images';
        $this->dir_tmp= $this->dir_path . '/tmp';
        $this->load->library('upload_lib');
    }

    /*public function upload_img_user_post(){
        $msg = '';
        $status = false;
        $answer = array();
        $data_user = $this->get_user_session();
        if( !empty($_FILES) && $data_user && $data_user['username']) {
            try {
                $option = $this->handle_get_option_post_folder();
                $this->handle_check_option_folder_is_created($this->dir_path_post,$option);
                $path_image = $this->dir_path_post.'/'.$option['store_value'].'/'.$option['group_value'].'/'.$option['child_value'];
                $tempPath = $_FILES[ 'file' ][ 'tmp_name' ];
                $file_name = $this->upload_lib->validate_file_in_path($path_image, $_FILES[ 'file' ][ 'name' ]);
                $uploadPath = $path_image . '/' . $file_name;
                $stt = move_uploaded_file( $tempPath, $uploadPath );
                if($stt){
                    $this->handle_check_folder_is_over_load($this->dir_path_post,$option);
                }
                $answer = array( 'name'=>$file_name,'path'=>$uploadPath );
                //$json = json_encode( $answer );
                $msg = 'File transfer completed';
                $status = true;
            } catch (Exception $e) {
                echo 'Caught exception: ',  $e->getMessage();
            }
        }
        $response = array_merge(array('status' => $status,'msg' => $msg),$answer) ;
        $this->custom_response($response);
    }*/

    public function upload_img_user_post_old(){
        $msg = '';
        $status = false;
        $answer = array();
        $data_user = $this->get_user_session();
        $tempPath = $_FILES[ 'file' ][ 'tmp_name' ];
        $file_is_valid =  $this->sup_check_file_info($tempPath);
        if(!$file_is_valid)
            $msg = 'invalid file';
        if( !empty($_FILES) && $data_user && $file_is_valid ) {
            try {
                $option = $this->handle_get_option_user_folder();
                $this->handle_check_user_folder_tmp('',$option,$data_user['user_id']);
                $child_folder_user = $this->dir_path_user .'/'.$option['current_store_user'].'/'.$data_user['user_id'].'/'.$this->dir_path_user_tmp;
                $file_name = $this->upload_lib->validate_file_in_path($child_folder_user, $_FILES[ 'file' ][ 'name' ]);
                $uploadPath = $child_folder_user . '/' . $file_name;
                move_uploaded_file( $tempPath, FCPATH.$uploadPath );
                $answer = array( 'name'=>$file_name,'path'=>$uploadPath );
                //$json = json_encode( $answer );
                $msg = 'File transfer completed';
                $status = true;
            } catch (Exception $e) {
                echo 'Caught exception: ',  $e->getMessage();
            }
        }
        $response = array_merge(array('status' => $status,'msg' => $msg),$answer) ;
        $this->custom_response($response);
    }
    public function upload_img_user_post(){
        $msg = '';
        $status = false;
        $answer = array();
        $data_user = $this->get_user_session();
        $tempPath = $_FILES[ 'file' ][ 'tmp_name' ];
        $file_is_valid =  $this->sup_check_file_info($tempPath);
        if(!$file_is_valid)
            $msg = 'invalid file';
        if( !empty($_FILES) && $data_user && $file_is_valid ) {
            try {
                $year_month = $this->get_tmp_year_month_path();
                $this->check_and_create_tmp_child($year_month); //make sure folder is available
                $session_id = session_id();
                $tmp_folder = $this->dir_path_tmp."/".$year_month;
                $file_name = $this->upload_lib->validate_file_in_path($tmp_folder, $session_id."_".$_FILES[ 'file' ][ 'name' ]);
                $uploadPath = $tmp_folder . '/' . $file_name;
                move_uploaded_file( $tempPath, FCPATH.$uploadPath );
                $answer = array( 'name'=>$file_name,'path'=>$uploadPath );
                //$json = json_encode( $answer );
                $msg = 'File transfer completed';
                $status = true;
            } catch (Exception $e) {
                echo 'Caught exception: ',  $e->getMessage();
            }
        }
        $response = array_merge(array('status' => $status,'msg' => $msg),$answer) ;
        $this->custom_response($response);
    }

    public function sup_check_file_info($tmp_name){
        $stt = false;
        $valid_ext = array('jpg','jpeg','png');
        $image_info = getimagesize($tmp_name);
        if($image_info){
            $type = $ext = false;
            list($type,$ext) = explode("/", $image_info['mime']);
            if($type=='image' && in_array($ext, $valid_ext)){
                $stt = true;
            }
        }
        return $stt;
    }

}


text:
ActiveRecord::Schema.define(:version => 20150726204409) do

  create_table "green_flag_feature_decisions", :force => true do |t|
    t.integer  "feature_id",      :null => false
    t.integer  "site_visitor_id", :null => false
    t.boolean  "enabled"
    t.boolean  "manual"
    t.datetime "created_at",      :null => false
    t.datetime "updated_at",      :null => false
    t.integer  "rule_id"
  end

  add_index "green_flag_feature_decisions", ["feature_id"], :name => "index_green_flag_feature_decisions_on_feature_id"
  add_index "green_flag_feature_decisions", ["site_visitor_id", "feature_id"], :name => "index_gf_feature_decisions_on_site_visitor_id_feature_id", :unique => true

  create_table "green_flag_feature_events", :force => true do |t|
    t.integer  "feature_id",      :null => false
    t.integer  "event_type_code", :null => false
    t.integer  "count",           :null => false
    t.datetime "created_at",      :null => false
    t.datetime "updated_at",      :null => false
  end

  add_index "green_flag_feature_events", ["event_type_code"], :name => "index_green_flag_feature_events_on_event_type_code"
  add_index "green_flag_feature_events", ["feature_id"], :name => "index_green_flag_feature_events_on_feature_id"

  create_table "green_flag_features", :force => true do |t|
    t.string   "code",                          :null => false
    t.string   "description"
    t.datetime "created_at",                    :null => false
    t.datetime "updated_at",                    :null => false
    t.integer  "version_number", :default => 1, :null => false
  end

  add_index "green_flag_features", ["code"], :name => "index_green_flag_features_on_code", :unique => true

  create_table "green_flag_rules", :force => true do |t|
    t.string   "group_key",                     :null => false
    t.integer  "feature_id",                    :null => false
    t.integer  "order_by",                      :null => false
    t.integer  "percentage",     :default => 0, :null => false
    t.datetime "created_at",                    :null => false
    t.datetime "updated_at",                    :null => false
    t.integer  "version_number", :default => 1, :null => false
  end

  add_index "green_flag_rules", ["feature_id", "group_key", "version_number"], :name => "index_green_flag_rules_on_feature_version_and_group_key", :unique => true
  add_index "green_flag_rules", ["feature_id", "order_by", "version_number"], :name => "index_green_flag_rules_on_feature_version_and_order_by", :unique => true

  create_table "green_flag_site_visitors", :force => true do |t|
    t.integer  "user_id"
    t.datetime "created_at",   :null => false
    t.datetime "updated_at",   :null => false
    t.string   "visitor_code", :null => false
  end

  add_index "green_flag_site_visitors", ["user_id"], :name => "index_green_flag_site_visitors_on_user_id", :unique => true
  add_index "green_flag_site_visitors", ["visitor_code"], :name => "index_green_flag_site_visitors_on_visitor_code", :unique => true

  create_table "users", :force => true do |t|
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
    t.string   "email"
  end

end


text:
package org.apache.bcel.verifier.tests;

public class JiraBcel291TestFixture {

    public static Object[] bug(final Object[] arg) {
        return arg.clone();
    }
}


text:
var contactsApp = angular.module('contactsApp', []);

contactsApp.controller('AppCtrl', ['$scope', '$http', function ($scope, $http) {

    var refresh = function () {
        $http.get("/contactList").success(function (response) {
            console.log("REFRESH: Data requested is received");
            $scope.contactList = response;
            $scope.contact = "";
        });
    };

    refresh();

    $scope.addContact = function () {
        console.log("ADD: " + $scope.contact._id);

        $http.post('/contactList', $scope.contact).then(function (response) {
            console.log("ADD RESPONSE: " + response);
            refresh();
        });
    };

    /**
     * Remove ctrl. Handles call of remove function from ejs.
     * @param id
     */
    $scope.remove = function (id) {
        console.log(id);
        // call the proper router with id passed in Express
        $http.delete('/contactList/' + id).success(function (response) {
            refresh();
        });
    };

    $scope.edit = function (id) {
        console.log("contact id in edit is " + id + " " + $scope.contact.name);
        console.log($scope.contact);
        $http.get('/contactList/' + id).success(function (response) {
            $scope.contact = response;
        });
    };

    $scope.update = function () {
        console.log("UPDATE: _id + Name " + $scope.contact._id + " " + $scope.contact.name);
        $http.put('/contactList/' + $scope.contact._id, $scope.contact).success(function (response) {
            refresh();
        });
    };

    $scope.deselect = function () {
        $scope.contact = "";
    };

    $scope.checkInput = function(){
        if($scope.contact.number == null || $scope.contact.email == null){
            console.log("IS FALSE!");
            return false;
        } else
            return true;
    };

    $scope.undo = function () {

    };

    $scope.pattern = /^\s*$/g;
}]);


text:
// --------------------------------------------------------------------------------------------------------------------
// Copyright (c) Lead Pipe Software. All rights reserved.
// Licensed under the MIT License. Please see the LICENSE file in the project root for full license information.
// --------------------------------------------------------------------------------------------------------------------

namespace LeadPipe.Net.Domain
{
    /// <summary>
    /// A marker interface that indicates an Entity is an Aggregate Root. Usage is completely optional.
    /// </summary>
    /// <remarks>Page 125 - Evans, Eric. Domain Driven Design. 2004. Addison-Wesley. March 2009</remarks>
    public interface IAggregateRoot : IEntity
    {
    }
}


text:
MODULE real_complex_module

    implicit none
    include 'mpif.h'

#ifdef _DRSDFT_
    integer,parameter :: TYPE_MAIN=MPI_REAL8
    character(1),parameter :: TRANSA='T'
    character(1),parameter :: TRANSB='N'
    real(8),parameter :: zero=0.d0
    real(8),parameter :: one=1.d0
#else
    integer,parameter :: TYPE_MAIN=MPI_COMPLEX16
    character(1),parameter :: TRANSA='C'
    character(1),parameter :: TRANSB='N'
    complex(8),parameter :: zero=(0.d0,0.d0)
    complex(8),parameter :: one=(1.d0,0.d0)
#endif

CONTAINS

  !---------------------------------------------------------------------------------------

  SUBROUTINE RCProduct( INA,INB,OUTC )
    implicit none
#ifdef _DRSDFT_
    real(8),intent(IN) :: INA,INB
    real(8),intent(OUT) :: OUTC

    OUTC = INA*INB
#else
    complex(8),intent(IN) :: INA,INB
    complex(8),intent(OUT) :: OUTC

    OUTC = conjg(INA)*INB
#endif
  END SUBROUTINE RCProduct

END MODULE real_complex_module


text:
package org.odlabs.wiquery.ui.droppable;

import static org.junit.Assert.*;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.junit.Ignore;
import org.junit.Test;
import org.odlabs.wiquery.tester.WiQueryTestCase;

/**
 * Test on {@link DroppableAjaxBehavior}
 *
 * @author Julien Roche
 */
public class DroppableAjaxBehaviorTestCase extends WiQueryTestCase
{

	/**
	 * Test method for
	 * {@link org.odlabs.wiquery.ui.droppable.DroppableAjaxBehavior#statement()} .
	 */
	@Test
	public void testStatement()
	{
		InnerDroppableAjaxBehavior droppableAjaxBehavior = new InnerDroppableAjaxBehavior();
		WebMarkupContainer component = new WebMarkupContainer("anId");
		component.setMarkupId("anId");
		component.add(droppableAjaxBehavior);

		WebPage webPage = new InnerPage();
		webPage.add(component);

		String ajaxCallResult = droppableAjaxBehavior.statement().render().toString();
		String expectedResult =
			"$('#anId').droppable({drop: function(event, ui) {\n\t"
				+ "var wcall=wicketAjaxGet('wicket/page?0-0.IBehaviorListener.1-anId&droppedId='+ui.draggable[0].id,function() { }.bind(this),function() { }.bind(this), function() {return Wicket.$('anId') != null;}.bind(this));\n"
				+ "}});";
		assertNotNull(droppableAjaxBehavior.getDroppableBehavior());
		assertEquals(expectedResult, ajaxCallResult);
	}

	private class InnerDroppableAjaxBehavior extends DroppableAjaxBehavior<Component>
	{
		private static final long serialVersionUID = 1L;

		@Override
		public void onDrop(Component droppedComponent, AjaxRequestTarget ajaxRequestTarget)
		{
		}
	}

	private class InnerPage extends WebPage
	{

		/**
		 *
		 */
		private static final long serialVersionUID = 1L;

	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<title>Coco Change History</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Author" content="Mike Pall">
<meta name="Copyright" content="Copyright (C) 2005-2008, Mike Pall">
<meta name="Language" content="en">
<link rel="stylesheet" type="text/css" href="bluequad.css" media="screen">
<link rel="stylesheet" type="text/css" href="bluequad-print.css" media="print">

LuaJIT

Coco Change History

Index

LuaJIT

Features

Installation

Running

API Extensions

Introduction

Performance

Debugging

Changes

Coco

Portability

API Extensions

Changes

DynASM

Features

Examples

Download »

This is a list of changes between the released versions of Coco.
The current stand-alone release is Coco 1.1.5.

Please check the
» Online Change History
to see whether newer versions are available.

Coco 1.1.5 — 2008-10-25

Upgraded to patch cleanly into Lua 5.1.4.

Added GCC inline assembler for faster context switching on x64.
Thanks to Robert G. Jakabosky.

Coco 1.1.4 — 2008-02-05

Upgraded to patch cleanly into Lua 5.1.3.

Fixed setjmp method for ARM with recent glibc versions.
Thanks to the LuaTeX developers.

Fixed setjmp method for x86 on Mac OS X (rarely used,
default is GCC inline assembler). Thanks to Jason Toffaletti.

Coco 1.1.3 — 2007-05-24

Upgraded to patch cleanly into Lua 5.1.2.

Merged patch from Zachary P. Landau for a Linux/ARM setjmp method (uClibc and glibc).

Coco 1.1.1 — 2006-06-20

Upgraded to patch cleanly into Lua 5.1.1.

C stacks are deallocated early: when a coroutine ends, and not when
the coroutine object is collected. This mainly benefits Windows Fibers.

Windows threads get the required Fiber context when resuming
a coroutine and not just on creation.

Coco 1.1.0 — 2006-02-18

Upgraded to patch cleanly into Lua 5.1 (final).

Added GCC inline assembler for context switching on x86 and MIPS32
[up to 3x faster].

New targets for setjmp method:
Mac OS X/x86, Solaris/x86 and x64 and Linux/MIPS32.

Workaround for WinXP problem with GetCurrentFiber().

The minimum C stack size has been increased to 32K+4K.

Removed <tt>lcocolib.c</tt> and integrated the (much smaller) changes
into <tt>lbaselib.c</tt>.

Note for embedders: this means you no longer need to call
<tt>luaopen_coco()</tt>.

Optional Valgrind support requires version 3.x.
Renamed define to USE_VALGRIND.

C stacks are now registered with Valgrind.

Coco pre-release 51w6 — 2005-08-09

This is the first pre-release of Coco. It targets Lua 5.1-work6 only
and is no longer available for download.

Copyright © 2005-2008 Mike Pall

·
Contact


text:
<?php

declare(strict_types=1);

namespace DI\Test\UnitTest\Definition\Resolver;

use DI\Definition\FactoryDefinition;
use DI\Definition\ObjectDefinition;
use DI\Definition\Resolver\DefinitionResolver;
use DI\Definition\Resolver\FactoryResolver;
use DI\NotFoundException;
use DI\Test\UnitTest\Definition\Resolver\Fixture\FixtureClass;
use DI\Test\UnitTest\Definition\Resolver\Fixture\NoConstructor;
use EasyMock\EasyMock;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;

/**
 * @covers \DI\Definition\Resolver\FactoryResolver
 */
class FactoryResolverTest extends TestCase
{
    use EasyMock;

    /**
     * @test
     */
    public function should_resolve_callables()
    {
        $container = $this->easyMock(ContainerInterface::class);
        $resolver = new FactoryResolver($container, $this->easyMock(DefinitionResolver::class));

        $definition = new FactoryDefinition('foo', function () {
            return 'bar';
        });

        $value = $resolver->resolve($definition);

        $this->assertEquals('bar', $value);
    }

    /**
     * @test
     */
    public function should_inject_container()
    {
        $container = $this->easyMock(ContainerInterface::class);
        $resolver = new FactoryResolver($container, $this->easyMock(DefinitionResolver::class));

        $definition = new FactoryDefinition('foo', function ($c) {
            return $c;
        });

        $value = $resolver->resolve($definition);

        $this->assertInstanceOf(ContainerInterface::class, $value);
    }

    /**
     * @test
     */
    public function should_throw_if_the_factory_is_not_callable()
    {
        $this->expectException('DI\Definition\Exception\InvalidDefinition');
        $this->expectExceptionMessage('Entry "foo" cannot be resolved: factory \'Hello world\' is neither a callable nor a valid container entry');
        $container = $this->easyMock(ContainerInterface::class);
        $resolver = new FactoryResolver($container, $this->easyMock(DefinitionResolver::class));

        $definition = new FactoryDefinition('foo', 'Hello world');

        $container->method('get')
            ->willThrowException(new NotFoundException);

        $resolver->resolve($definition);
    }

    /**
     * @test
     */
    public function should_throw_if_not_enough_parameters()
    {
        $this->expectException('DI\Definition\Exception\InvalidDefinition');
        $this->expectExceptionMessage('Entry "foo" cannot be resolved: Unable to invoke the callable because no value was given for parameter 3 ($c)');
        $container = $this->easyMock(ContainerInterface::class);
        $resolver = new FactoryResolver($container, $this->easyMock(DefinitionResolver::class));

        $definition = new FactoryDefinition('foo', function ($a, $b, $c) {
        });

        $resolver->resolve($definition);
    }

    /**
     * @test
     */
    public function should_inject_parameters()
    {
        $container = $this->easyMock(ContainerInterface::class);
        $resolver = new FactoryResolver($container, $this->easyMock(DefinitionResolver::class));

        $testCase = $this;
        $definition = new FactoryDefinition('foo', function ($c, $par1, $par2, $baz) use ($testCase) {
            $testCase->assertEquals('Parameter 1', $par1);
            $testCase->assertEquals(2, $par2);
            $testCase->assertEquals('bar', $baz);

            return $c;
        }, ['par1' => 'Parameter 1', 'par2' => 2]);

        $value = $resolver->resolve($definition, ['baz' => 'bar']);

        $this->assertInstanceOf(ContainerInterface::class, $value);
    }

    /**
     * @test
     */
    public function should_resolve_nested_definition_in_parameters()
    {
        $container = $this->easyMock(ContainerInterface::class);
        $parentResolver = $this->easyMock(DefinitionResolver::class);
        $resolver = new FactoryResolver($container, $parentResolver);

        $definition = new FactoryDefinition('foo', function ($par1) {
            return new FixtureClass($par1);
        }, ['par1' => new ObjectDefinition('', NoConstructor::class)]);

        $parentResolver->expects($this->once())
            ->method('resolve')
            ->with($this->isInstanceOf(ObjectDefinition::class))
            ->willReturn('bar');

        $object = $resolver->resolve($definition);

        $this->assertInstanceOf(FixtureClass::class, $object);
        $this->assertEquals('bar', $object->constructorParam1);
    }
}


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

namespace _08.Numbers_from_1_to_N
{
    class Program
    {
        static void Main(string[] args)
        {
            int N = int.Parse(Console.ReadLine());

            for (int i = 1; i <= N; i++)
            {
                Console.WriteLine(i);
            }
        }
    }
}


text:
<?php

use webvimark\modules\UserManagement\components\GhostHtml;
use webvimark\modules\UserManagement\UserManagementModule;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\helpers\ArrayHelper;
use yii\widgets\Pjax;
use webvimark\extensions\GridBulkActions\GridBulkActions;
use webvimark\extensions\GridPageSize\GridPageSize;
use yii\grid\GridView;

/**
 * @var yii\web\View $this
 * @var yii\data\ActiveDataProvider $dataProvider
 * @var webvimark\modules\UserManagement\models\rbacDB\search\AuthItemGroupSearch $searchModel
 */

$this->title = Yii::t('app', 'Grupos de permisos');
$this->params['breadcrumbs'][] = $this->title;
?>

<?= $this->title ?>

	<?php // echo $this->render('_search', ['model' => $searchModel]); ?>

						<?= GhostHtml::a(
							' ' . Yii::t('app', 'Crear'),
							['create'],
							['class' => 'btn btn-success']
						) ?>

					<?= GridPageSize::widget(['pjaxId'=>'auth-item-group-grid-pjax']) ?>

			<?php Pjax::begin([
				'id'=>'auth-item-group-grid-pjax',
			]) ?>

			<?= GridView::widget([
				'id'=>'auth-item-group-grid',
				'dataProvider' => $dataProvider,
				'pager'=>[
					'options'=>['class'=>'pagination pagination-sm'],
					'hideOnSinglePage'=>true,
					'lastPageLabel'=>'>>',
					'firstPageLabel'=>'<<',
				],
				'layout'=>'{items}

{pager}

{summary}'.GridBulkActions::widget([
						'gridId'=>'auth-item-group-grid',
						'actions'=>[Url::to(['bulk-delete'])=>GridBulkActions::t('app', 'Borrar'),],
						]).'

',
				'filterModel' => $searchModel,
				'columns' => [
					['class' => 'yii\grid\SerialColumn', 'options'=>['style'=>'width:10px'] ],

					[
						'attribute'=>'name',
						'value'=>function($model){
								return Html::a($model->name, ['update', 'id'=>$model->code], ['data-pjax'=>0]);
							},
						'format'=>'raw',
					],
					'code',

					['class' => 'yii\grid\CheckboxColumn', 'options'=>['style'=>'width:10px'] ],
					[
						'class' => 'yii\grid\ActionColumn',
						'contentOptions'=>['style'=>'width:70px; text-align:center;'],
					],
				],
			]); ?>

			<?php Pjax::end() ?>


text:
        <button>

</button>

{{ site.title }}

          {% for link in site.data.navigation.main %}
            {% if link.url contains 'http' %}
              {% assign domain = '' %}
            {% else %}
              {% assign domain = site.url | append: site.baseurl %}
            {% endif %}

{{ link.title }}

          {% endfor %}


text:
package se.manet.bangolfresultat.datastruct;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.StringTokenizer;

/** klassen som beskriver resultatlistan */
public class ResultList {
	private HashMap IDMap, classMap;			// saves personal results and the different class names
	private HashMap<String, String> classOrder; // contains the class order
	public static final int FILT = 0;			// filtunderlagets heltalsvärde
	public static final int EB = 1;				// EB-underlagets heltalsvärde
	public static final int BETONG = 2;			// Betong-underlagets heltalsvärde
	public static final int NO_EXTRA_DATA = 0;	// heltalsvärde för ingen extradata
	public static final int START_NBR = 10;		// heltalsvärde för att startnummer skall finnas med
	public static final int ID_NBR = 1;			// heltalsvärde för att idnummer skall finnas med
	public static final int START_AND_ID_NBR = 11;	// heltalsvärde för att start- och idnummer skall finnas med
	public static final int NO_RESULT_THIS_ROUND=-1;// markerar att inget resultat registeras för detta varv
	public static final int MAX_SCORE = 126;	// högsta möjliga slagantal på ett varv
	public static final int MIN_SCORE = 18;		// lägsta möjliga slagantal på ett varv
	private int nbrRounds, surface, nbrLapSums, nbrCols;// tävlingens antal varv, underlag, antal delsummor och antal kolumner
	private String[][] output, outputStyle;	// matris med utdata och matris med information om formatet på detta
	private boolean[] lapSum, startData;	// talar om vilka delsummor som valts, om startnummer och idnummer har valts
	private boolean place;					// anger om placeringsnummer skall visas

	/** skapar en resultatlista för nbrRounds antal varv, underlaget surface där 0 = filt, 1 = eb och 2 = betong
	 samt vilka extra data som valts där startData[0] = startnummer och startData[1] = idnummer */
	public ResultList(int nbrRounds, int surface, boolean[] startData) {
		this.lapSum = new boolean[nbrRounds-2];
		this.startData = startData;
		this.nbrRounds = nbrRounds;
		this.surface = surface;
		this.nbrLapSums = getNbrLapSums();
		if(startData[0] && startData[1]) {
			this.nbrCols = nbrLapSums + 4 + nbrRounds + 2;
		} else if(startData[0] || startData[1]) {
			this.nbrCols = nbrLapSums + 4 + nbrRounds + 1;
		} else {
			this.nbrCols = nbrLapSums + 4 + nbrRounds;
		}
		IDMap = new HashMap();
		classMap = new HashMap();
		initializeClassOrder();
	}

	/**
	 * Initializes the classes having special order. Other classes are ordered
	 * by class name.
	 */
	private void initializeClassOrder() {
		classOrder = new HashMap<String, String>();

		String[] names = new String[21];
		int i = 0;
		names[i++] = "Damveteraner";
		names[i++] = "Herrveteraner";
		names[i++] = "Oldtimers Damer";
		names[i++] = "Oldtimers Herrar";
		names[i++] = "Oldgirls";
		names[i++] = "Oldboys";
		names[i++] = "Ungdom flickor C";
		names[i++] = "Ungdom flickor B";
		names[i++] = "Ungdom flickor A";
		names[i++] = "Ungdom pojkar C";
		names[i++] = "Ungdom pojkar B";
		names[i++] = "Ungdom pojkar A";
		names[i++] = "Ungdom";
		names[i++] = "Damjuniorer";
		names[i++] = "Herrjuniorer";
		names[i++] = "Damseniorer";
		names[i++] = "Herrseniorer";
		names[i++] = "Klass D";
		names[i++] = "Klass C";
		names[i++] = "Klass B";
		names[i++] = "Klass A";

		String s = " ";
		for(int j = 0; j < names.length; j++) {
			classOrder.put(names[j], s);
			s = s + " ";
		}
	}

	/** lägger till ett resultat med startnummer startNbr, namn name, klubb club, idnummer idNbr, varvresultat results
	 antal varv rounds, klassen klass, prioritetsnummer prio och antal varv avklarade nbrRoundsFinished */
	public void addResult(int startNbr, String name, String club, String idNbr, int[] results, int rounds, String klass
			, int prio, int nbrRoundsFinished, int personID) {
		nbrRounds = rounds;
		Integer pID = new Integer(personID);
		if(IDMap.containsKey(pID)) {
			PersonResult pr = (PersonResult) IDMap.get(pID);
			removeFromKlass(pr.getKlass());
			addToKlass(klass);
			pr.changeResults(startNbr,name,club,idNbr,results,klass,prio,nbrRoundsFinished);
		} else {
			addToKlass(klass);
			IDMap.put(new Integer(personID), new PersonResult(startNbr, name, club, idNbr, results, rounds, klass, prio, nbrRoundsFinished, personID));
		}
	}

	/** tar bort resultatet för personen med namnet name och klubben club, returnerar true om det lyckas */
	public boolean removeResult(Integer personID) {
		//String identity = name + club;
		if(IDMap.containsKey(personID)) {
			PersonResult pr = (PersonResult) IDMap.get(personID);
			removeFromKlass(pr.getKlass());
			IDMap.remove(personID);
			return true;
		} else {
			return false;
		}
	}

	/** ändrar namn och klubb för en spelare till newName och newClub */
	public void changeNameAndClub(Integer personID, String newName, String newClub) {
		if(IDMap.containsKey(personID)) {
			PersonResult pr = (PersonResult) IDMap.get(personID);
			pr.changeNameAndClub(newName, newClub);
		}
	}

	/** räknar upp antal förekomster av klassen klass eller lägger till klassen om den inte finns med sedan tidigare */
	private void addToKlass(String klass) {
		if(classMap.containsKey(klass)) {
			int n = ((Integer)classMap.get(klass)).intValue();
			classMap.put(klass, new Integer(n++));
		} else {
			classMap.put(klass, new Integer(1));
		}
	}

	/** räknar ner antal förekomster av klassen klass */
	private void removeFromKlass(String klass) {
		if (classMap.containsKey(klass)) {
			int n = ((Integer)classMap.get(klass)).intValue();
			classMap.put(klass, new Integer(n--));
		}
	}

	/** returnerar PersonResult för personen med id personIdentification */
	public PersonResult getPerson(int personIdentification) {
		Integer personID = new Integer(personIdentification);
		if(IDMap.containsKey(personID)) {
			return (PersonResult) IDMap.get(personID);
		} else {
			return null;
		}
	}

	/**
	 * @return iterator över alla personers resultat
	 */
	public Iterator iterator() {
		return IDMap.values().iterator();
	}

	/** returnerar resultatlistans storlek */
	public int size() {
		return IDMap.size();
	}

	/** sorterar och returnerar därefter resultatlistan som en länkad lista */
	public LinkedList sortResults() {
		LinkedList list = new LinkedList();
		ResultComparator comparator = new ResultComparator();
		list.addAll(IDMap.values());
		Collections.sort(list, comparator);
		return list;
	}

	/** returnerar hur många delsummor som skall visas */
	private int getNbrLapSums() {
		int n = 0;
		for(int i = 0; i < nbrRounds-2; i++) {
			if(lapSum[i]) {
				n++;
			}
		}
		return n;
	}

	/** returnerar en vektor som talar om ifall placering, startnummer och licensnummer skall visas */
	public boolean[] getExtras() {
		boolean[] b = new boolean[3];
		b[0] = place;
		b[1] = startData[0];
		b[2] = startData[1];
		return b;
	}

	/** returnerar en matris med data ifrån resultatlistan */
	public String[][] getOutput() {
		LinkedList list = sortResults();
		ResultComparator comparator = new ResultComparator();
		HashMap tempMap = new HashMap();
		if(list.size() != 0) {
			output = new String[list.size()+3*getNbrOfClasses()-1][nbrCols];
			outputStyle = new String[list.size()+3*getNbrOfClasses()-1][nbrCols];
		} else {
			output = new String[1][1];
			outputStyle = new String[1][1];
		}
		int i = 0;
		int k = 0;
		int placeNbr = 0;
		int sameResult = 0;
		PersonResult oldPerson = null;
		while (i < list.size()) {
			placeNbr++;
			PersonResult pr = (PersonResult)list.get(i);

			if(oldPerson != null) {
				if(comparator.compare(pr, oldPerson) == 0) {
					sameResult++;
				} else {
					sameResult = 0;
				}
			}
			oldPerson = pr;

			int nbrRoundsFinished = pr.getNbrRoundsFinished();
			String klass = pr.getKlass();
			if(!tempMap.containsKey(klass) && tempMap.size()==0) {
				tempMap.put(klass, klass);
				output[i+k][0] = klass;
				outputStyle[i+k][0] = "Bold+";
				k++;
				setHeader(i,k);
				k++;
				placeNbr = 1;
			} else if(!tempMap.containsKey(klass)) {
				tempMap.put(klass, klass);
				output[i+k][0] = " ";
				k++;
				output[i+k][0] = klass;
				outputStyle[i+k][0] = "Bold+";
				k++;
				setHeader(i,k);
				k++;
				placeNbr = 1;
			}
			int j = 0;
			output[i+k][j] = pr.getName();
			j++;
			output[i+k][j] = pr.getClub();
			j++;
			if(startData[1]) {
				output[i+k][j] = String.valueOf(pr.getLicenseNr());
				j++;
			}
			if(startData[0]) {
				output[i+k][j] = String.valueOf(pr.getStartNr());
				j++;
			}
			int[] results = pr.getResultList();
			int nbrRoundsPlayed = nbrRoundsFinished;
			if(nbrRoundsFinished != 0) {
				if(results[0] != ResultList.NO_RESULT_THIS_ROUND) {
					output[i+k][j] = String.valueOf(results[0]);
					outputStyle[i+k][j] = getColor(results[0], 1);
				} else {
					output[i+k][j] = "-";
					outputStyle[i+k][j] = "black";
					nbrRoundsPlayed--;
				}
			}
			j++;
			int upperLevel;
			if(place) {
				upperLevel = nbrCols-3;
			} else {
				upperLevel = nbrCols-2;
			}
			int varv = 2;
			while(j < upperLevel) {
				if(nbrRoundsFinished >= varv) {
					if(results[varv-1] != ResultList.NO_RESULT_THIS_ROUND) {
						output[i+k][j] = String.valueOf(results[varv-1]);
						outputStyle[i+k][j] = getColor(results[varv-1], 1);
					} else {
						output[i+k][j] = "-";
						outputStyle[i+k][j] = "black";
						nbrRoundsPlayed--;
					}
					if(varv < nbrRounds) {
						// delsummor
						if(lapSum[varv-2]) {
							j++;
							int nbrRoundsPlayedThisFar = varv - (nbrRoundsFinished - nbrRoundsPlayed);
							if (nbrRoundsPlayedThisFar != 0) {
								output[i+k][j] = String.valueOf(pr.getSum(varv));
								outputStyle[i+k][j] = "S:a" + getColor(pr.getSum(varv), nbrRoundsPlayedThisFar);
							} else {
								output[i+k][j] = "-";
								outputStyle[i+k][j] = "black";
							}
						}
					}
					varv++;
				}
				j++;
			}
			if(nbrRoundsFinished != 0) {
				if(nbrRoundsPlayed != 0) {
					output[i+k][j] = String.valueOf(pr.getSum(nbrRoundsFinished));
					outputStyle[i+k][j] = "S:a" + getColor(pr.getSum(nbrRoundsFinished), nbrRoundsPlayed);
				} else {
					output[i+k][j] = "-";
					outputStyle[i+k][j] = "black";
				}
			}
			j++;
			if(nbrRoundsFinished != 0) {
				if(nbrRoundsPlayed != 0) {
					double snitt = (double)pr.getSum(nbrRoundsFinished)/(double)nbrRoundsPlayed;
					StringTokenizer str = new StringTokenizer(String.valueOf(snitt), ".");
					String heltal = str.nextToken();
					String decimaltal = str.nextToken();
					if(decimaltal.length() > 2) {
						if(Integer.parseInt(decimaltal.substring(2,3)) >= 5) {
							if(Integer.parseInt(decimaltal.substring(0,2)) == 99) {
								output[i+k][j] = (Integer.parseInt(heltal) + 1) + "," + "00";
							} else if(Integer.parseInt(decimaltal.substring(1,2)) == 9) {
								output[i+k][j] = heltal + "," + (Integer.parseInt(decimaltal.substring(0,1)) + 1) + "0";
							} else {
								output[i+k][j] = heltal + "," + decimaltal.substring(0,1) + (Integer.parseInt(decimaltal.substring(1,2))+1);
							}
						} else {
							output[i+k][j] = heltal + "," + decimaltal.substring(0,2);
						}
					} else if(decimaltal.length() > 1) {
						output[i+k][j] = heltal + "," + decimaltal.substring(0,2);
					} else {
						output[i+k][j] = heltal + "," + decimaltal.substring(0,1) + "0";
					}
					outputStyle[i+k][j] = getColor(pr.getSum(nbrRoundsFinished), nbrRoundsPlayed);
				} else {
					output[i+k][j] = "-";
					outputStyle[i+k][j] = "black";
				}
			}
			j++;
			if(place) {
				output[i+k][j] = String.valueOf(placeNbr - sameResult);
			}
			i++;
		}
		return output;
	}

	/** returnerar formateringen på outputen från resultatlistan */
	public String[][] getOutputStyle() {
		return outputStyle;
	}

	/** returnerar en sträng som talar om vilken färg resultatet skall ha,
	 	man ger in summan result och på hur många varv varv */
	private String getColor(int result, int varv) {
		double snitt = (double)result/(double)varv;
		String color;
		if(surface == FILT) {
			if(snitt < 29.99500) {
				color = "blue";
			} else if(snitt < 35.99500) {
				color = "green";
			} else if(snitt < 39.99500) {
				color = "red";
			} else {
				color = "black";
			}
		} else if(surface == EB) {
			if(snitt < 19.99500) {
				color = "blue";
			} else if(snitt < 24.99500) {
				color = "green";
			} else if(snitt < 29.99500) {
				color = "red";
			} else {
				color = "black";
			}
		} else {
			if(snitt < 24.99500) {
				color = "blue";
			} else if(snitt < 29.99500) {
				color = "green";
			} else if(snitt < 35.99500) {
				color = "red";
			} else {
				color = "black";
			}
		}
		return color;
	}

	/** sätter rubrikerna på rad i+k */
	private void setHeader(int i, int k) {
		String sum;
		if(nbrRounds > 5) {
			sum = "V";
		} else {
			sum = "Varv ";
		}
		int j = 0;
		output[i+k][j] = "Namn";
		outputStyle[i+k][j] = "Bold";
		j++;
		output[i+k][j] = "Klubb";
		outputStyle[i+k][j] = "Bold";
		j++;
		if(startData[1]) {
			output[i+k][j] = "Licensnummer";
			outputStyle[i+k][j] = "Bold";
			j++;
		}
		if(startData[0]) {
			output[i+k][j] = "StartNr";
			outputStyle[i+k][j] = "Bold";
			j++;
		}
		output[i+k][j] = sum + "1";
		outputStyle[i+k][j] = "Bold";
		j++;
		output[i+k][j] = sum + "2";
		outputStyle[i+k][j] = "Bold";
		j++;
		int varv = 2;
		int upperLevel;
		if(place) {
			upperLevel = nbrCols-3;
		} else {
			upperLevel = nbrCols-2;
		}
		while(j < upperLevel) {
			if(lapSum[varv-2]) {
				output[i+k][j] = "S:a";
				outputStyle[i+k][j] = "Bold";
				j++;
			}
			varv++;
			output[i+k][j] = sum + varv;
			outputStyle[i+k][j] = "Bold";
			j++;
		}
		output[i+k][j] = "S:a";
		outputStyle[i+k][j] = "Bold";
		j++;
		output[i+k][j] = "Medel";
		outputStyle[i+k][j] = "Bold";
		j++;
		if(place) {
			output[i+k][j] = "Plac.";
			outputStyle[i+k][j] = "Bold";
		}
	}

	/** ställer in vilka delsummor som skall visas utifrån lapSum */
	public void setLapSum(boolean[] lapSum) {
		nbrCols = nbrCols - nbrLapSums;
		this.lapSum = lapSum;
		nbrLapSums = getNbrLapSums();
		nbrCols = nbrCols + nbrLapSums;
	}

	/** anger om placering skall visas */
	public void setPlace(boolean place) {
		if(!this.place && place) {
			nbrCols++;
		} else if(this.place && !place) {
			nbrCols--;
		}
		this.place = place;
	}

	/** returnerar antalet olika klasser som finns i resultatlistan */
	private int getNbrOfClasses() {
		int n = 0;
		LinkedList list = new LinkedList();
		list.addAll(classMap.values());
		for(int i = 0; i < list.size(); i++) {
			if(((Integer)list.get(i)).intValue() != 0) {
				n++;
			}
		}
		return n;
	}

	/** returnerar antalet kolumner som behövs för att visa resultatet */
	public int getNbrCols() {
		return nbrCols;
	}

	/** returnerar hur många varv tävlingen är på */
	public int getNbrRounds() {
		return nbrRounds;
	}

	/** returnerar tävlingens underlag */
	public int getSurface() {
		return surface;
	}

	/** returnerar en vektor som talar om ifall startnummer och idnummer skall visas */
	public boolean[] getStartData() {
		return startData;
	}

	/** talar om vilka "extradata" i form av startnummer och idnummer som skall visas */
	public int getExtraData() {
		int extraData = NO_EXTRA_DATA;
		if(startData[0] && startData[1]) {
			extraData = START_AND_ID_NBR;
		} else if(startData[0]) {
			extraData = START_NBR;
		} else if(startData[1]) {
			extraData = ID_NBR;
		}
		return extraData;
	}

	/** talar om hur klasserna skall sorteras */
	private String getClassOrder(String className) {
		if(classOrder.containsKey(className)) {
			return (String) classOrder.get(className);
		} else {
			return className;
		}
	}

	/** klassen som sköter sorteringen av resultatlistan */
	class ResultComparator implements Comparator {
		/**	bestämmer skillnaden mellan lhs och rhs genom att sortera i ordningen
		 *	klass, avklarade varv, summa, prioritet och differens
		 *	@see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
		 */
		public int compare(Object lhs, Object rhs) {
			PersonResult left = (PersonResult) lhs;
			PersonResult right = (PersonResult) rhs;
			String klassRight = getClassOrder(right.getKlass());
			String klassLeft = getClassOrder(left.getKlass());
			int prioRight = right.getPrio();
			int prioLeft = left.getPrio();
			int roundsLeft = left.getNbrRoundsFinished();
			int roundsRight = right.getNbrRoundsFinished();
			int roundsPlayedLeft = left.getNbrRoundsPlayed();
			int roundsPlayedRight = right.getNbrRoundsPlayed();
			int sumRight, sumLeft;
			/*
			if(roundsPlayedLeft == 0) {
			    sumLeft = 127;
			} else {
			    sumLeft = left.getSum(roundsLeft);
			}
			if(roundsPlayedRight == 0) {
			    sumRight = 127;
			} else {
			    sumRight = right.getSum(roundsRight);
			}*/
			/** sortera på snitt för att se bra ut när någon står över ett varv */
			if(roundsPlayedLeft != 0) {
				sumLeft = (int) (10000*((double)left.getSum(roundsLeft)/(double)roundsPlayedLeft));
			} else {
				sumLeft = 10000 * 127;
			}
			if (roundsPlayedRight != 0) {
				sumRight = (int) (10000*((double)right.getSum(roundsRight)/(double)roundsPlayedRight));
			} else {
				sumRight = 10000 * 127;
			}
			int diffLeft = left.getDiff();
			int diffRight = right.getDiff();
			if (klassLeft.equals(klassRight)) {
				if (roundsLeft == roundsRight) {
					if (sumLeft == sumRight) {
						if (prioLeft == prioRight) {
							if (diffLeft == diffRight) {
								return 0;
							} else {
								return diffLeft - diffRight;
							}
						} else {
							return prioLeft - prioRight;
						}
					} else {
						return sumLeft - sumRight;
					}
				} else {
					return roundsRight - roundsLeft;
				}
			} else {
				return klassLeft.compareTo(klassRight);
			}
		}
	}
}


text:
export interface SkyTileDashboardConfigLayoutTile {
  id: string;
  isCollapsed: boolean;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
	 "http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>

	<meta http-equiv="content-type" content="text/html;charset=utf-8">
	<script type="text/javascript" src="../../build/lib/three.min.js"></script>
	<script type="text/javascript" src="../../build/jsmodeler.js"></script>
	<script type="text/javascript" src="../../build/jsmodeler.ext.three.js"></script>
	<script type="text/javascript" src="clockgenerator.js"></script>
	<title>JSModeler Clock Example</title>

	<style>
		html, body
		{
			margin : 0px;
			padding : 0px;
			width : 100%;
			height : 100%;
		}

		canvas
		{
			display : block;
		}
	</style>

	<script type="text/javascript">
		var viewer = null;
		var fixTime = false;

		function Update ()
		{
			var time = new Date ();

			var currentHours = time.getHours () % 12;
			var currentMinutes = time.getMinutes ();
			var currentSeconds = time.getSeconds ();
			var currentMilliseconds = time.getMilliseconds ();
			if (fixTime) {
				var currentHours = 1 % 12;
				var currentMinutes = 42;
				var currentSeconds = 27;
				var currentMilliseconds = 0;
			}

			var currentHoursInMinutes = currentHours * 60 + currentMinutes;
			var currentMinutesInSeconds = currentMinutes * 60 + currentSeconds;
			var currentSecondsInMilliseconds = currentSeconds * 1000 + currentMilliseconds;

			var hourAngle = currentHoursInMinutes * 360 / 720;
			var minuteAngle = currentMinutesInSeconds * 360 / 3600;
			var secondAngle = currentSecondsInMilliseconds * 360 / 60000;
			viewer.GetMesh (15).rotation.z = -hourAngle * JSM.DegRad;
			viewer.GetMesh (16).rotation.z = -minuteAngle * JSM.DegRad;
			viewer.GetMesh (17).rotation.z = -secondAngle * JSM.DegRad;

			viewer.Draw ();
			requestAnimationFrame (Update);
		};

		function Resize ()
		{
			var margin = 10;
			var canvas = document.getElementById ('example');
			canvas.width = window.innerWidth;
			canvas.height = window.innerHeight;
		}

		function Load ()
		{
			var TextureLoaded = function () {
				viewer.Draw ();
			};

			var viewerSettings = {
				cameraEyePosition : [2.0, 2.0, 2.0],
				cameraCenterPosition : [0.0, 0.0, 0.0],
				cameraUpVector : [1, 0, 0]
			};

			window.onresize = Resize;
			Resize ();

			viewer = new JSM.ThreeViewer ();
			viewer.Start (document.getElementById ('example'), viewerSettings);

			var model = JSM.GenerateClock (1.0, 100);

			var conversionData = {
				textureLoadedCallback : null,
				hasConvexPolygons : true
			};
			var meshes = JSM.ConvertModelToThreeMeshes (model, conversionData);

			for (var i = 0; i < meshes.length; i++) {
				viewer.AddMesh (meshes[i]);
			}

			var hash = window.location.hash.substr (1);
			if (hash == 'fixtime') {
				fixTime = true;
			}

			Update ();
		};

	    window.onload = function ()
		{
			Load ();
		};
	</script>

</head>

<body>
	<canvas id="example" width="1000" height="500"></canvas>
</body>

</html>


text:
using namespace v8;

void InitAll(Handle<Object> exports) {
  Connection::Init(exports);
}

NODE_MODULE(riak, InitAll)


text:
using System;
using System.Linq;
using System.Threading.Tasks;
using Cosmos.Debug.Kernel;

namespace Cosmos.CPU.x86.Memory.Old
{
    // This class must be static, as for creating objects, we need the heap
    // this heap implementation it the very most basic one: no reentrancy, etc.
    // Interrupts are disabled when trying to allocate a new block of memory.
    public static unsafe class Heap
    {
        private static Debugger mDebugger = new Debugger("Core", "Memory");

        private static uint mEndOfRam;

        private static uint mLastTableIndex = 0u;

        private static uint mLastEntryIndex = 0u;

        private static void DoInitialize(uint aEndOfRam)
        {
            mLastTableIndex = 0u;
            mLastEntryIndex = 0u;
            mEndOfRam = aEndOfRam;
            //
        }

        private static bool mInitialized = false;
        internal static void EnsureIsInitialized()
        {
            if (!mInitialized)
            {
                mInitialized = true;
                DoInitialize((Processor.GetAmountOfRAM() - 1) * 1024 * 1024);
                //DoInitialize(4 * 1024 * 1024, 16 * 1024 * 1024);
            }
        }

        private static void ClearMemory(void* aStartAddress, uint aLength)
        {
            //TODO: Move to memory. Internal access only...
            Processor.ZeroFill((uint)aStartAddress, aLength);
        }

        public static uint MemAlloc(uint aLength)
        {
            if (aLength == 0)
            {
                mDebugger.Send("    Request to retrieve block with size = 0 was halted!");
                while (true)
                {
                }
            }
            var xInterruptsWereEnabled = Processor.DisableInterrupts();
            try
            {
                EnsureIsInitialized();

                var xCurrentTableIdx = mLastTableIndex;
                DataLookupTable* xCurrentTable = GlobalSystemInfo.GlobalInformationTable->FirstDataLookupTable;
                DataLookupTable* xPreviousTable = null;
                uint xResult;
                #region Loop through existing tables and see if we find a free spot
                while (xCurrentTable != null)
                {
                    //mDebugger.Trace($"At address {(uint)xCurrentTable}");
                    if (ScanDataLookupTable(xCurrentTableIdx, xCurrentTable, aLength, out xResult))
                    {
                        if (xResult < Processor.GetEndOfKernel())
                        {
                            mDebugger.Send("Wrong handle returned!");
                            while (true)
                            {
                            }
                        }
                        return xResult;
                    }
                    xCurrentTableIdx++;
                    xPreviousTable = xCurrentTable;
                    xCurrentTable = xCurrentTable->Next;
                    mLastTableIndex = xCurrentTableIdx;
                    mLastEntryIndex = 0;
                }
                #endregion Loop through existing tables and see if we find a free spot

                // no tables found, lets create a new one, and use that
                if (xPreviousTable == null)
                {
                    // this check should theoretically be unnecessary, but lets keep it, to do some double-checking.
                    mDebugger.Send("No PreviousTable found!");
                    while (true)
                    {
                    }
                }
                var xLastItem = xPreviousTable->GetEntry(DataLookupTable.EntriesPerTable - 1);
                var xNextTablePointer = (DataLookupTable*)((uint)xLastItem->DataBlock + xLastItem->Size);
                // the memory hasn't been cleared yet, so lets do that now.
                ClearMemory(xNextTablePointer, GlobalSystemInfo.TotalDataLookupTableSize);
                xPreviousTable->Next = xNextTablePointer;
                xNextTablePointer->Previous = xPreviousTable;

                if (!ScanDataLookupTable(xCurrentTableIdx, xNextTablePointer, aLength, out xResult))
                {
                    // Something seriously weird happened: we could create a new DataLookupTable (with new entries)
                    // but couldn't allocate a new handle from it.
                    mDebugger.Send("    Something seriously weird happened: we could create a new DataLookupTable (with new entries), but couldn't allocate a new handle from it.");
                    while (true)
                    {
                    }
                }
                mLastTableIndex = xCurrentTableIdx;
                mLastEntryIndex = 0;
                return xResult;
            }
            finally
            {
                if (xInterruptsWereEnabled)
                {
                    Processor.EnableInterrupts();
                }
                else
                {
                    //mDebugger.Trace("    Not enabling interrupts, because they weren't enabled yet!");
                }
            }
        }

        private static bool ScanDataLookupTable(uint aTableIdx, DataLookupTable* aTable, uint aSize, out uint aHandle)
        {
            DataLookupEntry* xPreviousEntry = null;
            for (uint i = mLastEntryIndex; i < DataLookupTable.EntriesPerTable; i++)
            {
                var xCurrentEntry = aTable->GetEntry(i);

                //mDebugger.Trace($"Item.Size", xCurrentEntry->Size);
                //mDebugger.Trace($"Item.Refcount", xCurrentEntry->Refcount);
                if (xCurrentEntry->Size == 0)
                {
                    #region Found an uninitialized entry
                    // found an entry now. Let's set it
                    if (aTable->Next != null)
                    {
                        // once a handle is used, the size should be set. But at this point, it somehow got unset again.
                        // This should never occur.
                        mDebugger.Send("Found an entry which has no size, but there is a followup DataLookupTable");
                        while (true)
                        {
                        }
                    }

                    void* xDataBlock;
                    //mDebugger.Trace("Now calculate datablock pointer");
                    // now we found ourself a free handle
                    if (i == 0)
                    {
                        //mDebugger.Trace("Using table end");
                        // we don't have a previous handle yet, so we take the FirstByteAfterTable field of the DataLookupTable
                        // note: we're explicitly initializing all blocks, as memory hasn't been cleared yet.
                        var xTableAddr = (uint)aTable;
                        //mDebugger.Trace($"aTableAddr", xTableAddr);
                        var xTotalTableSize = GlobalSystemInfo.TotalDataLookupTableSize;
                        //mDebugger.Trace($"TotalTableSize", xTotalTableSize);
                        xDataBlock = (void*)(((uint)aTable) + GlobalSystemInfo.TotalDataLookupTableSize);
                    }
                    else
                    {
                        //mDebugger.Trace("Using previous entry");
                        // We're not the very first handle being assigned, so calculate the start address using the previous block
                        xDataBlock = (void*)((uint)xPreviousEntry->DataBlock + xPreviousEntry->Size);
                    }

                    // make sure the memory is empty
                    ClearMemory(xDataBlock, aSize);
                    //mDebugger.Trace("Cleared memory");
                    xCurrentEntry->Size = aSize;
                    xCurrentEntry->DataBlock = xDataBlock;
                    xCurrentEntry->Refcount = 1;

                    aHandle = (uint)xCurrentEntry->DataBlock;
                    //mDebugger.Trace($"Returning handle ", aHandle);
                    mLastEntryIndex = i;
                    #endregion Found an uninitialized entry
                    return true;
                }

                // Refcount == UInt32.MaxValue, it means that the block has been reclaimed, and can be reused now.
                if (xCurrentEntry->Refcount == UInt32.MaxValue)
                {
                    // we can reuse this entry if its Size >= aLength
                    if (xCurrentEntry->Size >= aSize)
                    {
                        // we can reuse this entry
                        xCurrentEntry->Refcount = 1;
                        aHandle = (uint)xCurrentEntry->DataBlock;
                        mLastEntryIndex = i;
                        return true;
                    }
                }
                xPreviousEntry = xCurrentEntry;
            }
            aHandle = 0;
            return false;
        }
    }
}


text:
package eu.qualimaster.common.hardware;

/**
 * Defines the interface for obtaining responses.
 *
 * @author Holger Eichelberger
 */
public interface IHardwareDispatcher {

    /**
     * Called when an upload is finished.
     *
     * @param msg the received message
     */
    public void received(UploadMessageOut msg);

    /**
     * Called when the information about running state of an algorithm is available.
     *
     * @param msg the received message
     */
    public void received(IsRunningAlgorithmOut msg);

    /**
     * Called when the result about stopping an algorithm is available.
     *
     * @param msg the received message
     */
    public void received(StopMessageOut msg);

    /**
     * Called when the server terminated.
     */
    public void serverTerminated();

}


text:
$(function(){
	$("#aside").addClass("alpha");
	$("#wrapper div#content").addClass("omega");
	$("#logo").addClass("alpha");
	$("#top-nav-bar").addClass("omega");
	$('div[data-hook="product_price"]').removeClass("five").addClass("seven");
	$("#taxon-crumbs").removeClass("five").addClass("seven");
});