text:
//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * Redistributions in binary form must reproduce the above
//        copyright notice, this list of conditions and the following
//        disclaimer in the documentation and/or other materials provided with
//        the distribution.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "GafferScene/InteractiveRender.h"

#include "GafferScene/SceneAlgo.h"
#include "GafferScene/SceneNode.h"
#include "GafferScene/SceneProcessor.h"

#include "Gaffer/Context.h"
#include "Gaffer/ScriptNode.h"
#include "Gaffer/StringPlug.h"

#include "IECoreScene/Transform.h"
#include "IECoreScene/VisibleRenderable.h"

#include "IECore/MessageHandler.h"
#include "IECore/NullObject.h"

#include "boost/algorithm/string/predicate.hpp"
#include "boost/bind.hpp"

#include "tbb/task.h"

using namespace std;
using namespace Imath;
using namespace IECore;
using namespace IECoreScene;
using namespace Gaffer;
using namespace GafferScene;

//////////////////////////////////////////////////////////////////////////
// Private utilities
//////////////////////////////////////////////////////////////////////////

namespace
{

InternedString g_cameraGlobalName( "option:render:camera" );

InternedString g_visibleAttributeName( "scene:visible" );
InternedString g_setsAttributeName( "sets" );
InternedString g_rendererContextName( "scene:renderer" );

bool visible( const CompoundObject *attributes )
{
	const IECore::BoolData *d = attributes->member<IECore::BoolData>( g_visibleAttributeName );
	return d ? d->readable() : true;
}

bool cameraGlobalsChanged( const CompoundObject *globals, const CompoundObject *previousGlobals )
{
	if( !previousGlobals )
	{
		return true;
	}
	CameraPtr camera1 = new Camera;
	CameraPtr camera2 = new Camera;
	RendererAlgo::applyCameraGlobals( camera1.get(), globals );
	RendererAlgo::applyCameraGlobals( camera2.get(), previousGlobals );

	return *camera1 != *camera2;
}

} // namespace

//////////////////////////////////////////////////////////////////////////
// Internal implementation details
//////////////////////////////////////////////////////////////////////////

// Represents a location in the Gaffer scene as specified to the
// renderer. We use this to build up a persistent representation of
// the scene which we can traverse to perform selective updates to
// only the changed locations. A Renderer's representation of the
// scene contains only a flat list of objects, whereas the SceneGraph
// maintains the original hierarchy, providing the means of flattening
// attribute and transform state for passing to the renderer. Calls
// to update() are made from a threaded scene traversal performed by
// SceneGraphUpdateTask.
class InteractiveRender::SceneGraph
{

	public :

		// We store separate scene graphs for
		// objects which are classified differently
		// by the renderer. This lets us output
		// lights and cameras prior to the
		// rest of the scene, which may be a
		// requirement of some renderer backends.
		enum Type
		{
			CameraType = 0,
			LightType = 1,
			ObjectType = 2,
			FirstType = CameraType,
			LastType = ObjectType,
			NoType = LastType + 1
		};

		enum Component
		{
			NoComponent = 0,
			BoundComponent = 1,
			TransformComponent = 2,
			AttributesComponent = 4,
			ObjectComponent = 8,
			ChildNamesComponent = 16,
			GlobalsComponent = 32,
			SetsComponent = 64,
			RenderSetsComponent = 128, // Sets prefixed with "render:"
			AllComponents = BoundComponent | TransformComponent | AttributesComponent | ObjectComponent | ChildNamesComponent | GlobalsComponent | SetsComponent | RenderSetsComponent
		};

		// Constructs the root of the scene graph.
		// Children are constructed using updateChildren().
		SceneGraph()
			:	m_parent( nullptr ), m_fullAttributes( new CompoundObject )
		{
			clear();
		}

		~SceneGraph()
		{
			clear();
		}

		const InternedString &name() const
		{
			return m_name;
		}

		// Called by SceneGraphUpdateTask to update this location. Returns a bitmask
		// of the components which were changed.
		unsigned update( const ScenePlug *scene, const ScenePlug::ScenePath &path, unsigned dirtyComponents, unsigned changedParentComponents, Type type, IECoreScenePreview::Renderer *renderer, const IECore::CompoundObject *globals, const RendererAlgo::RenderSets &renderSets )
		{
			unsigned changedComponents = 0;

			// Attributes

			if( !m_parent )
			{
				// Root - get attributes from globals.
				if( dirtyComponents & GlobalsComponent )
				{
					if( updateAttributes( globals ) )
					{
						changedComponents |= AttributesComponent;
					}
				}
			}
			else
			{
				// Non-root - get attributes the standard way.
				const bool parentAttributesChanged = changedParentComponents & AttributesComponent;
				if( parentAttributesChanged || ( dirtyComponents & AttributesComponent ) )
				{
					if( updateAttributes( scene->attributesPlug(), parentAttributesChanged ) )
					{
						changedComponents |= AttributesComponent;
					}
				}
			}

			if( !::visible( m_fullAttributes.get() ) )
			{
				clear();
				return changedComponents;
			}

			// Render Sets. We must obviously update these if
			// the sets have changed, but we also need to do an
			// update if the attributes have changed, because in
			// that case we may have overwritten the sets attribute.

			if( ( dirtyComponents & RenderSetsComponent ) || ( changedComponents & AttributesComponent ) )
			{
				if( updateRenderSets( path, renderSets ) )
				{
					changedComponents |= AttributesComponent;
				}
			}

			// Transform

			if( ( dirtyComponents & TransformComponent ) && updateTransform( scene->transformPlug(), changedParentComponents & TransformComponent ) )
			{
				changedComponents |= TransformComponent;
			}

			// Object

			if( ( dirtyComponents & ObjectComponent ) && updateObject( scene->objectPlug(), type, renderer, globals ) )
			{
				changedComponents |= ObjectComponent;
			}

			// Object updates for transform and attributes

			if( m_objectInterface )
			{
				if( !(changedComponents & ObjectComponent) )
				{
					// Apply attribute update to old object if necessary.
					if( changedComponents & AttributesComponent )
					{
						if( !m_objectInterface->attributes( attributesInterface( renderer ) ) )
						{
							// Failed to apply attributes - must replace entire object.
							m_objectHash = MurmurHash();
							if( updateObject( scene->objectPlug(), type, renderer, globals ) )
							{
								changedComponents |= ObjectComponent;
							}
						}
					}
				}

				// If the transform has changed, or we have an entirely new object,
				// the apply the transform.
				if( changedComponents & ( ObjectComponent | TransformComponent ) )
				{
					m_objectInterface->transform( m_fullTransform );
				}
			}

			// Children

			if( ( dirtyComponents & ChildNamesComponent ) && updateChildren( scene->childNamesPlug() ) )
			{
				changedComponents |= ChildNamesComponent;
			}

			m_cleared = false;

			return changedComponents;
		}

		const std::vector<SceneGraph *> &children()
		{
			return m_children;
		}

		// Invalidates this location, removing any resources it
		// holds in the renderer, and clearing all children. This is
		// used to "remove" a location without having to delete it
		// from the children() of its parent. We avoid the latter
		// because it would involve some unwanted locking - we
		// process children in parallel, and therefore want to avoid
		// child updates having to write to the parent.
		void clear()
		{
			clearChildren();
			clearObject();
			m_attributesHash = m_transformHash = m_childNamesHash = IECore::MurmurHash();
			m_cleared = true;
		}

		// Returns true if the location has not been finalised
		// since the last call to clear() - ie that it is not
		// in a valid state.
		bool cleared()
		{
			return m_cleared;
		}

	private :

		SceneGraph( const InternedString &name, const SceneGraph *parent )
			:	m_name( name ), m_parent( parent ), m_fullAttributes( new CompoundObject )
		{
			clear();
		}

		// Returns true if the attributes changed.
		bool updateAttributes( const CompoundObjectPlug *attributesPlug, bool parentAttributesChanged )
		{
			assert( m_parent );

			const IECore::MurmurHash attributesHash = attributesPlug->hash();
			if( attributesHash == m_attributesHash && !parentAttributesChanged )
			{
				return false;
			}

			ConstCompoundObjectPtr attributes = attributesPlug->getValue( &attributesHash );
			CompoundObject::ObjectMap &fullAttributes = m_fullAttributes->members();
			fullAttributes = m_parent->m_fullAttributes->members();
			for( CompoundObject::ObjectMap::const_iterator it = attributes->members().begin(), eIt = attributes->members().end(); it != eIt; ++it )
			{
				fullAttributes[it->first] = it->second;
			}

			m_attributesInterface = nullptr; // Will be updated lazily in attributesInterface()
			m_attributesHash = attributesHash;

			return true;
		}

		// As above, but for use at the root.
		bool updateAttributes( const CompoundObject *globals )
		{
			assert( !m_parent );

			ConstCompoundObjectPtr globalAttributes = GafferScene::SceneAlgo::globalAttributes( globals );
			if( m_fullAttributes && *m_fullAttributes == *globalAttributes )
			{
				return false;
			}

			m_fullAttributes->members() = globalAttributes->members();
			m_attributesInterface = nullptr;

			return true;
		}

		bool updateRenderSets( const ScenePlug::ScenePath &path, const RendererAlgo::RenderSets &renderSets )
		{
			m_fullAttributes->members()[g_setsAttributeName] = boost::const_pointer_cast<InternedStringVectorData>(
				renderSets.setsAttribute( path )
			);
			m_attributesInterface = nullptr;
			return true;
		}

		IECoreScenePreview::Renderer::AttributesInterface *attributesInterface( IECoreScenePreview::Renderer *renderer )
		{
			if( !m_attributesInterface )
			{
				m_attributesInterface = renderer->attributes( m_fullAttributes.get() );
			}
			return m_attributesInterface.get();
		}

		// Returns true if the transform changed.
		bool updateTransform( const M44fPlug *transformPlug, bool parentTransformChanged )
		{
			const IECore::MurmurHash transformHash = transformPlug->hash();
			if( transformHash == m_transformHash && !parentTransformChanged )
			{
				return false;
			}

			const M44f transform = transformPlug->getValue( &transformHash );
			if( m_parent )
			{
				m_fullTransform = transform * m_parent->m_fullTransform;
			}
			else
			{
				m_fullTransform = transform;
			}

			m_transformHash = transformHash;
			return true;
		}

		// Returns true if the object changed.
		bool updateObject( const ObjectPlug *objectPlug, Type type, IECoreScenePreview::Renderer *renderer, const IECore::CompoundObject *globals )
		{
			const bool hadObjectInterface = static_cast<bool>( m_objectInterface );
			if( type == NoType )
			{
				m_objectInterface = nullptr;
				return hadObjectInterface;
			}

			const IECore::MurmurHash objectHash = objectPlug->hash();
			if( objectHash == m_objectHash )
			{
				return false;
			}

			m_objectInterface = nullptr;

			IECore::ConstObjectPtr object = objectPlug->getValue( &objectHash );
			m_objectHash = objectHash;

			const IECore::NullObject *nullObject = runTimeCast<const IECore::NullObject>( object.get() );
			if( (type != LightType) && nullObject )
			{
				return hadObjectInterface;
			}

			std::string name;
			ScenePlug::pathToString( Context::current()->get<vector<InternedString> >( ScenePlug::scenePathContextName ), name );
			if( type == CameraType )
			{
				if( const IECoreScene::Camera *camera = runTimeCast<const IECoreScene::Camera>( object.get() ) )
				{
					IECoreScene::CameraPtr cameraCopy = camera->copy();
					RendererAlgo::applyCameraGlobals( cameraCopy.get(), globals );
					m_objectInterface = renderer->camera( name, cameraCopy.get(), attributesInterface( renderer ) );
				}
			}
			else if( type == LightType )
			{
				m_objectInterface = renderer->light( name, nullObject ? nullptr : object.get(), attributesInterface( renderer ) );
			}
			else
			{
				m_objectInterface = renderer->object( name, object.get(), attributesInterface( renderer ) );
			}

			return true;
		}

		void clearObject()
		{
			m_objectInterface = nullptr;
			m_objectHash = MurmurHash();
		}

		// Ensures that children() contains a child for every name specified
		// by childNamesPlug(). This just ensures that the children exist - they
		// will be subsequently be updated in parallel by the SceneGraphUpdateTask.
		bool updateChildren( const InternedStringVectorDataPlug *childNamesPlug )
		{
			const IECore::MurmurHash childNamesHash = childNamesPlug->hash();
			if( childNamesHash == m_childNamesHash )
			{
				return false;
			}

			IECore::ConstInternedStringVectorDataPtr childNamesData = childNamesPlug->getValue( &childNamesHash );
			const std::vector<IECore::InternedString> &childNames = childNamesData->readable();
			if( !existingChildNamesValid( childNames ) )
			{
				clearChildren();
				for( std::vector<IECore::InternedString>::const_iterator it = childNames.begin(), eIt = childNames.end(); it != eIt; ++it )
				{
					SceneGraph *child = new SceneGraph( *it, this );
					m_children.push_back( child );
				}
			}
			return true;
		}

		void clearChildren()
		{
			for( std::vector<SceneGraph *>::const_iterator it = m_children.begin(), eIt = m_children.end(); it != eIt; ++it )
			{
				delete *it;
			}
			m_children.clear();
		}

		bool existingChildNamesValid( const vector<IECore::InternedString> &childNames ) const
		{
			if( m_children.size() != childNames.size() )
			{
				return false;
			}
			for( size_t i = 0, e = childNames.size(); i < e; ++i )
			{
				if( m_children[i]->m_name != childNames[i] )
				{
					return false;
				}
			}
			return true;
		}

		IECore::InternedString m_name;

		const SceneGraph *m_parent;

		IECore::MurmurHash m_objectHash;
		IECoreScenePreview::Renderer::ObjectInterfacePtr m_objectInterface;

		IECore::MurmurHash m_attributesHash;
		IECore::CompoundObjectPtr m_fullAttributes;
		IECoreScenePreview::Renderer::AttributesInterfacePtr m_attributesInterface;

		IECore::MurmurHash m_transformHash;
		Imath::M44f m_fullTransform;

		IECore::MurmurHash m_childNamesHash;
		std::vector<SceneGraph *> m_children;

		bool m_cleared;

};

// TBB task used to perform multithreaded updates on our SceneGraph.
class InteractiveRender::SceneGraphUpdateTask : public tbb::task
{

	public :

		SceneGraphUpdateTask(
			const InteractiveRender *interactiveRender,
			SceneGraph *sceneGraph,
			SceneGraph::Type sceneGraphType,
			unsigned dirtyComponents,
			unsigned changedParentComponents,
			const Context *context,
			const ScenePlug::ScenePath &scenePath
		)
			:	m_interactiveRender( interactiveRender ),
				m_sceneGraph( sceneGraph ),
				m_sceneGraphType( sceneGraphType ),
				m_dirtyComponents( dirtyComponents ),
				m_changedParentComponents( changedParentComponents ),
				m_context( context ),
				m_scenePath( scenePath )
		{
		}

		task *execute() override
		{

			// Figure out if this location belongs in the type
			// of scene graph we're constructing. If it doesn't
			// belong, and neither do any of its descendants,
			// we can just early out.

			const unsigned sceneGraphMatch = this->sceneGraphMatch();
			if( !( sceneGraphMatch & ( IECore::PathMatcher::ExactMatch | IECore::PathMatcher::DescendantMatch ) ) )
			{
				m_sceneGraph->clear();
				return nullptr;
			}

			if( m_sceneGraph->cleared() )
			{
				// We cleared this location in the past, but now
				// want it. So we need to start from scratch, and
				// update everything.
				m_dirtyComponents = SceneGraph::AllComponents;
			}

			// Set up a context to compute the scene at the right
			// location.

			ScenePlug::PathScope pathScope( m_context, m_scenePath );

			// Update the scene graph at this location.

			unsigned changedComponents = m_sceneGraph->update(
				scene(),
				m_scenePath,
				m_dirtyComponents,
				m_changedParentComponents,
				sceneGraphMatch & IECore::PathMatcher::ExactMatch ? m_sceneGraphType : SceneGraph::NoType,
				m_interactiveRender->m_renderer.get(),
				m_interactiveRender->m_globals.get(),
				m_interactiveRender->m_renderSets
			);

			// Spawn subtasks to apply updates to each child.

			const std::vector<SceneGraph *> &children = m_sceneGraph->children();
			if( children.size() )
			{
				set_ref_count( 1 + children.size() );

				ScenePlug::ScenePath childPath = m_scenePath;
				childPath.push_back( IECore::InternedString() ); // space for the child name
				for( std::vector<SceneGraph *>::const_iterator it = children.begin(), eIt = children.end(); it != eIt; ++it )
				{
					childPath.back() = (*it)->name();
					SceneGraphUpdateTask *t = new( allocate_child() ) SceneGraphUpdateTask( m_interactiveRender, *it, m_sceneGraphType, m_dirtyComponents, changedComponents, m_context, childPath );
					spawn( *t );
				}

				wait_for_all();
			}

			return nullptr;
		}

	private :

		const ScenePlug *scene()
		{
			return m_interactiveRender->adaptedInPlug();
		}

		/// \todo Fast path for when sets were not dirtied.
		const unsigned sceneGraphMatch() const
		{
			switch( m_sceneGraphType )
			{
				case SceneGraph::CameraType :
					return m_interactiveRender->m_renderSets.camerasSet().match( m_scenePath );
				case SceneGraph::LightType :
					return m_interactiveRender->m_renderSets.lightsSet().match( m_scenePath );
				case SceneGraph::ObjectType :
				{
					unsigned m = m_interactiveRender->m_renderSets.lightsSet().match( m_scenePath ) |
					             m_interactiveRender->m_renderSets.camerasSet().match( m_scenePath );
					if( m & IECore::PathMatcher::ExactMatch )
					{
						return IECore::PathMatcher::AncestorMatch | IECore::PathMatcher::DescendantMatch;
					}
					else
					{
						return IECore::PathMatcher::EveryMatch;
					}
				}
				default :
					return IECore::PathMatcher::NoMatch;
			}
		}

		const InteractiveRender *m_interactiveRender;
		SceneGraph *m_sceneGraph;
		SceneGraph::Type m_sceneGraphType;
		unsigned m_dirtyComponents;
		unsigned m_changedParentComponents;
		const Context *m_context;
		ScenePlug::ScenePath m_scenePath;

};

//////////////////////////////////////////////////////////////////////////
// InteractiveRender
//////////////////////////////////////////////////////////////////////////

size_t InteractiveRender::g_firstPlugIndex = 0;

IE_CORE_DEFINERUNTIMETYPED( InteractiveRender );

InteractiveRender::InteractiveRender( const std::string &name )
	:	InteractiveRender( /* rendererType = */ InternedString(), name )
{
}

InteractiveRender::InteractiveRender( const IECore::InternedString &rendererType, const std::string &name )
	:	Node( name )
{
	storeIndexOfNextChild( g_firstPlugIndex );
	addChild( new ScenePlug( "in" ) );
	addChild( new StringPlug( rendererType.string().empty() ? "renderer" : "__renderer", Plug::In, rendererType.string() ) );
	addChild( new IntPlug( "state", Plug::In, Stopped, Stopped, Paused, Plug::Default & ~Plug::Serialisable ) );
	addChild( new ScenePlug( "out", Plug::Out, Plug::Default & ~Plug::Serialisable ) );
	addChild( new ScenePlug( "__adaptedIn", Plug::In, Plug::Default & ~Plug::Serialisable ) );

	SceneProcessorPtr adaptors = RendererAlgo::createAdaptors();
	setChild( "__adaptors", adaptors );
	adaptors->inPlug()->setInput( inPlug() );
	adaptedInPlug()->setInput( adaptors->outPlug() );

	outPlug()->setInput( inPlug() );

	plugDirtiedSignal().connect( boost::bind( &InteractiveRender::plugDirtied, this, ::_1 ) );

	stop(); // Use stop to initialise remaining member variables
}

InteractiveRender::~InteractiveRender()
{
	stop();
}

ScenePlug *InteractiveRender::inPlug()
{
	return getChild<ScenePlug>( g_firstPlugIndex );
}

const ScenePlug *InteractiveRender::inPlug() const
{
	return getChild<ScenePlug>( g_firstPlugIndex );
}

Gaffer::StringPlug *InteractiveRender::rendererPlug()
{
	return getChild<StringPlug>( g_firstPlugIndex + 1 );
}

const Gaffer::StringPlug *InteractiveRender::rendererPlug() const
{
	return getChild<StringPlug>( g_firstPlugIndex + 1 );
}

Gaffer::IntPlug *InteractiveRender::statePlug()
{
	return getChild<IntPlug>( g_firstPlugIndex + 2 );
}

const Gaffer::IntPlug *InteractiveRender::statePlug() const
{
	return getChild<IntPlug>( g_firstPlugIndex + 2 );
}

ScenePlug *InteractiveRender::outPlug()
{
	return getChild<ScenePlug>( g_firstPlugIndex + 3 );
}

const ScenePlug *InteractiveRender::outPlug() const
{
	return getChild<ScenePlug>( g_firstPlugIndex + 3 );
}

ScenePlug *InteractiveRender::adaptedInPlug()
{
	return getChild<ScenePlug>( g_firstPlugIndex + 4 );
}

const ScenePlug *InteractiveRender::adaptedInPlug() const
{
	return getChild<ScenePlug>( g_firstPlugIndex + 4 );
}

Gaffer::Context *InteractiveRender::getContext()
{
	return m_context.get();
}

const Gaffer::Context *InteractiveRender::getContext() const
{
	return m_context.get();
}

void InteractiveRender::setContext( Gaffer::ContextPtr context )
{
	if( m_context == context )
	{
		return;
	}

	m_context = context;
	m_dirtyComponents = SceneGraph::AllComponents;
	update();
}

void InteractiveRender::plugDirtied( const Gaffer::Plug *plug )
{

	if( plug == adaptedInPlug()->boundPlug() )
	{
		m_dirtyComponents |= SceneGraph::BoundComponent;
	}
	else if( plug == adaptedInPlug()->transformPlug() )
	{
		m_dirtyComponents |= SceneGraph::TransformComponent;
	}
	else if( plug == adaptedInPlug()->attributesPlug() )
	{
		m_dirtyComponents |= SceneGraph::AttributesComponent;
	}
	else if( plug == adaptedInPlug()->objectPlug() )
	{
		m_dirtyComponents |= SceneGraph::ObjectComponent;
	}
	else if( plug == adaptedInPlug()->childNamesPlug() )
	{
		m_dirtyComponents |= SceneGraph::ChildNamesComponent;
	}
	else if( plug == adaptedInPlug()->globalsPlug() )
	{
		m_dirtyComponents |= SceneGraph::GlobalsComponent;
	}
	else if( plug == adaptedInPlug()->setPlug() )
	{
		m_dirtyComponents |= SceneGraph::SetsComponent;
	}
	else if( plug == rendererPlug() )
	{
		stop();
		m_dirtyComponents = SceneGraph::AllComponents;
	}

	if( plug == adaptedInPlug() ||
	    plug == statePlug()
	)
	{
		try
		{
			update();
		}
		catch( const std::exception &e )
		{
			errorSignal()( plug, plug, e.what() );
		}
	}
}

void InteractiveRender::contextChanged( const IECore::InternedString &name )
{
	if( boost::starts_with( name.string(), "ui:" ) )
	{
		return;
	}
	m_dirtyComponents = SceneGraph::AllComponents;
	update();
}

void InteractiveRender::update()
{
	const std::string rendererName = rendererPlug()->getValue();

	updateEffectiveContext();
	ContextPtr context = new Context( *m_effectiveContext );
	context->set( g_rendererContextName, rendererName );
	Context::Scope scopedContext( context.get() );

	const State requiredState = (State)statePlug()->getValue();

	// Stop the current render if we've been asked to, or if
	// there is no real input scene.

	if( requiredState == Stopped || !runTimeCast<SceneNode>( inPlug()->source()->node() ) )
	{
		stop();
		return;
	}

	// If we've got this far, we know we want to be running or paused.
	// Start a render if we don't have one.

	if( !m_renderer )
	{
		m_renderer = IECoreScenePreview::Renderer::create(
			rendererName,
			IECoreScenePreview::Renderer::Interactive
		);
	}

	// We need to pause to make edits, even if we want to
	// be running in the end.
	m_renderer->pause();
	if( requiredState == Paused )
	{
		m_state = requiredState;
		return;
	}

	// We want to be running, so update the globals
	// and the scene graph, and kick off a render.
	assert( requiredState == Running );

	bool cameraGlobalsChanged = false;
	if( m_dirtyComponents & SceneGraph::GlobalsComponent )
	{
		ConstCompoundObjectPtr globals = adaptedInPlug()->globalsPlug()->getValue();
		RendererAlgo::outputOptions( globals.get(), m_globals.get(), m_renderer.get() );
		RendererAlgo::outputOutputs( globals.get(), m_globals.get(), m_renderer.get() );
		cameraGlobalsChanged = ::cameraGlobalsChanged( globals.get(), m_globals.get() );
		m_globals = globals;
	}

	if( m_dirtyComponents & SceneGraph::SetsComponent )
	{
		if( m_renderSets.update( adaptedInPlug() ) & RendererAlgo::RenderSets::RenderSetsChanged )
		{
			m_dirtyComponents |= SceneGraph::RenderSetsComponent;
		}
	}

	for( int i = SceneGraph::FirstType; i <= SceneGraph::LastType; ++i )
	{
		SceneGraph *sceneGraph = m_sceneGraphs[i].get();
		if( i == SceneGraph::CameraType && cameraGlobalsChanged )
		{
			// Because the globals are applied to camera objects, we must update the object whenever
			// the globals have changed, so we clear the scene graph and start again.
			sceneGraph->clear();
		}
		SceneGraphUpdateTask *task = new( tbb::task::allocate_root() ) SceneGraphUpdateTask( this, sceneGraph, (SceneGraph::Type)i, m_dirtyComponents, SceneGraph::NoComponent, context.get(), ScenePlug::ScenePath() );
		tbb::task::spawn_root_and_wait( *task );
	}

	if( cameraGlobalsChanged )
	{
		updateDefaultCamera();
	}

	m_dirtyComponents = SceneGraph::NoComponent;
	m_state = requiredState;

	m_renderer->render();
}

void InteractiveRender::updateEffectiveContext()
{
	if( m_context )
	{
		if( m_effectiveContext == m_context )
		{
			return;
		}
		m_effectiveContext = m_context;
	}
	else if( ScriptNode *n = ancestor<ScriptNode>() )
	{
		if( m_effectiveContext == n->context() )
		{
			return;
		}
		m_effectiveContext = n->context();
	}
	else
	{
		m_effectiveContext = new Context();
	}

	m_contextChangedConnection = m_effectiveContext->changedSignal().connect(
		boost::bind( &InteractiveRender::contextChanged, this, ::_2 )
	);
}

void InteractiveRender::updateDefaultCamera()
{
	const StringData *cameraOption = m_globals->member<StringData>( g_cameraGlobalName );
	m_defaultCamera = nullptr;
	if( cameraOption && !cameraOption->readable().empty() )
	{
		return;
	}

	CameraPtr defaultCamera = new IECoreScene::Camera;
	RendererAlgo::applyCameraGlobals( defaultCamera.get(), m_globals.get() );
	IECoreScenePreview::Renderer::AttributesInterfacePtr defaultAttributes = m_renderer->attributes( adaptedInPlug()->attributesPlug()->defaultValue() );
	ConstStringDataPtr name = new StringData( "gaffer:defaultCamera" );
	m_defaultCamera = m_renderer->camera( name->readable(), defaultCamera.get(), defaultAttributes.get() );
	m_renderer->option( "camera", name.get() );
}

void InteractiveRender::stop()
{
	if( m_renderer )
	{
		m_renderer->pause();
	}

	m_sceneGraphs.clear();
	for( int i = SceneGraph::FirstType; i <= SceneGraph::LastType; ++i )
	{
		m_sceneGraphs.push_back( unique_ptr<SceneGraph>( new SceneGraph ) );
	}
	m_defaultCamera = nullptr;
	m_renderer = nullptr;

	m_globals = adaptedInPlug()->globalsPlug()->defaultValue();
	m_renderSets.clear();

	m_dirtyComponents = SceneGraph::AllComponents;
	m_state = Stopped;
}


text:
package com.andydennie.countrypicker;

public class Country {
	private String code;
	private String name;

    public Country(String code, String name) {
        this.code = code;
        this.name = name;
    }

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public boolean hasAdministrativeDivisions() {
        return code.equals("US");
    }

}

redpajama_set_name: RedPajamaGithub


text:
module PNM where

import qualified Data.ByteString.Lazy.Char8 as L8
import qualified Data.ByteString.Lazy as L
import Data.Char (isSpace)

data Greymap = Greymap {
  greyWidth :: Int
  , greyHeight :: Int
  , greyMax :: Int
  , greyData :: L.ByteString
  } deriving (Eq)

instance Show Greymap where
  show (Greymap w h m _) = "Greymap " ++ show w ++ "x" ++ show h ++ " " ++ show m

parseP5 :: L.ByteString -> Maybe (Greymap, L.ByteString)
parseP5 s =
  case matchHeader (L8.pack "P5") s of
    Nothing -> Nothing
    Just s1 ->
      case getNat s1 of
        Nothing -> Nothing
        Just (width, s2) ->
          case getNat (L8.dropWhile isSpace s2) of
            Nothing -> Nothing
            Just (height, s3) ->
              case getNat (L8.dropWhile isSpace s3) of
                Nothing -> Nothing
                Just (maxGrey, s4)
                  | maxGrey > 255 -> Nothing
                  | otherwise ->
                    case getBytes 1 s4 of
                      Nothing -> Nothing
                      Just (_, s5) ->
                        case getBytes (width * height) s5 of
                          Nothing -> Nothing
                          Just (bitmap, s6) ->
                            Just (Greymap width height maxGrey bitmap, s6)

matchHeader :: L.ByteString -> L.ByteString -> Maybe L.ByteString
matchHeader prefix str
  | prefix `L8.isPrefixOf` str = Just (L8.dropWhile isSpace (L.drop (L.length prefix) str))
  | otherwise = Nothing

getNat :: L.ByteString -> Maybe (Int, L.ByteString)
getNat s = case L8.readInt s of
  Nothing -> Nothing
  Just (num, rest)
    | num <= 0 -> Nothing
    | otherwise -> Just (fromIntegral num, rest)

getBytes :: Int -> L.ByteString -> Maybe (L.ByteString, L.ByteString)
getBytes n str = let count = fromIntegral n
                     both@(prefix, _) = L.splitAt count str
                 in if L.length prefix < count
                    then Nothing
                    else Just both

(>>?) :: Maybe a -> (a -> Maybe b) -> Maybe b
Nothing >>? _ = Nothing
(Just v) >>? f = f v

parseP5_take2 :: L.ByteString -> Maybe (Greymap, L.ByteString)
parseP5_take2 s =
  matchHeader (L8.pack "P5") s >>?
  \s -> skipSpace ((), s) >>?
  (getNat . snd) >>?
  skipSpace >>?
  \(width, s) -> getNat s >>?
  skipSpace >>?
  \(height, s) -> getNat s >>?
  \(maxGrey, s) -> getBytes 1 s >>?
  (getBytes (width * height) . snd) >>?
  \(bitmap, s) -> Just (Greymap width height maxGrey bitmap, s)

skipSpace :: (a, L.ByteString) -> Maybe (a, L.ByteString)
skipSpace (a, s) = Just (a, L8.dropWhile isSpace s)


text:
package org.apache.archiva.security;

import com.google.common.collect.Lists;
import junit.framework.TestCase;
import net.sf.ehcache.CacheManager;
import org.apache.archiva.configuration.ArchivaConfiguration;
import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
import org.apache.archiva.redback.rbac.RBACManager;
import org.apache.archiva.redback.rbac.RbacObjectNotFoundException;
import org.apache.archiva.redback.rbac.UserAssignment;
import org.apache.archiva.redback.role.RoleManager;
import org.apache.archiva.redback.system.SecuritySystem;
import org.apache.archiva.redback.users.User;
import org.apache.archiva.redback.users.UserManager;
import org.apache.archiva.redback.users.UserManagerException;
import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.security.common.ArchivaRoleConstants;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;

import javax.inject.Inject;
import javax.inject.Named;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * AbstractSecurityTest
 */
@RunWith(ArchivaSpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context.xml" })
public abstract class AbstractSecurityTest
    extends TestCase
{

    protected Logger log = LoggerFactory.getLogger( getClass() );

    protected static final String USER_GUEST = "guest";

    protected static final String USER_ADMIN = "admin";

    protected static final String USER_ALPACA = "alpaca";

    @Inject
    @Named(value = "securitySystem#testable")
    protected SecuritySystem securitySystem;

    @Inject
    @Named(value = "rbacManager#memory")
    protected RBACManager rbacManager;

    @Inject
    protected RoleManager roleManager;

    @Inject
    @Named(value = "archivaConfiguration#default")
    private ArchivaConfiguration archivaConfiguration;

    @Inject
    private RepositoryRegistry repositoryRegistry;

    @Inject
    protected UserRepositories userRepos;

    protected void setupRepository( String repoId )
        throws Exception
    {
        // Add repo to configuration.
        ManagedRepositoryConfiguration repoConfig = new ManagedRepositoryConfiguration();
        repoConfig.setId( repoId );
        repoConfig.setName( "Testable repo <" + repoId + ">" );
        repoConfig.setLocation( Paths.get( "target/test-repo/" + repoId ).toString() );
        if ( !archivaConfiguration.getConfiguration().getManagedRepositoriesAsMap().containsKey( repoId ) )
        {
            repositoryRegistry.putRepository( repoConfig );
        }

        // Add repo roles to security.
        userRepos.createMissingRepositoryRoles( repoId );
    }

    protected void assignRepositoryObserverRole( String principal, String repoId )
        throws Exception
    {
        roleManager.assignTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, repoId, principal );
    }

    protected User createUser( String principal, String fullname )
        throws UserManagerException
    {
        UserManager userManager = securitySystem.getUserManager();

        User user = userManager.createUser( principal, fullname, principal + "@testable.archiva.apache.org" );
        securitySystem.getPolicy().setEnabled( false );
        userManager.addUser( user );
        securitySystem.getPolicy().setEnabled( true );

        return user;
    }

    @Override
    @Before
    public void setUp()
        throws Exception
    {
        super.setUp();

        Path srcConfig = Paths.get( "src/test/resources/repository-archiva.xml" );
        Path destConfig = Paths.get( "target/test-conf/archiva.xml" );

        Files.createDirectories(destConfig.getParent());
        Files.deleteIfExists(destConfig);

        FileUtils.copyFile( srcConfig.toFile(), destConfig.toFile() );

        // Some basic asserts.
        assertNotNull( securitySystem );
        assertNotNull( rbacManager );
        assertNotNull( roleManager );
        assertNotNull( userRepos );
        assertNotNull( archivaConfiguration );

        // Setup Admin User.
        User adminUser = createUser( USER_ADMIN, "Admin User" );
        roleManager.assignRole( ArchivaRoleConstants.TEMPLATE_SYSTEM_ADMIN, adminUser.getUsername() );

        // Setup Guest User.
        User guestUser = createUser( USER_GUEST, "Guest User" );
        roleManager.assignRole( ArchivaRoleConstants.TEMPLATE_GUEST, guestUser.getUsername() );

        repositoryRegistry.setArchivaConfiguration(archivaConfiguration);
        repositoryRegistry.reload();
    }

    protected void restoreGuestInitialValues( String userId )
        throws Exception
    {
        UserAssignment userAssignment = null;
        try
        {
            userAssignment = rbacManager.getUserAssignment( userId );
        }
        catch ( RbacObjectNotFoundException e )
        {
            log.info( "ignore RbacObjectNotFoundException for id {} during restoreGuestInitialValues", userId );
            return;
        }
        userAssignment.setRoleNames( Lists.newArrayList( "Guest" ) );
        rbacManager.saveUserAssignment( userAssignment );
        CacheManager.getInstance().clearAll();
    }
}


text:
package com.go.tea.parsetree;

import java.util.LinkedList;
import com.go.tea.compiler.SourceInfo;
import com.go.tea.compiler.Type;

/******************************************************************************
 * A ParenExpression is a thin wrapper around an Expression that was
 * delimited by parenthesis in the source code. A parse tree does not
 * necessarily need a ParenExpression, but it is useful when reconstructing
 * something that resembles the source code.
 *
 * @author Brian S O'Neill
 * @version
 * <!--$$Revision:--> 28 <!-- $-->, <!--$$JustDate:--> 01/02/01 <!-- $-->
 */
public class ParenExpression extends Expression {
    private Expression mExpr;

    public ParenExpression(SourceInfo info, Expression expr) {
        super(info);
        mExpr = expr;
    }

    public Object accept(NodeVisitor visitor) {
        return visitor.visit(this);
    }

    public Object clone() {
        ParenExpression pe = (ParenExpression)super.clone();
        pe.mExpr = (Expression)mExpr.clone();
        return pe;
    }

    public boolean isExceptionPossible() {
        return super.isExceptionPossible() ||
            (mExpr != null && mExpr.isExceptionPossible());
    }

    public Type getType() {
        return mExpr.getType();
    }

    public Type getInitialType() {
        return mExpr.getInitialType();
    }

    public void convertTo(Type toType, boolean preferCast) {
        mExpr.convertTo(toType, preferCast);
    }

    public LinkedList getConversionChain() {
        return mExpr.getConversionChain();
    }

    public void setType(Type type) {
        mExpr.setType(type);
    }

    public void setInitialType(Type type) {
        mExpr.setInitialType(type);
    }

    public boolean isValueKnown() {
        return mExpr.isValueKnown();
    }

    public Object getValue() {
        return mExpr.getValue();
    }

    public Expression getExpression() {
        return mExpr;
    }

    public void setExpression(Expression expr) {
        mExpr = expr;
    }
}


text:
package org.apache.nifi.hbase;

import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.controller.ControllerService;
import org.apache.nifi.hbase.put.PutColumn;
import org.apache.nifi.hbase.put.PutFlowFile;
import org.apache.nifi.hbase.scan.Column;
import org.apache.nifi.hbase.scan.ResultHandler;

import java.io.IOException;
import java.util.Collection;
import java.util.List;

@Tags({"hbase", "client"})
@CapabilityDescription("A controller service for accessing an HBase client.")
public interface HBaseClientService extends ControllerService {

    /**
     * Puts a batch of mutations to the given table.
     *
     * @param tableName the name of an HBase table
     * @param puts a list of put mutations for the given table
     * @throws IOException thrown when there are communication errors with HBase
     */
    void put(String tableName, Collection<PutFlowFile> puts) throws IOException;

    /**
     * Puts the given row to HBase with the provided columns.
     *
     * @param tableName the name of an HBase table
     * @param rowId the id of the row to put
     * @param columns the columns of the row to put
     * @throws IOException thrown when there are communication errors with HBase
     */
    void put(String tableName, byte[] rowId, Collection<PutColumn> columns) throws IOException;

    /**
     * Atomically checks if a row/family/qualifier value matches the expected value. If it does, then the Put is added to HBase.
     *
     * @param tableName the name of an HBase table
     * @param rowId the id of the row to check
     * @param family the family of the row to check
     * @param qualifier the qualifier of the row to check
     * @param value the value of the row to check. If null, the check is for the lack of column (ie: non-existence)
     * @return True if the Put was executed, false otherwise
     * @throws IOException thrown when there are communication errors with HBase$
     */
    boolean checkAndPut(String tableName, byte[] rowId, byte[] family, byte[] qualifier, byte[] value, PutColumn column) throws IOException;

    /**
     * Deletes the given row on HBase. All cells are deleted.
     *
     * @param tableName the name of an HBase table
     * @param rowId the id of the row to delete
     * @throws IOException thrown when there are communication errors with HBase
     */
    void delete(String tableName, byte[] rowId) throws IOException;

    /**
     * Deletes the given row on HBase. Uses the supplied visibility label for all cells in the delete.
     * It will fail if HBase cannot delete a cell because the visibility label on the cell does not match the specified
     * label.
     *
     * @param tableName the name of an HBase table
     * @param rowId the id of the row to delete
     * @param visibilityLabel a visibility label to apply to the delete
     * @throws IOException thrown when there are communication errors with HBase
     */
    void delete(String tableName, byte[] rowId, String visibilityLabel) throws IOException;

    /**
     * Deletes a list of rows in HBase. All cells are deleted.
     *
     * @param tableName the name of an HBase table
     * @param rowIds a list of rowIds to send in a batch delete
     */

    void delete(String tableName, List<byte[]> rowIds) throws IOException;

    /**
     * Deletes a list of cells from HBase. This is intended to be used with granular delete operations.
     *
     * @param tableName the name of an HBase table.
     * @param deletes a list of DeleteRequest objects.
     * @throws IOException thrown when there are communication errors with HBase
     */
    void deleteCells(String tableName, List<DeleteRequest> deletes) throws IOException;

    /**
     * Deletes a list of rows in HBase. All cells that match the visibility label are deleted.
     *
     * @param tableName the name of an HBase table
     * @param rowIds a list of rowIds to send in a batch delete
     * @param visibilityLabel a visibility label expression
     */

    void delete(String tableName, List<byte[]> rowIds, String visibilityLabel) throws IOException;

    /**
     * Scans the given table using the optional filter criteria and passing each result to the provided handler.
     *
     * @param tableName the name of an HBase table to scan
     * @param columns optional columns to return, if not specified all columns are returned
     * @param filterExpression optional filter expression, if not specified no filtering is performed
     * @param minTime the minimum timestamp of cells to return, passed to the HBase scanner timeRange
     * @param handler a handler to process rows of the result set
     * @throws IOException thrown when there are communication errors with HBase
     */
    void scan(String tableName, Collection<Column> columns, String filterExpression, long minTime, ResultHandler handler) throws IOException;

    /**
     * Scans the given table using the optional filter criteria and passing each result to the provided handler.
     *
     * @param tableName the name of an HBase table to scan
     * @param columns optional columns to return, if not specified all columns are returned
     * @param filterExpression optional filter expression, if not specified no filtering is performed
     * @param minTime the minimum timestamp of cells to return, passed to the HBase scanner timeRange
     * @param authorizations the visibility labels to apply to the scanner.
     * @param handler a handler to process rows of the result set
     * @throws IOException thrown when there are communication errors with HBase
     */
    void scan(String tableName, Collection<Column> columns, String filterExpression, long minTime, List<String> authorizations, ResultHandler handler) throws IOException;

    /**
     * Scans the given table for the given rowId and passes the result to the handler.
     *
     * @param tableName the name of an HBase table to scan
     * @param startRow the row identifier to start scanning at
     * @param endRow the row identifier to end scanning at
     * @param columns optional columns to return, if not specified all columns are returned
     * @param handler a handler to process rows of the result
     * @throws IOException thrown when there are communication errors with HBase
     */
    void scan(String tableName, byte[] startRow, byte[] endRow, Collection<Column> columns, List<String> authorizations, ResultHandler handler) throws IOException;

    /**
     * Scans the given table for the given range of row keys or time rage and passes the result to a handler.<br/>
     *
     * @param tableName the name of an HBase table to scan
     * @param startRow the row identifier to start scanning at
     * @param endRow the row identifier to end scanning at
     * @param filterExpression  optional filter expression, if not specified no filtering is performed
     * @param timerangeMin the minimum timestamp of cells to return, passed to the HBase scanner timeRange
     * @param timerangeMax the maximum timestamp of cells to return, passed to the HBase scanner timeRange
     * @param limitRows the maximum number of rows to be returned by scanner
     * @param isReversed whether this scan is a reversed one.
     * @param blockCache set to use the block cache option of hbase scan.
     * @param columns optional columns to return, if not specified all columns are returned
     * @param authorizations optional list of visibility labels that the user should be able to see when communicating with HBase
     * @param handler a handler to process rows of the result
     */
    void scan(String tableName, String startRow, String endRow, String filterExpression, Long timerangeMin, Long timerangeMax, Integer limitRows,
            Boolean isReversed, Boolean blockCache, Collection<Column> columns, List<String> authorizations, ResultHandler handler) throws IOException;

    /**
     * Converts the given boolean to it's byte representation.
     *
     * @param b a boolean
     * @return the boolean represented as bytes
     */
    byte[] toBytes(boolean b);

    /**
     * Converts the given float to its byte representation.
     *
     * @param f a float
     * @return the float represented as bytes
     */
    byte[] toBytes(float f);

    /**
     * Converts the given float to its byte representation.
     *
     * @param i an int
     * @return the int represented as bytes
     */
    byte[] toBytes(int i);

    /**
     * Converts the given long to it's byte representation.
     *
     * @param l a long
     * @return the long represented as bytes
     */
    byte[] toBytes(long l);

    /**
     * Converts the given double to it's byte representation.
     *
     * @param d a double
     * @return the double represented as bytes
     */
    byte[] toBytes(double d);

    /**
     * Converts the given string to it's byte representation.
     *
     * @param s a string
     * @return the string represented as bytes
     */
    byte[] toBytes(String s);

    /**
     * Converts the given binary formatted string to a byte representation
     * @param s a binary encoded string
     * @return the string represented as bytes
     */
    byte[] toBytesBinary(String s);

    /**
     * Create a transit URI from the current configuration and the specified table name.
     * The default implementation just prepend "hbase://" to the table name and row key, i.e. "hbase://tableName/rowKey".
     * @param tableName The name of a HBase table
     * @param rowKey The target HBase row key, this can be null or empty string if the operation is not targeted to a specific row
     * @return a qualified transit URI which can identify a HBase table row in a HBase cluster
     */
    default String toTransitUri(String tableName, String rowKey) {
        return "hbase://" + tableName + (rowKey != null && !rowKey.isEmpty() ? "/" + rowKey : "");
    }

}


text: Mabetle Go CMD


text:
package edu.wpi.rail.jrosbridge.messages.std;

import static org.junit.Assert.*;

import javax.json.Json;
import javax.json.JsonObject;

import org.junit.Before;
import org.junit.Test;

import edu.wpi.rail.jrosbridge.messages.Message;

public class TestInt16 {

	private Int16 empty, i1;

	@Before
	public void setUp() {
		empty = new Int16();
		i1 = new Int16((short) 127);
	}

	@Test
	public void testConstructor() {
		assertEquals((short) 0, empty.getData());

		assertEquals("{\"data\":0}", empty.toString());

		assertEquals(1, empty.toJsonObject().size());
		assertEquals(0, empty.toJsonObject().getInt(Int16.FIELD_DATA));

		assertEquals(Int16.TYPE, empty.getMessageType());
	}

	@Test
	public void testShortConstructor() {
		assertEquals((short) 127, i1.getData());

		assertEquals("{\"data\":127}", i1.toString());

		assertEquals(1, i1.toJsonObject().size());
		assertEquals(127, i1.toJsonObject().getInt(Int16.FIELD_DATA));

		assertEquals(Int16.TYPE, i1.getMessageType());
	}

	@Test
	public void testHashCode() {
		assertEquals(empty.toString().hashCode(), empty.hashCode());
		assertEquals(i1.toString().hashCode(), i1.hashCode());
	}

	@Test
	public void testEquals() {
		assertFalse(empty.equals(i1));
		assertFalse(i1.equals(empty));

		assertTrue(empty.equals(empty));
		assertTrue(i1.equals(i1));
	}

	@Test
	public void testEqualsWrongObject() {
		assertFalse(empty.equals(new String(empty.toString())));
	}

	@Test
	public void testClone() {
		Int16 clone = i1.clone();
		assertEquals(i1.toString(), clone.toString());
		assertEquals(i1.toJsonObject(), clone.toJsonObject());
		assertEquals(i1.getMessageType(), clone.getMessageType());
		assertEquals(i1.getData(), clone.getData());
		assertNotSame(i1, clone);
		assertNotSame(i1.toString(), clone.toString());
		assertNotSame(i1.toJsonObject(), clone.toJsonObject());
	}

	@Test
	public void testFromJsonString() {
		Int16 data = Int16.fromJsonString(i1.toString());
		assertEquals(i1.toString(), data.toString());
		assertEquals(i1.toJsonObject(), data.toJsonObject());
		assertEquals(i1.getMessageType(), data.getMessageType());
		assertEquals(i1.getData(), data.getData());
		assertNotSame(i1, data);
		assertNotSame(i1.toString(), data.toString());
		assertNotSame(i1.toJsonObject(), data.toJsonObject());
	}

	@Test
	public void testFromMessage() {
		Message m = new Message(i1.toString());
		Int16 data = Int16.fromMessage(m);
		assertEquals(i1.toString(), data.toString());
		assertEquals(i1.toJsonObject(), data.toJsonObject());
		assertEquals(i1.getMessageType(), data.getMessageType());
		assertEquals(i1.getData(), data.getData());
		assertNotSame(i1, data);
		assertNotSame(i1.toString(), data.toString());
		assertNotSame(i1.toJsonObject(), data.toJsonObject());
	}

	@Test
	public void testFromJsonObject() {
		JsonObject jsonObject = Json.createObjectBuilder()
				.add(Int16.FIELD_DATA, i1.getData()).build();
		Int16 data = Int16.fromJsonObject(jsonObject);
		assertEquals(i1.toString(), data.toString());
		assertEquals(i1.toJsonObject(), data.toJsonObject());
		assertEquals(i1.getMessageType(), data.getMessageType());
		assertEquals(i1.getData(), data.getData());
		assertNotSame(i1, data);
		assertNotSame(i1.toString(), data.toString());
		assertNotSame(i1.toJsonObject(), data.toJsonObject());
	}

	@Test
	public void testFromJsonObjectNoData() {
		JsonObject jsonObject = Json.createObjectBuilder().build();
		Int16 data = Int16.fromJsonObject(jsonObject);
		assertEquals((short) 0, data.getData());
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2017 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd"
       default-lazy-init="true" default-autowire="byName">

    <bean id="testDataSourceFactory" class="com.evolveum.midpoint.repo.sql.DataSourceFactory" destroy-method="destroy">
        <property name="configuration" value="#{testSqlRepositoryFactory.sqlConfiguration}"/>
    </bean>

    <bean id="testDataSource" factory-bean="testDataSourceFactory" factory-method="createDataSource"
          depends-on="testDataSourceFactory"/>

    <!-- Proxied data source used to collect SQL statements -->

    <bean id="proxiedTestDataSource" primary="true" class="net.ttddyy.dsproxy.support.ProxyDataSource">
        <property name="dataSource" ref="testDataSource"/>
        <property name="proxyConfig" ref="proxyConfig"/>
    </bean>

    <bean id="proxyConfig"
          factory-bean="proxyConfigSupport"
          factory-method="create"/>

    <bean id="proxyConfigSupport" class="net.ttddyy.dsproxy.support.ProxyConfigSpringXmlSupport">
        <property name="dataSourceName" value="my-ds"/>
        <property name="queryListener" ref="queryChainListener"/>        <!-- this is bound to be ChainListener (unfortunately) -->
<!--        <property name="methodListener" ref="methodListener"/>-->
    </bean>

    <bean id="queryChainListener" class="net.ttddyy.dsproxy.listener.ChainListener">
        <property name="listeners">
            <list>
                <ref bean="testQueryListener"/>
            </list>
        </property>
    </bean>

    <!-- We don't need this (under normal circumstances) -->
<!--    <bean id="methodListener" class="net.ttddyy.dsproxy.listener.CompositeMethodListener">-->
<!--        <property name="listeners">-->
<!--            <list>-->
<!--                <bean class="net.ttddyy.dsproxy.listener.TracingMethodListener"/>-->
<!--            </list>-->
<!--        </property>-->
<!--    </bean>-->

    <!-- Hibernate session factory -->
    <bean id="testSessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
          depends-on="proxiedTestDataSource" lazy-init="true">

        <property name="dataSource" ref="proxiedTestDataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">#{testSqlRepositoryFactory.sqlConfiguration.hibernateDialect}</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.hbm2ddl.auto">#{testSqlRepositoryFactory.sqlConfiguration.hibernateHbm2ddl}</prop>
                <prop key="hibernate.id.new_generator_mappings">true</prop>
                <prop key="hibernate.jdbc.batch_size">20</prop>
                <prop key="javax.persistence.validation.mode">none</prop>
                <prop key="hibernate.transaction.coordinator_class">jdbc</prop>
                <prop key="hibernate.hql.bulk_id_strategy">org.hibernate.hql.spi.id.inline.InlineIdsOrClauseBulkIdStrategy</prop>
                <prop key="hibernate.session_factory.statement_inspector">com.evolveum.midpoint.repo.sql.testing.TestStatementInspector</prop>
                <!-- Todo implement strategy that will not do select when where clause contains only equals on primary key -->
                <!--<prop key="hibernate.hql.bulk_id_strategy">com.evolveum.midpoint.repo.sql.util.EmptyMultiTableBulkIdStrategy</prop>-->
            </props>
        </property>
        <property name="implicitNamingStrategy">
            <bean class="com.evolveum.midpoint.repo.sql.util.MidPointImplicitNamingStrategy"/>
        </property>
        <property name="physicalNamingStrategy">
            <bean class="com.evolveum.midpoint.repo.sql.util.MidPointPhysicalNamingStrategy"/>
        </property>
        <property name="annotatedPackages">
            <list>
                <value>com.evolveum.midpoint.repo.sql.type</value>
            </list>
        </property>
        <property name="packagesToScan">
            <list>
                <value>com.evolveum.midpoint.repo.sql.data.common</value>
                <value>com.evolveum.midpoint.repo.sql.data.common.any</value>
                <value>com.evolveum.midpoint.repo.sql.data.common.container</value>
                <value>com.evolveum.midpoint.repo.sql.data.common.embedded</value>
                <value>com.evolveum.midpoint.repo.sql.data.common.enums</value>
                <value>com.evolveum.midpoint.repo.sql.data.common.id</value>
                <value>com.evolveum.midpoint.repo.sql.data.common.other</value>
                <value>com.evolveum.midpoint.repo.sql.data.common.type</value>
                <value>com.evolveum.midpoint.repo.sql.data.audit</value>
            </list>
        </property>
        <property name="entityInterceptor">
            <ref bean="testInterceptor"/>
        </property>
    </bean>

    <context:annotation-config/>
    <context:component-scan base-package="com.evolveum.midpoint.repo.sql"/>

</beans>


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Scramble</title>

Scramble

  <audio id="pew" src="assets/pew.mp3" crossorigin="anonymous" preload="auto"></audio>
  <audio id="bomb" src="assets/bomb.mp3" crossorigin="anonymous" preload="auto"></audio>
  <audio id="explosion" src="assets/explosion.mp3" crossorigin="anonymous" preload="auto"></audio>


text:
package org.softwarewolf.gameserver.repository;

import java.util.Collection;
import java.util.List;

import org.softwarewolf.gameserver.domain.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;

public interface UserRepository extends MongoRepository<User, String> {
	User findOneById(String id);

	User findOneByUsername(String arg0);

	List<User> findByAuthorities(Collection arg0);

    /// Find by key value pair
    @Query("{?0 : ?1}")
    List<User> findAllByKeyValue(String key, Object value);

    /// Find by key and array of values
    @Query("{?0 : {$in : ?1}}")
    List<User> findAllByKeyValues(String key, Object[] value);

    List<User> deleteByUsername(String username);

    User findOneByEmail(String email);
}


text:
/**
 */
(function (cornerstoneWADOImageLoader) {

  "use strict";

  function getLutDescriptor(dataSet, tag) {
    if(!dataSet.elements[tag] || dataSet.elements[tag].length != 6) {
      return;
    }
    return [dataSet.uint16(tag, 0),dataSet.uint16(tag, 1), dataSet.uint16(tag, 2)]
  }

  function getLutData(lutDataSet, tag, lutDescriptor) {
    var lut = [];
    var lutData = lutDataSet.elements[tag];
    var numLutEntries = lutDescriptor[0];
    for (var i = 0; i < numLutEntries; i++) {
      // Output range is always unsigned
      if(lutDescriptor[2] === 16) {
        lut[i] = lutDataSet.uint16(tag, i);
      }
      else {
        lut[i] = lutDataSet.byteArray[i + lutData.dataOffset];
      }
    }
    return lut;
  }

  function populatePaletteColorLut(dataSet, imagePixelModule) {
    // return immediately if no palette lut elements
    if(!dataSet.elements['x00281101']) {
      return;
    }
    imagePixelModule.redPaletteColorLookupTableDescriptor =  getLutDescriptor(dataSet, 'x00281101');
    imagePixelModule.greenPaletteColorLookupTableDescriptor =  getLutDescriptor(dataSet, 'x00281102');
    imagePixelModule.bluePaletteColorLookupTableDescriptor =  getLutDescriptor(dataSet, 'x00281103');

    imagePixelModule.redPaletteColorLookupTableData =  getLutData(dataSet, 'x00281201', imagePixelModule.redPaletteColorLookupTableDescriptor);
    imagePixelModule.greenPaletteColorLookupTableData = getLutData(dataSet, 'x00281202', imagePixelModule.greenPaletteColorLookupTableDescriptor);
    imagePixelModule.bluePaletteColorLookupTableData = getLutData(dataSet, 'x00281203', imagePixelModule.bluePaletteColorLookupTableDescriptor);
  }

  function populateSmallestLargestPixelValues(dataSet, imagePixelModule) {
    var pixelRepresentation = dataSet.uint16('x00280103');
    if(pixelRepresentation === 0) {
      imagePixelModule.smallestPixelValue = dataSet.uint16('x00280106');
      imagePixelModule.largestPixelValue = dataSet.uint16('x00280107');
    } else {
      imagePixelModule.smallestPixelValue = dataSet.int16('x00280106');
      imagePixelModule.largestPixelValue = dataSet.int16('x00280107');
    }
  }

  function getImagePixelModule(dataSet) {

    var imagePixelModule = {
      samplesPerPixel: dataSet.uint16('x00280002'),
      photometricInterpretation: dataSet.string('x00280004'),
      rows: dataSet.uint16('x00280010'),
      columns: dataSet.uint16('x00280011'),
      bitsAllocated: dataSet.uint16('x00280100'),
      bitsStored: dataSet.uint16('x00280101'),
      highBit: dataSet.uint16('x00280102'),
      pixelRepresentation: dataSet.uint16('x00280103'),
      planarConfiguration: dataSet.uint16('x00280006'),
      pixelAspectRatio: dataSet.string('x00280034')
    };
    populateSmallestLargestPixelValues(dataSet, imagePixelModule);
    populatePaletteColorLut(dataSet, imagePixelModule);
    return imagePixelModule;

  }

  // module exports
  cornerstoneWADOImageLoader.wadouri.getImagePixelModule = getImagePixelModule

}(cornerstoneWADOImageLoader));


text:
_出於某種原因(~~有關部門~~)作者已刪除,並未找到替代。_
GFWList2PAC
===========

[![PyPI version]][PyPI]
[![Build Status]][Travis CI]
[![Coverage Status]][Coverage]

Generate fast PAC file from gfwlist. Examples: [fast mode] / [precise mode].

Fast mode: use O(1) domain lookup

Precise mode: use adblock plus engine

### Usage

    pip install gfwlist2pac

    usage: gfwlist2pac [-h] [-i GFWLIST] -f PAC -p PROXY [--user-rule USER_RULE]
                   [--precise]

    optional arguments:
      -h, --help            show this help message and exit
      -i GFWLIST, --input GFWLIST
                            path to gfwlist
      -f PAC, --file PAC    path to output pac
      -p PROXY, --proxy PROXY
                            the proxy parameter in the pac file, for example,
                            "SOCKS5 127.0.0.1:1080;"
      --user-rule USER_RULE
                            user rule file, which will be appended to gfwlist
      --precise             use adblock plus algorithm instead of O(1) lookup

### Performance

The PAC generated by GFWList2PAC is 1900x faster than SwitchySharp.

    Testing fast mode pac generated by gfwlist2pac
    avg: 0.50us

    Testing precise mode pac generated by gfwlist2pac
    avg: 1.66us

    Testing pac generated by switchysharp
    avg: 952.99us

[Build Status]:    https://img.shields.io/travis/clowwindy/gfwlist2pac/master.svg?style=flat
[Coverage Status]: http://192.81.132.184/result/gfwlist2pac
[Coverage]:        http://192.81.132.184/job/gfwlist2pac/ws/htmlcov/index.html
[Travis CI]:       https://travis-ci.org/clowwindy/gfwlist2pac
[PyPI]:            https://pypi.python.org/pypi/gfwlist2pac
[PyPI version]:    https://img.shields.io/pypi/v/gfwlist2pac.svg?style=flat
[fast mode]:       https://github.com/clowwindy/gfwlist2pac/blob/master/test/proxy.pac
[precise mode]:    https://github.com/clowwindy/gfwlist2pac/blob/master/test/proxy_abp.pac


text:
<?php

namespace OpenOrchestra\Backoffice\ValueTransformer\Strategies;

use OpenOrchestra\Backoffice\ValueTransformer\ValueTransformerInterface;

/**
 * Class DoubleToHtmlStringTransformer
 */
class DoubleToHtmlStringTransformer implements ValueTransformerInterface
{
    /**
     * @param integer|double $data
     *
     * @return string
     */
    public function transform($data)
    {
       return (string) $data;
    }

    /**
     * @param string $fieldType
     * @param mixed  $value
     *
     * @return bool
     */
    public function support($fieldType, $value)
    {
        return gettype($value) == 'double';
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'double';
    }
}


text:
package io.github.ibuildthecloud.gdapi.util;

public interface TransformationService {

    String transform(String value, String method);

    String untransform(String value);

    boolean compare(String plainText, String encrypted);

}


text:
from node.Node import Node

class DivisorNode(Node):

    def __init__(self, data):
        Node.__init__(self, data)

    def __str__(self):
        return '/'

    def compute(acc, data):
        return acc / data


text:
# note: this makefile is purely for the examples and tests
# there is no need to build the library itself.

CCFLAGS = -I include
CC = clang

ifeq ($(OS),Windows_NT)
  # note that this makefile assumes you have basic unix utilities such as unxutils
  CCFLAGS += -fms-compatibility-version=19
  CC = "C:\Program Files\LLVM\bin\clang.exe"
  EXE = .exe
else
  CCFLAGS += -g -O2 -lstdc++
endif

# add your binary here
BINARIES = \
	bin/andyzip$(EXE)

all: $(BINARIES)

clean:
	rm -f $(BINARIES)

bin/andyzip$(EXE): examples/andyzip.cpp include/andyzip/decoder.hpp
	$(CC) $(CCFLAGS) $< -o $@


text:
"use strict";

var debug = false, interval = 300;

var mysql = require('mysql');
var mysqlConfig = {
	host: process.env.VCAP_MYSQL_HOST || '127.0.0.1',
	port: parseInt(process.env.VCAP_MYSQL_PORT) || 3306,
	database: process.env.VCAP_MYSQL_PORT || 'monitoring',
	user: process.env.VCAP_MYSQL_USER || 'monitoring',
	password: process.env.VCAP_MYSQL_PASSWORD || 'monitoring'
};
function getConnection(callback) {
	var conn = mysql.createConnection(mysqlConfig);
	conn.connect(function(err) {
		if (!err)
			callback.call(this, conn);
		else
			console.error('MySQL error: ' + err.stack);
	});
}

var mailfrom = process.env.VCAP_MAIL_FROM;
var mailto = process.env.VCAP_MAIL_TO;
var mailer = require('nodemailer');
var smtp = require('nodemailer-smtp-transport');
var mailhost = process.env.VCAP_MAIL_HOST || '127.0.0.1';
var mailport = parseInt(process.env.VCAP_MAIL_PORT) || 25;
var mailtransport = mailer.createTransport(new smtp({ host: mailhost, port: mailport }));
function sendAlert(name) {
	var a = apps[name];
	console.log("Send alert for " + name);
	if (mailfrom && mailto) {
		mailtransport.sendMail({
			from: mailfrom,
			to: mailto,
			subject: 'Monitoring alert on ' + name,
			html: '
Application ' + name + ' (' + a.url + ') seems down
Status = ' + a.status + '
'
		});
	}
}

// ZZZ allow invalid SSL certificates
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

var simplicite = require('simplicite');
var nbapps, apps;

/*var Datastore = require('nedb')
var db = new Datastore({ filename: 'app.dat' });
db.loadDatabase(function (err) {
	if (!err) {
			console.log('Database loaded');
			//db.insert({ name: name, url: url, active: active }, function (err, doc) {
			//	console.log(doc);
			//});
			start();
	} else console.log(err);
});*/
start();

function monitorApp(name, callback) {
	if (!apps[name].session && apps[name].active === '1') {
		apps[name].session = simplicite.session({ url: apps[name].url, debug: debug });
		apps[name].session._name = name; // ZZZ Name stored at session level to retrieve it then() functions
	}
	if (apps[name].session) {
		console.log('Request to ' + name);
		apps[name].session.getHealth().then(function(health) {
			try {
				var n = health._scope._name;
				delete health._scope; // Remove scope reference from response

				health.name = n; // Add name for health view

				// Version 3.0 compatibility tweaks
				if (typeof health.cache.grantcache === 'string') {
					var c = health.cache.grantcache.split('/');
					health.cache.grantcache = parseInt(c[0]);
					health.cache.grantcachemax = parseInt(c[1]);
				}
				if (typeof health.cache.objectcache === 'string') {
					var c = health.cache.objectcache.split('/');
					health.cache.objectcache = parseInt(c[0]);
					health.cache.objectcachemax = parseInt(c[1]);
				}
				if (typeof health.cache.processcache === 'string') {
					var c = health.cache.processcache.split('/');
					health.cache.processcache = parseInt(c[0]);
					health.cache.processcachemax = parseInt(c[1]);
				}

				apps[n].status = 200;
				apps[n].health = health;
				console.log('Response from ' + n + ' = ' + health.platform.status);

				getConnection(function(c) {
					c.query('insert into monitoring_data set ?', {
						name: n,
						ts: health.healthcheck.date,
						activesessions: health.application.activesessions,
						totalusers: health.application.totalusers,
						enabledusers: health.application.enabledusers,
						heapfree: health.javavm.heapfree,
						heapsize: health.javavm.heapsize,
						heapmaxsize: health.javavm.heapmaxsize,
						totalfreesize: health.javavm.totalfreesize,
						grantcache: health.cache.grantcache,
						grantcachemax: health.cache.grantcachemax,
						objectcache: health.cache.objectcache,
						objectcachemax: health.cache.objectcachemax,
						processcache: health.cache.processcache,
						processcachemax: health.cache.processcachemax,
						diskfree: health.disk.diskfree,
						diskusable: health.disk.diskusable,
						disktotal: health.disk.disktotal
					}, function(err) {
						if (err) console.error('MySQL error: ' + err.stack);
						c.destroy();
						if (callback) callback.call(this, name);
					});
				});
			} catch(e) {
				console.error(e);
			}
		}, function(err) {
			try {
				var n = err._scope._name;
				delete err._scope; // Remove scope reference from response
				var s = err.status || 404;
				var alert = (apps[n].status === 0 || apps[n].status === 200) && s !== 200;
				apps[n].status = s;
				if (alert) sendAlert(n); // Send alert once when status is not 200
				console.error('Error on ' + n + ' = ' + err.message);
			} catch(e) {
				console.error(e);
			}
		});
	}
}

function monitorApps() {
	for (var name in apps) monitorApp(name);
	setTimeout(monitorApps, interval * 1000);
}

function start() {
	getConnection(function(conn) {
		conn.query('select name, url, active from monitoring_app order by name', function (err, rs) {
			apps = {};
			nbapps = 0;
			if (!err) {
				nbapps = rs.length;
				for (var k = 0; k < nbapps; k++) {
					var r = rs[k];
					apps[r.name] = r;
					apps[r.name].status = 0;
				}
				monitorApps();
				conn.destroy();

				var express = require('express');
				var server = express();
				server.use(express.static(__dirname + '/public'));
				server.set('view engine', 'jade');
				server.set('views', __dirname + '/views');

				var args = process.argv.slice(2);
				var serverHost = process.env.VCAP_APP_HOST || args[0] || '127.0.0.1';
				var serverPort = process.env.VCAP_APP_PORT || args[1] || 3000;

				var basicAuth = require('basic-auth');
				var basicAuthUser = process.env.VCAP_APP_USERNAME || args[2];
				var basicAuthPass = process.env.VCAP_APP_PASSWORD || args[3];

				server.get('/', function(req, res) {
					// TODO : build data from database
					var d = [ 1, 2, 3 ];
					function render(n) {
						if (apps[n].health)
							res.render('health', { health: apps[n].health, data: d });
						else
							res.render('error', { error: 'No data for name = ' + n });
					}

					res.header('Cache-Control', 'private, no-cache, no-store, no-transform, must-revalidate');
					res.header('Expires', '-1');
					res.header('Pragma', 'no-cache');

					var credentials = basicAuth(req);
					if (basicAuthUser && basicAuthPass && (!credentials || credentials.name != basicAuthUser || credentials.pass != basicAuthPass)) {
						res.statusCode = 401;
						res.setHeader('WWW-Authenticate', 'Basic realm="Monitoring"');
						res.render('error', { error: 'Access denied' });
					} else {
						var name = req.query ? req.query.name : null;
						if (name) {
							var action = req.query.action;
							if (action === 'start' || action === 'stop') {
								var a = action === 'start' ? '1' : '0';
								getConnection(function(c) {
									console.log('Application ' + name + ', active = ' + a);
									c.query('update monitoring_app set active = \'' + a + '\' where name = \'' + name + '\'', function(err) {
										if (!err) {
											apps[name].active = a;
											apps[name].status = 0;
											delete apps[name].health;
											delete apps[name].session;
											res.render('index', { size: nbapps, rows: apps });
										} else {
											console.error('MySQL error: ' + err.stack);
											res.render('error', { error: err.message })
										}
									});
								});
							//} else if (action === 'add') {
								//getConnection(function(c) {
									//c.query('insert into monitoring_app(name, url) values (?)', { name: name, url: url }, function(err) {...});
								//});
							//} else if (action === 'del') {
								//getConnection(function(c) {
									//c.query('delete from monitoring_app where name = \'' + name + '\'', function(err) {...});
								//});
							} else { // action === 'health'
								var force = req.query ? req.query.force : null;
								if (force)
									monitorApp(name, render);
								else
									render(name);
							}
						} else
							res.render('index', { size: nbapps, rows: apps });
					}
				});

				server.listen(serverPort, serverHost);
				console.log('Server listening on ' + serverHost + ':' + serverPort);
			} else {
				console.error('MySQL error: ' + err.stack);
				res.render('error', { error: err.message })
			}
		});
	});
}

process.on('SIGINT', function() {
	console.log('Shutdown');
	process.exit();
});


text:
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_COMPILER_TYPES_H_
#define V8_COMPILER_TYPES_H_

#include "src/base/compiler-specific.h"
#include "src/conversions.h"
#include "src/globals.h"
#include "src/handles.h"
#include "src/objects.h"
#include "src/ostreams.h"

namespace v8 {
namespace internal {
namespace compiler {

// SUMMARY
//
// A simple type system for compiler-internal use. It is based entirely on
// union types, and all subtyping hence amounts to set inclusion. Besides the
// obvious primitive types and some predefined unions, the type language also
// can express class types (a.k.a. specific maps) and singleton types (i.e.,
// concrete constants).
//
// The following equations and inequations hold:
//
//   None <= T
//   T <= Any
//
//   Number = Signed32 \/ Unsigned32 \/ Double
//   Smi <= Signed32
//   Name = String \/ Symbol
//   UniqueName = InternalizedString \/ Symbol
//   InternalizedString < String
//
//   Receiver = Object \/ Proxy
//   OtherUndetectable < Object
//   DetectableReceiver = Receiver - OtherUndetectable
//
//   Constant(x) < T  iff instance_type(map(x)) < T
//
//
// RANGE TYPES
//
// A range type represents a continuous integer interval by its minimum and
// maximum value.  Either value may be an infinity, in which case that infinity
// itself is also included in the range.   A range never contains NaN or -0.
//
// If a value v happens to be an integer n, then Constant(v) is considered a
// subtype of Range(n, n) (and therefore also a subtype of any larger range).
// In order to avoid large unions, however, it is usually a good idea to use
// Range rather than Constant.
//
//
// PREDICATES
//
// There are two main functions for testing types:
//
//   T1->Is(T2)     -- tests whether T1 is included in T2 (i.e., T1 <= T2)
//   T1->Maybe(T2)  -- tests whether T1 and T2 overlap (i.e., T1 /\ T2 =/= 0)
//
// Typically, the former is to be used to select representations (e.g., via
// T->Is(SignedSmall())), and the latter to check whether a specific case needs
// handling (e.g., via T->Maybe(Number())).
//
// There is no functionality to discover whether a type is a leaf in the
// lattice. That is intentional. It should always be possible to refine the
// lattice (e.g., splitting up number types further) without invalidating any
// existing assumptions or tests.
// Consequently, do not normally use Equals for type tests, always use Is!
//
// The NowIs operator implements state-sensitive subtying, as described above.
// Any compilation decision based on such temporary properties requires runtime
// guarding!
//
//
// PROPERTIES
//
// Various formal properties hold for constructors, operators, and predicates
// over types. For example, constructors are injective and subtyping is a
// complete partial order.
//
// See test/cctest/test-types.cc for a comprehensive executable specification,
// especially with respect to the properties of the more exotic 'temporal'
// constructors and predicates (those prefixed 'Now').
//
//
// IMPLEMENTATION
//
// Internally, all 'primitive' types, and their unions, are represented as
// bitsets. Bit 0 is reserved for tagging. Only structured types require
// allocation.

// -----------------------------------------------------------------------------
// Values for bitset types

// clang-format off

#define INTERNAL_BITSET_TYPE_LIST(V)                                      \
  V(OtherUnsigned31, 1u << 1)  \
  V(OtherUnsigned32, 1u << 2)  \
  V(OtherSigned32,   1u << 3)  \
  V(OtherNumber,     1u << 4)  \

#define PROPER_BITSET_TYPE_LIST(V) \
  V(None,                0u)        \
  V(Negative31,          1u << 5)   \
  V(Null,                1u << 6)   \
  V(Undefined,           1u << 7)   \
  V(Boolean,             1u << 8)   \
  V(Unsigned30,          1u << 9)   \
  V(MinusZero,           1u << 10)  \
  V(NaN,                 1u << 11)  \
  V(Symbol,              1u << 12)  \
  V(InternalizedString,  1u << 13)  \
  V(OtherString,         1u << 14)  \
  V(Simd,                1u << 15)  \
  V(OtherObject,         1u << 17)  \
  V(OtherUndetectable,   1u << 16)  \
  V(Proxy,               1u << 18)  \
  V(Function,            1u << 19)  \
  V(Hole,                1u << 20)  \
  V(OtherInternal,       1u << 21)  \
  \
  V(Signed31,                   kUnsigned30 | kNegative31) \
  V(Signed32,                   kSigned31 | kOtherUnsigned31 | kOtherSigned32) \
  V(Signed32OrMinusZero,        kSigned32 | kMinusZero) \
  V(Signed32OrMinusZeroOrNaN,   kSigned32 | kMinusZero | kNaN) \
  V(Negative32,                 kNegative31 | kOtherSigned32) \
  V(Unsigned31,                 kUnsigned30 | kOtherUnsigned31) \
  V(Unsigned32,                 kUnsigned30 | kOtherUnsigned31 | \
                                kOtherUnsigned32) \
  V(Unsigned32OrMinusZero,      kUnsigned32 | kMinusZero) \
  V(Unsigned32OrMinusZeroOrNaN, kUnsigned32 | kMinusZero | kNaN) \
  V(Integral32,                 kSigned32 | kUnsigned32) \
  V(PlainNumber,                kIntegral32 | kOtherNumber) \
  V(OrderedNumber,              kPlainNumber | kMinusZero) \
  V(MinusZeroOrNaN,             kMinusZero | kNaN) \
  V(Number,                     kOrderedNumber | kNaN) \
  V(String,                     kInternalizedString | kOtherString) \
  V(UniqueName,                 kSymbol | kInternalizedString) \
  V(Name,                       kSymbol | kString) \
  V(BooleanOrNumber,            kBoolean | kNumber) \
  V(BooleanOrNullOrNumber,      kBooleanOrNumber | kNull) \
  V(BooleanOrNullOrUndefined,   kBoolean | kNull | kUndefined) \
  V(NullOrNumber,               kNull | kNumber) \
  V(NullOrUndefined,            kNull | kUndefined) \
  V(Undetectable,               kNullOrUndefined | kOtherUndetectable) \
  V(NumberOrOddball,            kNumber | kNullOrUndefined | kBoolean | kHole) \
  V(NumberOrSimdOrString,       kNumber | kSimd | kString) \
  V(NumberOrString,             kNumber | kString) \
  V(NumberOrUndefined,          kNumber | kUndefined) \
  V(PlainPrimitive,             kNumberOrString | kBoolean | kNullOrUndefined) \
  V(Primitive,                  kSymbol | kSimd | kPlainPrimitive) \
  V(DetectableReceiver,         kFunction | kOtherObject | kProxy) \
  V(Object,                     kFunction | kOtherObject | kOtherUndetectable) \
  V(Receiver,                   kObject | kProxy) \
  V(StringOrReceiver,           kString | kReceiver) \
  V(Unique,                     kBoolean | kUniqueName | kNull | kUndefined | \
                                kReceiver) \
  V(Internal,                   kHole | kOtherInternal) \
  V(NonInternal,                kPrimitive | kReceiver) \
  V(NonNumber,                  kUnique | kString | kInternal) \
  V(Any,                        0xfffffffeu)

// clang-format on

/*
 * The following diagrams show how integers (in the mathematical sense) are
 * divided among the different atomic numerical types.
 *
 *   ON    OS32     N31     U30     OU31    OU32     ON
 * ______[_______[_______[_______[_______[_______[_______
 *     -2^31   -2^30     0      2^30    2^31    2^32
 *
 * E.g., OtherUnsigned32 (OU32) covers all integers from 2^31 to 2^32-1.
 *
 * Some of the atomic numerical bitsets are internal only (see
 * INTERNAL_BITSET_TYPE_LIST).  To a types user, they should only occur in
 * union with certain other bitsets.  For instance, OtherNumber should only
 * occur as part of PlainNumber.
 */

#define BITSET_TYPE_LIST(V)    \
  INTERNAL_BITSET_TYPE_LIST(V) \
  PROPER_BITSET_TYPE_LIST(V)

class Type;

// -----------------------------------------------------------------------------
// Bitset types (internal).

class V8_EXPORT_PRIVATE BitsetType {
 public:
  typedef uint32_t bitset;  // Internal

  enum : uint32_t {
#define DECLARE_TYPE(type, value) k##type = (value),
    BITSET_TYPE_LIST(DECLARE_TYPE)
#undef DECLARE_TYPE
        kUnusedEOL = 0
  };

  static bitset SignedSmall();
  static bitset UnsignedSmall();

  bitset Bitset() {
    return static_cast<bitset>(reinterpret_cast<uintptr_t>(this) ^ 1u);
  }

  static bool IsInhabited(bitset bits) { return bits != kNone; }

  static bool Is(bitset bits1, bitset bits2) {
    return (bits1 | bits2) == bits2;
  }

  static double Min(bitset);
  static double Max(bitset);

  static bitset Glb(Type* type);  // greatest lower bound that's a bitset
  static bitset Glb(double min, double max);
  static bitset Lub(Type* type);  // least upper bound that's a bitset
  static bitset Lub(i::Map* map);
  static bitset Lub(i::Object* value);
  static bitset Lub(double value);
  static bitset Lub(double min, double max);
  static bitset ExpandInternals(bitset bits);

  static const char* Name(bitset);
  static void Print(std::ostream& os, bitset);  // NOLINT
#ifdef DEBUG
  static void Print(bitset);
#endif

  static bitset NumberBits(bitset bits);

  static bool IsBitset(Type* type) {
    return reinterpret_cast<uintptr_t>(type) & 1;
  }

  static Type* NewForTesting(bitset bits) { return New(bits); }

 private:
  friend class Type;

  static Type* New(bitset bits) {
    return reinterpret_cast<Type*>(static_cast<uintptr_t>(bits | 1u));
  }

  struct Boundary {
    bitset internal;
    bitset external;
    double min;
  };
  static const Boundary BoundariesArray[];
  static inline const Boundary* Boundaries();
  static inline size_t BoundariesSize();
};

// -----------------------------------------------------------------------------
// Superclass for non-bitset types (internal).
class TypeBase {
 protected:
  friend class Type;

  enum Kind { kHeapConstant, kOtherNumberConstant, kTuple, kUnion, kRange };

  Kind kind() const { return kind_; }
  explicit TypeBase(Kind kind) : kind_(kind) {}

  static bool IsKind(Type* type, Kind kind) {
    if (BitsetType::IsBitset(type)) return false;
    TypeBase* base = reinterpret_cast<TypeBase*>(type);
    return base->kind() == kind;
  }

  // The hacky conversion to/from Type*.
  static Type* AsType(TypeBase* type) { return reinterpret_cast<Type*>(type); }
  static TypeBase* FromType(Type* type) {
    return reinterpret_cast<TypeBase*>(type);
  }

 private:
  Kind kind_;
};

// -----------------------------------------------------------------------------
// Constant types.

class OtherNumberConstantType : public TypeBase {
 public:
  double Value() { return value_; }

  static bool IsOtherNumberConstant(double value);
  static bool IsOtherNumberConstant(Object* value);

 private:
  friend class Type;
  friend class BitsetType;

  static Type* New(double value, Zone* zone) {
    return AsType(new (zone->New(sizeof(OtherNumberConstantType)))
                      OtherNumberConstantType(value));  // NOLINT
  }

  static OtherNumberConstantType* cast(Type* type) {
    DCHECK(IsKind(type, kOtherNumberConstant));
    return static_cast<OtherNumberConstantType*>(FromType(type));
  }

  explicit OtherNumberConstantType(double value)
      : TypeBase(kOtherNumberConstant), value_(value) {
    CHECK(IsOtherNumberConstant(value));
  }

  BitsetType::bitset Lub() { return BitsetType::kOtherNumber; }

  double value_;
};

class V8_EXPORT_PRIVATE HeapConstantType : public NON_EXPORTED_BASE(TypeBase) {
 public:
  i::Handle<i::HeapObject> Value() { return object_; }

 private:
  friend class Type;
  friend class BitsetType;

  static Type* New(i::Handle<i::HeapObject> value, Zone* zone) {
    BitsetType::bitset bitset = BitsetType::Lub(*value);
    return AsType(new (zone->New(sizeof(HeapConstantType)))
                      HeapConstantType(bitset, value));
  }

  static HeapConstantType* cast(Type* type) {
    DCHECK(IsKind(type, kHeapConstant));
    return static_cast<HeapConstantType*>(FromType(type));
  }

  HeapConstantType(BitsetType::bitset bitset, i::Handle<i::HeapObject> object);

  BitsetType::bitset Lub() { return bitset_; }

  BitsetType::bitset bitset_;
  Handle<i::HeapObject> object_;
};

// -----------------------------------------------------------------------------
// Range types.

class RangeType : public TypeBase {
 public:
  struct Limits {
    double min;
    double max;
    Limits(double min, double max) : min(min), max(max) {}
    explicit Limits(RangeType* range) : min(range->Min()), max(range->Max()) {}
    bool IsEmpty();
    static Limits Empty() { return Limits(1, 0); }
    static Limits Intersect(Limits lhs, Limits rhs);
    static Limits Union(Limits lhs, Limits rhs);
  };

  double Min() { return limits_.min; }
  double Max() { return limits_.max; }

 private:
  friend class Type;
  friend class BitsetType;
  friend class UnionType;

  static Type* New(double min, double max, Zone* zone) {
    return New(Limits(min, max), zone);
  }

  static bool IsInteger(double x) {
    return nearbyint(x) == x && !i::IsMinusZero(x);  // Allows for infinities.
  }

  static Type* New(Limits lim, Zone* zone) {
    DCHECK(IsInteger(lim.min) && IsInteger(lim.max));
    DCHECK(lim.min <= lim.max);
    BitsetType::bitset bits = BitsetType::Lub(lim.min, lim.max);

    return AsType(new (zone->New(sizeof(RangeType))) RangeType(bits, lim));
  }

  static RangeType* cast(Type* type) {
    DCHECK(IsKind(type, kRange));
    return static_cast<RangeType*>(FromType(type));
  }

  RangeType(BitsetType::bitset bitset, Limits limits)
      : TypeBase(kRange), bitset_(bitset), limits_(limits) {}

  BitsetType::bitset Lub() { return bitset_; }

  BitsetType::bitset bitset_;
  Limits limits_;
};

// -----------------------------------------------------------------------------
// Superclass for types with variable number of type fields.
class StructuralType : public TypeBase {
 public:
  int LengthForTesting() { return Length(); }

 protected:
  friend class Type;

  int Length() { return length_; }

  Type* Get(int i) {
    DCHECK(0 <= i && i < this->Length());
    return elements_[i];
  }

  void Set(int i, Type* type) {
    DCHECK(0 <= i && i < this->Length());
    elements_[i] = type;
  }

  void Shrink(int length) {
    DCHECK(2 <= length && length <= this->Length());
    length_ = length;
  }

  StructuralType(Kind kind, int length, i::Zone* zone)
      : TypeBase(kind), length_(length) {
    elements_ = reinterpret_cast<Type**>(zone->New(sizeof(Type*) * length));
  }

 private:
  int length_;
  Type** elements_;
};

// -----------------------------------------------------------------------------
// Tuple types.

class TupleType : public StructuralType {
 public:
  int Arity() { return this->Length(); }
  Type* Element(int i) { return this->Get(i); }

  void InitElement(int i, Type* type) { this->Set(i, type); }

 private:
  friend class Type;

  TupleType(int length, Zone* zone) : StructuralType(kTuple, length, zone) {}

  static Type* New(int length, Zone* zone) {
    return AsType(new (zone->New(sizeof(TupleType))) TupleType(length, zone));
  }

  static TupleType* cast(Type* type) {
    DCHECK(IsKind(type, kTuple));
    return static_cast<TupleType*>(FromType(type));
  }
};

// -----------------------------------------------------------------------------
// Union types (internal).
// A union is a structured type with the following invariants:
// - its length is at least 2
// - at most one field is a bitset, and it must go into index 0
// - no field is a union
// - no field is a subtype of any other field
class UnionType : public StructuralType {
 private:
  friend Type;
  friend BitsetType;

  UnionType(int length, Zone* zone) : StructuralType(kUnion, length, zone) {}

  static Type* New(int length, Zone* zone) {
    return AsType(new (zone->New(sizeof(UnionType))) UnionType(length, zone));
  }

  static UnionType* cast(Type* type) {
    DCHECK(IsKind(type, kUnion));
    return static_cast<UnionType*>(FromType(type));
  }

  bool Wellformed();
};

class V8_EXPORT_PRIVATE Type {
 public:
  typedef BitsetType::bitset bitset;  // Internal

// Constructors.
#define DEFINE_TYPE_CONSTRUCTOR(type, value) \
  static Type* type() { return BitsetType::New(BitsetType::k##type); }
  PROPER_BITSET_TYPE_LIST(DEFINE_TYPE_CONSTRUCTOR)
#undef DEFINE_TYPE_CONSTRUCTOR

  static Type* SignedSmall() {
    return BitsetType::New(BitsetType::SignedSmall());
  }
  static Type* UnsignedSmall() {
    return BitsetType::New(BitsetType::UnsignedSmall());
  }

  static Type* OtherNumberConstant(double value, Zone* zone) {
    return OtherNumberConstantType::New(value, zone);
  }
  static Type* HeapConstant(i::Handle<i::HeapObject> value, Zone* zone) {
    return HeapConstantType::New(value, zone);
  }
  static Type* Range(double min, double max, Zone* zone) {
    return RangeType::New(min, max, zone);
  }
  static Type* Tuple(Type* first, Type* second, Type* third, Zone* zone) {
    Type* tuple = TupleType::New(3, zone);
    tuple->AsTuple()->InitElement(0, first);
    tuple->AsTuple()->InitElement(1, second);
    tuple->AsTuple()->InitElement(2, third);
    return tuple;
  }

  // NewConstant is a factory that returns Constant, Range or Number.
  static Type* NewConstant(i::Handle<i::Object> value, Zone* zone);
  static Type* NewConstant(double value, Zone* zone);

  static Type* Union(Type* type1, Type* type2, Zone* zone);
  static Type* Intersect(Type* type1, Type* type2, Zone* zone);

  static Type* Of(double value, Zone* zone) {
    return BitsetType::New(BitsetType::ExpandInternals(BitsetType::Lub(value)));
  }
  static Type* Of(i::Object* value, Zone* zone) {
    return BitsetType::New(BitsetType::ExpandInternals(BitsetType::Lub(value)));
  }
  static Type* Of(i::Handle<i::Object> value, Zone* zone) {
    return Of(*value, zone);
  }

  static Type* For(i::Map* map) {
    return BitsetType::New(BitsetType::ExpandInternals(BitsetType::Lub(map)));
  }
  static Type* For(i::Handle<i::Map> map) { return For(*map); }

  // Predicates.
  bool IsInhabited() { return BitsetType::IsInhabited(this->BitsetLub()); }

  bool Is(Type* that) { return this == that || this->SlowIs(that); }
  bool Maybe(Type* that);
  bool Equals(Type* that) { return this->Is(that) && that->Is(this); }

  // Inspection.
  bool IsRange() { return IsKind(TypeBase::kRange); }
  bool IsHeapConstant() { return IsKind(TypeBase::kHeapConstant); }
  bool IsOtherNumberConstant() {
    return IsKind(TypeBase::kOtherNumberConstant);
  }
  bool IsTuple() { return IsKind(TypeBase::kTuple); }

  HeapConstantType* AsHeapConstant() { return HeapConstantType::cast(this); }
  OtherNumberConstantType* AsOtherNumberConstant() {
    return OtherNumberConstantType::cast(this);
  }
  RangeType* AsRange() { return RangeType::cast(this); }
  TupleType* AsTuple() { return TupleType::cast(this); }

  // Minimum and maximum of a numeric type.
  // These functions do not distinguish between -0 and +0.  If the type equals
  // kNaN, they return NaN; otherwise kNaN is ignored.  Only call these
  // functions on subtypes of Number.
  double Min();
  double Max();

  // Extracts a range from the type: if the type is a range or a union
  // containing a range, that range is returned; otherwise, NULL is returned.
  Type* GetRange();

  static bool IsInteger(i::Object* x);
  static bool IsInteger(double x) {
    return nearbyint(x) == x && !i::IsMinusZero(x);  // Allows for infinities.
  }

  int NumConstants();

  // Printing.

  void PrintTo(std::ostream& os);

#ifdef DEBUG
  void Print();
#endif

  // Helpers for testing.
  bool IsBitsetForTesting() { return IsBitset(); }
  bool IsUnionForTesting() { return IsUnion(); }
  bitset AsBitsetForTesting() { return AsBitset(); }
  UnionType* AsUnionForTesting() { return AsUnion(); }

 private:
  // Friends.
  template <class>
  friend class Iterator;
  friend BitsetType;
  friend UnionType;

  // Internal inspection.
  bool IsKind(TypeBase::Kind kind) { return TypeBase::IsKind(this, kind); }

  bool IsNone() { return this == None(); }
  bool IsAny() { return this == Any(); }
  bool IsBitset() { return BitsetType::IsBitset(this); }
  bool IsUnion() { return IsKind(TypeBase::kUnion); }

  bitset AsBitset() {
    DCHECK(this->IsBitset());
    return reinterpret_cast<BitsetType*>(this)->Bitset();
  }
  UnionType* AsUnion() { return UnionType::cast(this); }

  bitset BitsetGlb() { return BitsetType::Glb(this); }
  bitset BitsetLub() { return BitsetType::Lub(this); }

  bool SlowIs(Type* that);

  static bool Overlap(RangeType* lhs, RangeType* rhs);
  static bool Contains(RangeType* lhs, RangeType* rhs);
  static bool Contains(RangeType* range, i::Object* val);

  static int UpdateRange(Type* type, UnionType* result, int size, Zone* zone);

  static RangeType::Limits IntersectRangeAndBitset(Type* range, Type* bits,
                                                   Zone* zone);
  static RangeType::Limits ToLimits(bitset bits, Zone* zone);

  bool SimplyEquals(Type* that);

  static int AddToUnion(Type* type, UnionType* result, int size, Zone* zone);
  static int IntersectAux(Type* type, Type* other, UnionType* result, int size,
                          RangeType::Limits* limits, Zone* zone);
  static Type* NormalizeUnion(Type* unioned, int size, Zone* zone);
  static Type* NormalizeRangeAndBitset(Type* range, bitset* bits, Zone* zone);
};

}  // namespace compiler
}  // namespace internal
}  // namespace v8

#endif  // V8_COMPILER_TYPES_H_


text:
import sbt._
import Keys._
import play.Project._
import com.typesafe.sbtidea.SbtIdeaPlugin

object ApplicationBuild extends Build {

  override def settings = super.settings ++ SbtIdeaPlugin.ideaSettings

  val PlayCrudName = "play-crud"
  val PlayCrudVersion = "1.0.0-SNAPSHOT"
  val PlayCrudDependencies = Seq(
    javaCore,
    "commons-beanutils" % "commons-beanutils" % "1.8.3"
  )
  val PlayCrudEbeanDependencies = Seq(
    javaCore,javaJdbc,javaEbean
  )

  val appName         = PlayCrudName+"-ebean-test"
  val appVersion      = PlayCrudVersion
  val appDependencies = PlayCrudEbeanDependencies

  val PlayCrudCore = Project(PlayCrudName+"-core", file("modules/core")).settings(
    crossPaths := false,
    version := PlayCrudVersion
  )

  val PlayCrud = play.Project(PlayCrudName, PlayCrudVersion, PlayCrudDependencies, file("modules/crud")).settings(
    crossPaths := false
  ).dependsOn(PlayCrudCore)

  val PlayCrudEbean = play.Project(PlayCrudName+"-ebean", PlayCrudVersion, PlayCrudEbeanDependencies, file("modules/ebean")).settings(
    crossPaths := false
  ).dependsOn(PlayCrudCore)

  val main = play.Project(appName, appVersion, appDependencies).settings(
    // Add your own project settings here
  ).dependsOn(PlayCrud, PlayCrudEbean).aggregate(PlayCrud, PlayCrudEbean)

}


text:
import java.util.List;

class Foo<E extends List<String> & Runnable> {
  Foo() {}

  {
    Foo foo = new Foo<error descr="Cannot use '<>' with anonymous inner classes"><></error>() {};
  }
}


text:
let LocalDatabase = function () {
	this.db = null;
}

LocalDatabase.prototype.open = function (databasename) {
	return new Promise((resolve) => {
		let request = indexedDB.open(databasename, 1);

		request.onerror = (err) => {
			console.log(err)
		}

		request.onsuccess = (e) => {
			console.log('opened');
			this.db = e.target.result;
			resolve(true);
		}

		request.onupgradeneeded = (e) => {
	    	console.log ("Going to upgrade our DB");
	    	this.db = e.target.result;
	    	if(this.db.objectStoreNames.contains("artists")) {
	    		this.db.deleteObjectStore("artists");
	    	}
	        let store = this.db.createObjectStore("artists", {autoIncrement: true});

	        request.onfailure = this.onerror;
	        request.onerror = function(e) {
	        	console.error("Err:"+e);
	        }
	    }
    })
}

LocalDatabase.prototype.add = function (databasename, data) {
	//console.log('add', this.db)
	let trans = this.db.transaction(['artists'], 'readwrite');
	let objectStore = trans.objectStore("artists");

	data.forEach((d, i) => {
		console.log(d);
		let request = objectStore.put(d);
	    request.onsuccess = function(e) {
	    	console.log('data added');
	    };
	    request.onerror = function(e) {
	        console.error("Error Adding an item: ", e);
	    };
	});
}

LocalDatabase.prototype.get = function (databasename) {
	return new Promise((resolve) => {
		let finalResult = [];
		let trans = this.db.transaction(["artists"], "readwrite");
	    let store = trans.objectStore("artists");

	    let keyRange = IDBKeyRange.lowerBound(0);
	    let cursorRequest = store.openCursor(keyRange);

	    cursorRequest.onsuccess = function(e) {
	        var result = e.target.result;
	        if(!!result == false) {
	        	resolve(finalResult);
	        	return;
	        }
	        //console.log(result.value);
	        finalResult.push(result.value);
	    	result.continue();
	    };
	});
}

LocalDatabase.prototype.close = function () {
	this.db.close();
}

LocalDatabase.prototype.resetTopArtists = function () {
	window.indexedDB.deleteDatabase("artists");

}

export default LocalDatabase;