text:
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "SnXmlImpl.h"
#include "PsHash.h"
#include "PsHashMap.h"
#include "SnSimpleXmlWriter.h"
#include "PsSort.h"
#include "PsFastXml.h"
#include "PsString.h"
#include "SnXmlMemoryPool.h"
#include "PxExtensionMetaDataObjects.h"
#include "SnXmlVisitorWriter.h"
#include "SnXmlVisitorReader.h"
#include "SnXmlMemoryAllocator.h"
#include "SnXmlStringToType.h"
#include "PsString.h"
#include "SnRepXCollection.h"
#include "SnRepXUpgrader.h"
#include "../SnSerializationRegistry.h"
#include "PsFoundation.h"
#include "CmCollection.h"

using namespace physx;
using namespace Sn;

using namespace physx::profile; //for the foundation wrapper system.

namespace physx { namespace Sn {

	class XmlNodeWriter : public SimpleXmlWriter
	{
		XmlMemoryAllocatorImpl&		mParseAllocator;
		XmlNode*					mCurrentNode;
		XmlNode*					mTopNode;
		PxU32						mTabCount;

	public:
		XmlNodeWriter( XmlMemoryAllocatorImpl& inAllocator, PxU32 inTabCount = 0 )
			: mParseAllocator( inAllocator )
			, mCurrentNode( NULL )
			, mTopNode( NULL )
			, mTabCount( inTabCount )
		{}
		XmlNodeWriter& operator=(const XmlNodeWriter&);
		virtual ~XmlNodeWriter(){}
		void onNewNode( XmlNode* newNode )
		{
			if ( mCurrentNode != NULL )
				mCurrentNode->addChild( newNode );
			if ( mTopNode == NULL )
				mTopNode = newNode;
			mCurrentNode = newNode;
			++mTabCount;
		}

		XmlNode* getTopNode() const { return mTopNode; }

		virtual void beginTag( const char* inTagname )
		{
			onNewNode( allocateRepXNode( &mParseAllocator.mManager, inTagname, NULL ) );
		}
		virtual void endTag()
		{
			if ( mCurrentNode )
				mCurrentNode = mCurrentNode->mParent;
			if ( mTabCount )
				--mTabCount;
		}
		virtual void addAttribute( const char*, const char* )
		{
			PX_ASSERT( false );
		}
		virtual void writeContentTag( const char* inTag, const char* inContent )
		{
			onNewNode( allocateRepXNode( &mParseAllocator.mManager, inTag, inContent ) );
			endTag();
		}
		virtual void addContent( const char* inContent )
		{
			if ( mCurrentNode->mData )
				releaseStr( &mParseAllocator.mManager, mCurrentNode->mData );
			mCurrentNode->mData = copyStr( &mParseAllocator.mManager, inContent );
		}
		virtual PxU32 tabCount() { return mTabCount; }
	};

	struct XmlWriterImpl : public XmlWriter
	{
		PxU32				mTagDepth;
		SimpleXmlWriter*	mWriter;
		MemoryBuffer*		mMemBuffer;

		XmlWriterImpl( SimpleXmlWriter* inWriter, MemoryBuffer* inMemBuffer )
			: mTagDepth( 0 )
			, mWriter( inWriter )
			, mMemBuffer( inMemBuffer )
		{
		}
		~XmlWriterImpl()
		{
			while( mTagDepth )
			{
				--mTagDepth;
				mWriter->endTag();
			}
		}
		virtual void write( const char* inName, const char* inData )
		{
			mWriter->writeContentTag( inName, inData );
		}
		virtual void write( const char* inName, const PxRepXObject& inLiveObject )
		{
			(*mMemBuffer) << inLiveObject.id;
			writeProperty( *mWriter, *mMemBuffer, inName );
		}
		virtual void addAndGotoChild( const char* inName )
		{
			mWriter->beginTag( inName );
			mTagDepth++;
		}
		virtual void leaveChild()
		{
			if ( mTagDepth )
			{
				mWriter->endTag();
				--mTagDepth;
			}
		}
	};

	struct XmlParseArgs
	{
		XmlMemoryAllocatorImpl*					mAllocator;
		ProfileArray<RepXCollectionItem>*		mCollection;

		XmlParseArgs( XmlMemoryAllocatorImpl* inAllocator
			, ProfileArray<RepXCollectionItem>* inCollection)
			: mAllocator( inAllocator )
			, mCollection( inCollection )
		{
		}
	};

	struct XmlNodeReader : public XmlReaderWriter
	{
		FoundationWrapper mWrapper;
		CMemoryPoolManager& mManager;
		XmlNode* mCurrentNode;
		XmlNode* mTopNode;
		ProfileArray<XmlNode*> mContext;
		XmlNodeReader( XmlNode* inCurrentNode, PxAllocatorCallback& inAllocator, CMemoryPoolManager& nodePoolManager )
			: mWrapper( inAllocator )
			, mManager( nodePoolManager )
			, mCurrentNode( inCurrentNode )
			, mTopNode( inCurrentNode )
			, mContext( mWrapper )
		{
		}

		//Does this node exist as data in the format.
		virtual bool read( const char* inName, const char*& outData )
		{
			XmlNode* theChild( mCurrentNode->findChildByName( inName ) );
			if ( theChild )
			{
				outData = theChild->mData;
				return outData && *outData;
			}
			return false;
		}

		virtual bool read( const char* inName, PxSerialObjectId& outId )
		{
			XmlNode* theChild( mCurrentNode->findChildByName( inName ) );
			if ( theChild )
			{
				const char* theValue( theChild->mData );
				strto( outId, theValue );
				return true;
			}
			return false;
		}

		virtual bool gotoChild( const char* inName )
		{
			XmlNode* theChild( mCurrentNode->findChildByName( inName ) );
			if ( theChild )
			{
				mCurrentNode =theChild;
				return true;
			}
			return false;
		}
		virtual bool gotoFirstChild()
		{
			if ( mCurrentNode->mFirstChild )
			{
				mCurrentNode = mCurrentNode->mFirstChild;
				return true;
			}
			return false;
		}
		virtual bool gotoNextSibling()
		{
			if ( mCurrentNode->mNextSibling )
			{
				mCurrentNode = mCurrentNode->mNextSibling;
				return true;
			}
			return false;
		}
		virtual PxU32 countChildren()
		{
			PxU32 retval=  0;
			for ( XmlNode* theChild = mCurrentNode->mFirstChild; theChild != NULL; theChild = theChild->mNextSibling )
				++retval;
			return retval;
		}
		virtual const char* getCurrentItemName()
		{
			return mCurrentNode->mName;
		}
		virtual const char* getCurrentItemValue()
		{
			return mCurrentNode->mData;
		}

		virtual bool leaveChild()
		{
			if ( mCurrentNode != mTopNode && mCurrentNode->mParent )
			{
				mCurrentNode = mCurrentNode->mParent;
				return true;
			}
			return false;
		}

		virtual void pushCurrentContext()
		{
			mContext.pushBack( mCurrentNode );
		}
		virtual void popCurrentContext()
		{
			if ( mContext.size() )
			{
				mCurrentNode = mContext.back();
				mContext.popBack();
			}
		}

		virtual void setNode( XmlNode& inNode )
		{
			mContext.clear();
			mCurrentNode = &inNode;
			mTopNode = mCurrentNode;
		}

		virtual void addOrGotoChild( const char* inName )
		{
			if ( gotoChild( inName )== false )
			{
				XmlNode* newNode = allocateRepXNode( &mManager, inName, NULL );
				mCurrentNode->addChild( newNode );
				mCurrentNode = newNode;
			}
		}
		virtual void setCurrentItemValue( const char* inValue )
		{
			mCurrentNode->mData = copyStr( &mManager, inValue );
		}
		virtual bool removeChild( const char* name )
		{
			XmlNode* theChild( mCurrentNode->findChildByName( name ) );
			if ( theChild )
			{
				releaseNodeAndChildren( &mManager, theChild );
				return true;
			}
			return false;
		}
		virtual void release() { this->~XmlNodeReader(); mWrapper.getAllocator().deallocate(this); }

	private:
		XmlNodeReader& operator=(const XmlNodeReader&);
	};

	PX_INLINE void  freeNodeAndChildren( XmlNode* tempNode, TMemoryPoolManager& inManager )
	{
		for( XmlNode* theNode = tempNode->mFirstChild; theNode != NULL; theNode = theNode->mNextSibling )
			freeNodeAndChildren( theNode, inManager );
		tempNode->orphan();
		release( &inManager, tempNode );
	}

	class XmlParser : public FastXml::Callback
	{
		XmlParseArgs			mParseArgs;
		//For parse time only allocations
		XmlMemoryAllocatorImpl& mParseAllocator;
		XmlNode* mCurrentNode;
		XmlNode* mTopNode;

	public:
		XmlParser( XmlParseArgs inArgs, XmlMemoryAllocatorImpl& inParseAllocator )
			: mParseArgs( inArgs )
			, mParseAllocator( inParseAllocator )
			, mCurrentNode( NULL )
			, mTopNode( NULL )
		{
		}

		virtual ~XmlParser(){}

		virtual bool processComment(const char* /*comment*/) { return true; }
		// 'element' is the name of the element that is being closed.
		// depth is the recursion depth of this element.
		// Return true to continue processing the XML file.
		// Return false to stop processing the XML file; leaves the read pointer of the stream right after this close tag.
		// The bool 'isError' indicates whether processing was stopped due to an error, or intentionally canceled early.
		virtual bool processClose(const char* /*element*/,physx::PxU32 /*depth*/,bool& /*isError*/)
		{
			mCurrentNode = mCurrentNode->mParent;
			return true;
		}

		// return true to continue processing the XML document, false to skip.
		virtual bool processElement(
			const char *elementName,   // name of the element
			const char  *elementData,  // element data, null if none
			const FastXml::AttributePairs& attr,      // attributes
			PxI32 /*lineno*/)
		{
			XmlNode* newNode = allocateRepXNode( &mParseAllocator.mManager, elementName, elementData );
			if ( mCurrentNode )
				mCurrentNode->addChild( newNode );
			mCurrentNode = newNode;
			//Add the elements as children.
			for( PxI32 item = 0; item < attr.getNbAttr(); item ++ )
			{
				XmlNode* node = allocateRepXNode( &mParseAllocator.mManager, attr.getKey((PxU32)item), attr.getValue((PxU32)item) );
				mCurrentNode->addChild( node );
			}
			if ( mTopNode == NULL ) mTopNode = newNode;
			return true;
		}

		XmlNode* getTopNode() { return mTopNode; }

		virtual void *  allocate(PxU32 size)
		{
			if ( size )
				return mParseAllocator.allocate(size);
			return NULL;
		}
		virtual void	deallocate(void *mem)
		{
			if ( mem )
				mParseAllocator.deallocate(reinterpret_cast<PxU8*>(mem));
		}

	private:
		XmlParser& operator=(const XmlParser&);
	};

	struct RepXCollectionSharedData
	{
		FoundationWrapper				mWrapper;
		XmlMemoryAllocatorImpl			mAllocator;
		PxU32							mRefCount;

		RepXCollectionSharedData( PxAllocatorCallback& inAllocator )
			: mWrapper( inAllocator )
			, mAllocator( inAllocator )
			, mRefCount( 0 )
		{
		}
		~RepXCollectionSharedData() {}

		void addRef() { ++mRefCount;}
		void release()
		{
			if ( mRefCount ) --mRefCount;
			if ( !mRefCount ) { this->~RepXCollectionSharedData(); mWrapper.getAllocator().deallocate(this);}
		}
	};

	struct SharedDataPtr
	{
		RepXCollectionSharedData* mData;
		SharedDataPtr( RepXCollectionSharedData* inData )
			: mData( inData )
		{
			mData->addRef();
		}
		SharedDataPtr( const SharedDataPtr& inOther )
			: mData( inOther.mData )
		{
			mData->addRef();
		}
		SharedDataPtr& operator=( const SharedDataPtr& inOther );
		~SharedDataPtr()
		{
			mData->release();
			mData = NULL;
		}
		RepXCollectionSharedData* operator->() { return mData; }
		const RepXCollectionSharedData* operator->() const { return mData; }
	};

	class RepXCollectionImpl : public RepXCollection, public UserAllocated
	{
		SharedDataPtr							mSharedData;

		XmlMemoryAllocatorImpl&					mAllocator;
		PxSerializationRegistry&				mSerializationRegistry;
		ProfileArray<RepXCollectionItem>		mCollection;
		TMemoryPoolManager						mSerializationManager;
		MemoryBuffer							mPropertyBuffer;
		PxTolerancesScale						mScale;
		PxVec3									mUpVector;
		const char*								mVersionStr;
		PxCollection*							mPxCollection;

	public:
		RepXCollectionImpl( PxSerializationRegistry& inRegistry, PxAllocatorCallback& inAllocator, PxCollection& inPxCollection )
			: mSharedData( &PX_NEW_REPX_SERIALIZER( RepXCollectionSharedData ))
			, mAllocator( mSharedData->mAllocator )
			, mSerializationRegistry( inRegistry )
			, mCollection( mSharedData->mWrapper )
			, mSerializationManager( inAllocator )
			, mPropertyBuffer( &mSerializationManager )
			, mUpVector( 0,0,0 )
			, mVersionStr( getLatestVersion() )
			, mPxCollection( &inPxCollection )
		{
			memset( &mScale, 0, sizeof( PxTolerancesScale ) );
			PX_ASSERT( mScale.isValid() == false );
		}

		RepXCollectionImpl( PxSerializationRegistry& inRegistry, const RepXCollectionImpl& inSrc, const char* inNewVersion )
			: mSharedData( inSrc.mSharedData )
			, mAllocator( mSharedData->mAllocator )
			, mSerializationRegistry( inRegistry )
			, mCollection( mSharedData->mWrapper )
			, mSerializationManager( mSharedData->mWrapper.getAllocator() )
			, mPropertyBuffer( &mSerializationManager )
			, mScale( inSrc.mScale )
			, mUpVector( inSrc.mUpVector )
			, mVersionStr( inNewVersion )
			, mPxCollection( NULL )
		{
		}

		virtual ~RepXCollectionImpl()
		{
			PxU32 numItems = mCollection.size();
			for ( PxU32 idx = 0; idx < numItems; ++idx )
			{
				XmlNode* theNode = mCollection[idx].descriptor;
				releaseNodeAndChildren( &mAllocator.mManager, theNode );
			}
		}
		RepXCollectionImpl& operator=(const RepXCollectionImpl&);

		virtual void destroy()
		{
			FoundationWrapper tempWrapper( mSharedData->mWrapper.getAllocator() );
			this->~RepXCollectionImpl();
			tempWrapper.getAllocator().deallocate(this);
		}

		virtual void setTolerancesScale(const PxTolerancesScale& inScale) {  mScale = inScale; }
		virtual PxTolerancesScale getTolerancesScale() const { return mScale; }
		virtual void setUpVector( const PxVec3& inUpVector ) { mUpVector = inUpVector; }
		virtual PxVec3 getUpVector() const { return mUpVector; }

		PX_INLINE RepXCollectionItem findItemBySceneItem( const PxRepXObject& inObject ) const
		{
			//See if the object is in the collection
			for ( PxU32 idx =0; idx < mCollection.size(); ++idx )
				if ( mCollection[idx].liveObject.serializable == inObject.serializable )
					return mCollection[idx];
			return RepXCollectionItem();
		}

		virtual RepXAddToCollectionResult addRepXObjectToCollection( const PxRepXObject& inObject, PxCollection* inCollection, PxRepXInstantiationArgs& inArgs )
		{
			PX_ASSERT( inObject.serializable );
			PX_ASSERT( inObject.id );
			if ( inObject.serializable == NULL || inObject.id == 0 )
				return RepXAddToCollectionResult( RepXAddToCollectionResult::InvalidParameters );

			PxRepXSerializer* theSerializer = mSerializationRegistry.getRepXSerializer( inObject.typeName );
			if ( theSerializer == NULL )
				return RepXAddToCollectionResult( RepXAddToCollectionResult::SerializerNotFound );

			RepXCollectionItem existing = findItemBySceneItem( inObject );
			if ( existing.liveObject.serializable )
				return RepXAddToCollectionResult( RepXAddToCollectionResult::AlreadyInCollection, existing.liveObject.id );

			XmlNodeWriter theXmlWriter( mAllocator, 1 );
			XmlWriterImpl theRepXWriter( &theXmlWriter, &mPropertyBuffer );
			{
				SimpleXmlWriter::STagWatcher theWatcher( theXmlWriter, inObject.typeName );
				writeProperty( theXmlWriter, mPropertyBuffer, "Id", inObject.id  );
				theSerializer->objectToFile( inObject, inCollection, theRepXWriter, mPropertyBuffer,inArgs );
			}
			mCollection.pushBack( RepXCollectionItem( inObject, theXmlWriter.getTopNode() ) );
			return RepXAddToCollectionResult( RepXAddToCollectionResult::Success, inObject.id );
		}

		virtual bool instantiateCollection( PxRepXInstantiationArgs& inArgs, PxCollection& inCollection )
		{
			for ( PxU32 idx =0; idx < mCollection.size(); ++idx )
			{
				RepXCollectionItem theItem( mCollection[idx] );
				PxRepXSerializer* theSerializer = mSerializationRegistry.getRepXSerializer( theItem.liveObject.typeName );
				if (theSerializer )
				{
					XmlNodeReader theReader( theItem.descriptor, mAllocator.getAllocator(), mAllocator.mManager );
					XmlMemoryAllocatorImpl instantiationAllocator( mAllocator.getAllocator() );
					PxRepXObject theLiveObject = theSerializer->fileToObject( theReader, instantiationAllocator, inArgs, &inCollection );
					if (theLiveObject.isValid())
					{
						const PxBase* s =  reinterpret_cast<const PxBase*>( theLiveObject.serializable ) ;
                        inCollection.add( *const_cast<PxBase*>(s), PxSerialObjectId( theItem.liveObject.id ));
                    }
					else
						return false;
				}
				else
				{
					Ps::getFoundation().error(PxErrorCode::eINTERNAL_ERROR, __FILE__, __LINE__,
						"PxSerialization::createCollectionFromXml: "
						"PxRepXSerializer missing for type %s", theItem.liveObject.typeName);
					return false;
				}
			}

			return true;
		}

		void saveXmlNode( XmlNode* inNode, SimpleXmlWriter& inWriter )
		{
			XmlNode* theNode( inNode );
			if ( theNode->mData && *theNode->mData && theNode->mFirstChild == NULL )
				inWriter.writeContentTag( theNode->mName, theNode->mData );
			else
			{
				inWriter.beginTag( theNode->mName );
				if ( theNode->mData && *theNode->mData )
					inWriter.addContent( theNode->mData );
				for ( XmlNode* theChild = theNode->mFirstChild;
						theChild != NULL;
						theChild = theChild->mNextSibling )
					saveXmlNode( theChild, inWriter );
				inWriter.endTag();
			}
		}

		virtual void save( PxOutputStream& inStream )
		{
			SimpleXmlWriterImpl<PxOutputStream> theWriter( inStream, mAllocator.getAllocator() );
			theWriter.beginTag( "PhysX30Collection" );
			theWriter.addAttribute( "version", mVersionStr );
			{
				XmlWriterImpl theRepXWriter( &theWriter, &mPropertyBuffer );
				writeProperty( theWriter, mPropertyBuffer, "UpVector", mUpVector );
				theRepXWriter.addAndGotoChild( "Scale" );
				writeAllProperties( &mScale, theRepXWriter, mPropertyBuffer, *mPxCollection);
				theRepXWriter.leaveChild();
			}
			for ( PxU32 idx =0; idx < mCollection.size(); ++idx )
			{
				RepXCollectionItem theItem( mCollection[idx] );
				XmlNode* theNode( theItem.descriptor );
				saveXmlNode( theNode, theWriter );
			}
		}

		void load( PxInputData& inFileBuf, SerializationRegistry& s )
		{
			inFileBuf.seek(0);
			XmlParser theParser( XmlParseArgs( &mAllocator, &mCollection ), mAllocator );
			FastXml* theFastXml = createFastXml( &theParser );
			theFastXml->processXml( inFileBuf );
			XmlNode* theTopNode = theParser.getTopNode();
			if ( theTopNode != NULL )
			{
				{

					XmlMemoryAllocatorImpl instantiationAllocator( mAllocator.getAllocator() );
					XmlNodeReader theReader( theTopNode, mAllocator.getAllocator(), mAllocator.mManager );
					readProperty( theReader, "UpVector", mUpVector );
					if ( theReader.gotoChild( "Scale" ) )
					{
						readAllProperties( PxRepXInstantiationArgs( s.getPhysics() ), theReader, &mScale, instantiationAllocator, *mPxCollection);
						theReader.leaveChild();
					}
					const char* verStr = NULL;
					if ( theReader.read( "version", verStr ) )
						mVersionStr = verStr;
				}
				for ( XmlNode* theChild = theTopNode->mFirstChild;
						theChild != NULL;
						theChild = theChild->mNextSibling )
				{
					if ( physx::PxStricmp( theChild->mName, "scale" ) == 0
						|| physx::PxStricmp( theChild->mName, "version" ) == 0
						|| physx::PxStricmp( theChild->mName, "upvector" ) == 0 )
						continue;
					XmlNodeReader theReader( theChild, mAllocator.getAllocator(), mAllocator.mManager );
					PxRepXObject theObject;
					theObject.typeName = theChild->mName;
					theObject.serializable = NULL;
					PxSerialObjectId theId = 0;
					theReader.read( "Id", theId );
					theObject.id = theId;
					mCollection.pushBack( RepXCollectionItem( theObject, theChild ) );
				}
			}
			else
			{
				Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__,
				"Cannot parse any object from the input buffer, please check the input repx data.");
			}
			theFastXml->release();
		}

		virtual const char* getVersion() { return mVersionStr; }

		virtual const RepXCollectionItem* begin() const
		{
			return mCollection.begin();
		}
		virtual const RepXCollectionItem* end() const
		{
			return mCollection.end();
		}

		virtual RepXCollection& createCollection( const char* inVersionStr )
		{
			PxAllocatorCallback& allocator = mSharedData->mWrapper.getAllocator();
			RepXCollectionImpl* retval = PX_PLACEMENT_NEW((allocator.allocate(sizeof(RepXCollectionImpl), "createCollection",  __FILE__, __LINE__ )), RepXCollectionImpl) ( mSerializationRegistry, *this, inVersionStr );

			return *retval;
		}

		//Performs a deep copy of the repx node.
		virtual XmlNode* copyRepXNode( const XmlNode* srcNode )
		{
			return physx::Sn::copyRepXNode( &mAllocator.mManager, srcNode );
		}

		virtual void addCollectionItem( RepXCollectionItem inItem )
		{
			mCollection.pushBack( inItem );
		}

		virtual PxAllocatorCallback& getAllocator() { return mSharedData->mAllocator.getAllocator(); }
		//Create a new repx node with this name.  Its value is unset.
		virtual XmlNode& createRepXNode( const char* name )
		{
			XmlNode* newNode = allocateRepXNode( &mSharedData->mAllocator.mManager, name, NULL );
			return *newNode;
		}

		//Release this when finished.
		virtual XmlReaderWriter& createNodeEditor()
		{
			PxAllocatorCallback& allocator = mSharedData->mWrapper.getAllocator();
			XmlReaderWriter* retval = PX_PLACEMENT_NEW((allocator.allocate(sizeof(XmlNodeReader), "createNodeEditor",  __FILE__, __LINE__ )), XmlNodeReader) ( NULL, allocator, mAllocator.mManager );
			return *retval;
		}
	};

	const char* RepXCollection::getLatestVersion()
	{
#define TOSTR_(x)   #x
#define CONCAT_(a, b, c) TOSTR_(a.##b.##c)
#define MAKE_VERSION_STR(a,b,c)  CONCAT_(a, b, c)

		return MAKE_VERSION_STR(PX_PHYSICS_VERSION_MAJOR,PX_PHYSICS_VERSION_MINOR,PX_PHYSICS_VERSION_BUGFIX);
	}

	static RepXCollection* create(SerializationRegistry& s, PxAllocatorCallback& inAllocator, PxCollection& inCollection )
	{
		return PX_PLACEMENT_NEW((inAllocator.allocate(sizeof(RepXCollectionImpl), "RepXCollection::create",  __FILE__, __LINE__ )), RepXCollectionImpl) ( s, inAllocator, inCollection );
	}

	static RepXCollection* create(SerializationRegistry& s, PxInputData &data, PxAllocatorCallback& inAllocator, PxCollection& inCollection )
	{
		RepXCollectionImpl* theCollection = static_cast<RepXCollectionImpl*>( create(s, inAllocator, inCollection ) );
		theCollection->load( data, s );
		return theCollection;
	}
}

	bool PxSerialization::serializeCollectionToXml( PxOutputStream& outputStream, PxCollection& collection, PxSerializationRegistry& sr, PxCooking* cooking, const PxCollection* externalRefs, PxXmlMiscParameter* inArgs )
	{
		if( !PxSerialization::isSerializable(collection, sr, const_cast<PxCollection*>(externalRefs)) )
			return false;

		bool bRet = true;

		SerializationRegistry& sn = static_cast<SerializationRegistry&>(sr);
		PxRepXInstantiationArgs args( sn.getPhysics(), cooking );

		PxCollection* tmpCollection = PxCreateCollection();
		PX_ASSERT(tmpCollection);

		tmpCollection->add( collection );
		if(externalRefs)
		{
			tmpCollection->add(*const_cast<PxCollection*>(externalRefs));
		}

		PxAllocatorCallback& allocator = PxGetFoundation().getAllocatorCallback();
		Sn::RepXCollection* theRepXCollection = Sn::create(sn, allocator, *tmpCollection );

		if(inArgs != NULL)
		{
			theRepXCollection->setTolerancesScale(inArgs->scale);
			theRepXCollection->setUpVector(inArgs->upVector);
		}

		PxU32 nbObjects = collection.getNbObjects();
		if( nbObjects )
		{
			sortCollection( static_cast<Cm::Collection&>(collection), sn, true);

            for( PxU32 i = 0; i < nbObjects; i++ )
			{
                PxBase& s = collection.getObject(i);
				if( PxConcreteType::eSHAPE == s.getConcreteType() )
				{
					PxShape& shape = static_cast<PxShape&>(s);
					if( shape.isExclusive() )
						continue;
				}

				PxSerialObjectId id = collection.getId(s);
				if(id == PX_SERIAL_OBJECT_ID_INVALID)
					id = static_cast<PxSerialObjectId>( reinterpret_cast<size_t>( &s ));

				PxRepXObject ro = createRepXObject( &s, id );
				if ( ro.serializable == NULL || ro.id == 0 )
				{
					bRet = false;
					break;
				}

				theRepXCollection->addRepXObjectToCollection( ro, tmpCollection, args );
			}
		}
		tmpCollection->release();

		theRepXCollection->save(outputStream);
		theRepXCollection->destroy();

		return bRet;
	}

	PxCollection* PxSerialization::createCollectionFromXml(PxInputData& inputData, PxCooking& cooking, PxSerializationRegistry& sr, const PxCollection* externalRefs, PxStringTable* stringTable, PxXmlMiscParameter* outArgs)
	{
		SerializationRegistry& sn = static_cast<SerializationRegistry&>(sr);
		PxCollection* collection = PxCreateCollection();
		PX_ASSERT(collection);

		if( externalRefs )
			collection->add(*const_cast<PxCollection*>(externalRefs));

		PxAllocatorCallback& allocator = PxGetFoundation().getAllocatorCallback();
		Sn::RepXCollection* theRepXCollection = Sn::create(sn, inputData, allocator, *collection);
		theRepXCollection = &Sn::RepXUpgrader::upgradeCollection( *theRepXCollection );

		PxRepXInstantiationArgs args( sn.getPhysics(), &cooking, stringTable );
		if( !theRepXCollection->instantiateCollection(args, *collection) )
		{
			collection->release();
			theRepXCollection->destroy();
			return NULL;
		}

		if( externalRefs )
			collection->remove(*const_cast<PxCollection*>(externalRefs));

		if(outArgs != NULL)
		{
			outArgs->upVector = theRepXCollection->getUpVector();
			outArgs->scale = theRepXCollection->getTolerancesScale();
		}

		theRepXCollection->destroy();

		return collection;
	}
}


text:
namespace FakeOcc {

template<typename T>
class GenericHandle
{
public:
    GenericHandle() { }
    GenericHandle(const GenericHandle<T>&) { }
    GenericHandle(const T*) { }
    Standard_Boolean IsNull() const { return Standard_True; }
    T* operator->() const { return NULL; }
    GenericHandle<T>& operator=(const T*) { return *this; }
};

} // namespace FakeOcc

#endif // FAKE_OCC_GENERIC_HANDLE

redpajama_set_name: RedPajamaGithub


text:
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_dir.h"
#include "xfs_dir2.h"
#include "xfs_dmapi.h"
#include "xfs_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_alloc_btree.h"
#include "xfs_ialloc_btree.h"
#include "xfs_dir_sf.h"
#include "xfs_dir2_sf.h"
#include "xfs_attr_sf.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_buf_item.h"
#include "xfs_trans_priv.h"
#include "xfs_error.h"
#include "xfs_rw.h"

STATIC xfs_buf_t *xfs_trans_buf_item_match(xfs_trans_t *, xfs_buftarg_t *,
		xfs_daddr_t, int);
STATIC xfs_buf_t *xfs_trans_buf_item_match_all(xfs_trans_t *, xfs_buftarg_t *,
		xfs_daddr_t, int);

/*
 * Get and lock the buffer for the caller if it is not already
 * locked within the given transaction.  If it is already locked
 * within the transaction, just increment its lock recursion count
 * and return a pointer to it.
 *
 * Use the fast path function xfs_trans_buf_item_match() or the buffer
 * cache routine incore_match() to find the buffer
 * if it is already owned by this transaction.
 *
 * If we don't already own the buffer, use get_buf() to get it.
 * If it doesn't yet have an associated xfs_buf_log_item structure,
 * then allocate one and add the item to this transaction.
 *
 * If the transaction pointer is NULL, make this just a normal
 * get_buf() call.
 */
xfs_buf_t *
xfs_trans_get_buf(xfs_trans_t	*tp,
		  xfs_buftarg_t	*target_dev,
		  xfs_daddr_t	blkno,
		  int		len,
		  uint		flags)
{
	xfs_buf_t		*bp;
	xfs_buf_log_item_t	*bip;

	if (flags == 0)
		flags = XFS_BUF_LOCK | XFS_BUF_MAPPED;

	/*
	 * Default to a normal get_buf() call if the tp is NULL.
	 */
	if (tp == NULL) {
		bp = xfs_buf_get_flags(target_dev, blkno, len,
							flags | BUF_BUSY);
		return(bp);
	}

	/*
	 * If we find the buffer in the cache with this transaction
	 * pointer in its b_fsprivate2 field, then we know we already
	 * have it locked.  In this case we just increment the lock
	 * recursion count and return the buffer to the caller.
	 */
	if (tp->t_items.lic_next == NULL) {
		bp = xfs_trans_buf_item_match(tp, target_dev, blkno, len);
	} else {
		bp  = xfs_trans_buf_item_match_all(tp, target_dev, blkno, len);
	}
	if (bp != NULL) {
		ASSERT(XFS_BUF_VALUSEMA(bp) <= 0);
		if (XFS_FORCED_SHUTDOWN(tp->t_mountp)) {
			xfs_buftrace("TRANS GET RECUR SHUT", bp);
			XFS_BUF_SUPER_STALE(bp);
		}
		/*
		 * If the buffer is stale then it was binval'ed
		 * since last read.  This doesn't matter since the
		 * caller isn't allowed to use the data anyway.
		 */
		else if (XFS_BUF_ISSTALE(bp)) {
			xfs_buftrace("TRANS GET RECUR STALE", bp);
			ASSERT(!XFS_BUF_ISDELAYWRITE(bp));
		}
		ASSERT(XFS_BUF_FSPRIVATE2(bp, xfs_trans_t *) == tp);
		bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t *);
		ASSERT(bip != NULL);
		ASSERT(atomic_read(&bip->bli_refcount) > 0);
		bip->bli_recur++;
		xfs_buftrace("TRANS GET RECUR", bp);
		xfs_buf_item_trace("GET RECUR", bip);
		return (bp);
	}

	/*
	 * We always specify the BUF_BUSY flag within a transaction so
	 * that get_buf does not try to push out a delayed write buffer
	 * which might cause another transaction to take place (if the
	 * buffer was delayed alloc).  Such recursive transactions can
	 * easily deadlock with our current transaction as well as cause
	 * us to run out of stack space.
	 */
	bp = xfs_buf_get_flags(target_dev, blkno, len, flags | BUF_BUSY);
	if (bp == NULL) {
		return NULL;
	}

	ASSERT(!XFS_BUF_GETERROR(bp));

	/*
	 * The xfs_buf_log_item pointer is stored in b_fsprivate.  If
	 * it doesn't have one yet, then allocate one and initialize it.
	 * The checks to see if one is there are in xfs_buf_item_init().
	 */
	xfs_buf_item_init(bp, tp->t_mountp);

	/*
	 * Set the recursion count for the buffer within this transaction
	 * to 0.
	 */
	bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t*);
	ASSERT(!(bip->bli_flags & XFS_BLI_STALE));
	ASSERT(!(bip->bli_format.blf_flags & XFS_BLI_CANCEL));
	ASSERT(!(bip->bli_flags & XFS_BLI_LOGGED));
	bip->bli_recur = 0;

	/*
	 * Take a reference for this transaction on the buf item.
	 */
	atomic_inc(&bip->bli_refcount);

	/*
	 * Get a log_item_desc to point at the new item.
	 */
	(void) xfs_trans_add_item(tp, (xfs_log_item_t*)bip);

	/*
	 * Initialize b_fsprivate2 so we can find it with incore_match()
	 * above.
	 */
	XFS_BUF_SET_FSPRIVATE2(bp, tp);

	xfs_buftrace("TRANS GET", bp);
	xfs_buf_item_trace("GET", bip);
	return (bp);
}

/*
 * Get and lock the superblock buffer of this file system for the
 * given transaction.
 *
 * We don't need to use incore_match() here, because the superblock
 * buffer is a private buffer which we keep a pointer to in the
 * mount structure.
 */
xfs_buf_t *
xfs_trans_getsb(xfs_trans_t	*tp,
		struct xfs_mount *mp,
		int		flags)
{
	xfs_buf_t		*bp;
	xfs_buf_log_item_t	*bip;

	/*
	 * Default to just trying to lock the superblock buffer
	 * if tp is NULL.
	 */
	if (tp == NULL) {
		return (xfs_getsb(mp, flags));
	}

	/*
	 * If the superblock buffer already has this transaction
	 * pointer in its b_fsprivate2 field, then we know we already
	 * have it locked.  In this case we just increment the lock
	 * recursion count and return the buffer to the caller.
	 */
	bp = mp->m_sb_bp;
	if (XFS_BUF_FSPRIVATE2(bp, xfs_trans_t *) == tp) {
		bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t*);
		ASSERT(bip != NULL);
		ASSERT(atomic_read(&bip->bli_refcount) > 0);
		bip->bli_recur++;
		xfs_buf_item_trace("GETSB RECUR", bip);
		return (bp);
	}

	bp = xfs_getsb(mp, flags);
	if (bp == NULL) {
		return NULL;
	}

	/*
	 * The xfs_buf_log_item pointer is stored in b_fsprivate.  If
	 * it doesn't have one yet, then allocate one and initialize it.
	 * The checks to see if one is there are in xfs_buf_item_init().
	 */
	xfs_buf_item_init(bp, mp);

	/*
	 * Set the recursion count for the buffer within this transaction
	 * to 0.
	 */
	bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t*);
	ASSERT(!(bip->bli_flags & XFS_BLI_STALE));
	ASSERT(!(bip->bli_format.blf_flags & XFS_BLI_CANCEL));
	ASSERT(!(bip->bli_flags & XFS_BLI_LOGGED));
	bip->bli_recur = 0;

	/*
	 * Take a reference for this transaction on the buf item.
	 */
	atomic_inc(&bip->bli_refcount);

	/*
	 * Get a log_item_desc to point at the new item.
	 */
	(void) xfs_trans_add_item(tp, (xfs_log_item_t*)bip);

	/*
	 * Initialize b_fsprivate2 so we can find it with incore_match()
	 * above.
	 */
	XFS_BUF_SET_FSPRIVATE2(bp, tp);

	xfs_buf_item_trace("GETSB", bip);
	return (bp);
}

#ifdef DEBUG
xfs_buftarg_t *xfs_error_target;
int	xfs_do_error;
int	xfs_req_num;
int	xfs_error_mod = 33;
#endif

/*
 * Get and lock the buffer for the caller if it is not already
 * locked within the given transaction.  If it has not yet been
 * read in, read it from disk. If it is already locked
 * within the transaction and already read in, just increment its
 * lock recursion count and return a pointer to it.
 *
 * Use the fast path function xfs_trans_buf_item_match() or the buffer
 * cache routine incore_match() to find the buffer
 * if it is already owned by this transaction.
 *
 * If we don't already own the buffer, use read_buf() to get it.
 * If it doesn't yet have an associated xfs_buf_log_item structure,
 * then allocate one and add the item to this transaction.
 *
 * If the transaction pointer is NULL, make this just a normal
 * read_buf() call.
 */
int
xfs_trans_read_buf(
	xfs_mount_t	*mp,
	xfs_trans_t	*tp,
	xfs_buftarg_t	*target,
	xfs_daddr_t	blkno,
	int		len,
	uint		flags,
	xfs_buf_t	**bpp)
{
	xfs_buf_t		*bp;
	xfs_buf_log_item_t	*bip;
	int			error;

	if (flags == 0)
		flags = XFS_BUF_LOCK | XFS_BUF_MAPPED;

	/*
	 * Default to a normal get_buf() call if the tp is NULL.
	 */
	if (tp == NULL) {
		bp = xfs_buf_read_flags(target, blkno, len, flags | BUF_BUSY);
		if (!bp)
			return XFS_ERROR(ENOMEM);

		if ((bp != NULL) && (XFS_BUF_GETERROR(bp) != 0)) {
			xfs_ioerror_alert("xfs_trans_read_buf", mp,
					  bp, blkno);
			error = XFS_BUF_GETERROR(bp);
			xfs_buf_relse(bp);
			return error;
		}
#ifdef DEBUG
		if (xfs_do_error && (bp != NULL)) {
			if (xfs_error_target == target) {
				if (((xfs_req_num++) % xfs_error_mod) == 0) {
					xfs_buf_relse(bp);
					printk("Returning error!\n");
					return XFS_ERROR(EIO);
				}
			}
		}
#endif
		if (XFS_FORCED_SHUTDOWN(mp))
			goto shutdown_abort;
		*bpp = bp;
		return 0;
	}

	/*
	 * If we find the buffer in the cache with this transaction
	 * pointer in its b_fsprivate2 field, then we know we already
	 * have it locked.  If it is already read in we just increment
	 * the lock recursion count and return the buffer to the caller.
	 * If the buffer is not yet read in, then we read it in, increment
	 * the lock recursion count, and return it to the caller.
	 */
	if (tp->t_items.lic_next == NULL) {
		bp = xfs_trans_buf_item_match(tp, target, blkno, len);
	} else {
		bp = xfs_trans_buf_item_match_all(tp, target, blkno, len);
	}
	if (bp != NULL) {
		ASSERT(XFS_BUF_VALUSEMA(bp) <= 0);
		ASSERT(XFS_BUF_FSPRIVATE2(bp, xfs_trans_t *) == tp);
		ASSERT(XFS_BUF_FSPRIVATE(bp, void *) != NULL);
		ASSERT((XFS_BUF_ISERROR(bp)) == 0);
		if (!(XFS_BUF_ISDONE(bp))) {
			xfs_buftrace("READ_BUF_INCORE !DONE", bp);
			ASSERT(!XFS_BUF_ISASYNC(bp));
			XFS_BUF_READ(bp);
			xfsbdstrat(tp->t_mountp, bp);
			xfs_iowait(bp);
			if (XFS_BUF_GETERROR(bp) != 0) {
				xfs_ioerror_alert("xfs_trans_read_buf", mp,
						  bp, blkno);
				error = XFS_BUF_GETERROR(bp);
				xfs_buf_relse(bp);
				/*
				 * We can gracefully recover from most
				 * read errors. Ones we can't are those
				 * that happen after the transaction's
				 * already dirty.
				 */
				if (tp->t_flags & XFS_TRANS_DIRTY)
					xfs_force_shutdown(tp->t_mountp,
							   XFS_METADATA_IO_ERROR);
				return error;
			}
		}
		/*
		 * We never locked this buf ourselves, so we shouldn't
		 * brelse it either. Just get out.
		 */
		if (XFS_FORCED_SHUTDOWN(mp)) {
			xfs_buftrace("READ_BUF_INCORE XFSSHUTDN", bp);
			*bpp = NULL;
			return XFS_ERROR(EIO);
		}

		bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t*);
		bip->bli_recur++;

		ASSERT(atomic_read(&bip->bli_refcount) > 0);
		xfs_buf_item_trace("READ RECUR", bip);
		*bpp = bp;
		return 0;
	}

	/*
	 * We always specify the BUF_BUSY flag within a transaction so
	 * that get_buf does not try to push out a delayed write buffer
	 * which might cause another transaction to take place (if the
	 * buffer was delayed alloc).  Such recursive transactions can
	 * easily deadlock with our current transaction as well as cause
	 * us to run out of stack space.
	 */
	bp = xfs_buf_read_flags(target, blkno, len, flags | BUF_BUSY);
	if (bp == NULL) {
		*bpp = NULL;
		return 0;
	}
	if (XFS_BUF_GETERROR(bp) != 0) {
	    XFS_BUF_SUPER_STALE(bp);
		xfs_buftrace("READ ERROR", bp);
		error = XFS_BUF_GETERROR(bp);

		xfs_ioerror_alert("xfs_trans_read_buf", mp,
				  bp, blkno);
		if (tp->t_flags & XFS_TRANS_DIRTY)
			xfs_force_shutdown(tp->t_mountp, XFS_METADATA_IO_ERROR);
		xfs_buf_relse(bp);
		return error;
	}
#ifdef DEBUG
	if (xfs_do_error && !(tp->t_flags & XFS_TRANS_DIRTY)) {
		if (xfs_error_target == target) {
			if (((xfs_req_num++) % xfs_error_mod) == 0) {
				xfs_force_shutdown(tp->t_mountp,
						   XFS_METADATA_IO_ERROR);
				xfs_buf_relse(bp);
				printk("Returning error in trans!\n");
				return XFS_ERROR(EIO);
			}
		}
	}
#endif
	if (XFS_FORCED_SHUTDOWN(mp))
		goto shutdown_abort;

	/*
	 * The xfs_buf_log_item pointer is stored in b_fsprivate.  If
	 * it doesn't have one yet, then allocate one and initialize it.
	 * The checks to see if one is there are in xfs_buf_item_init().
	 */
	xfs_buf_item_init(bp, tp->t_mountp);

	/*
	 * Set the recursion count for the buffer within this transaction
	 * to 0.
	 */
	bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t*);
	ASSERT(!(bip->bli_flags & XFS_BLI_STALE));
	ASSERT(!(bip->bli_format.blf_flags & XFS_BLI_CANCEL));
	ASSERT(!(bip->bli_flags & XFS_BLI_LOGGED));
	bip->bli_recur = 0;

	/*
	 * Take a reference for this transaction on the buf item.
	 */
	atomic_inc(&bip->bli_refcount);

	/*
	 * Get a log_item_desc to point at the new item.
	 */
	(void) xfs_trans_add_item(tp, (xfs_log_item_t*)bip);

	/*
	 * Initialize b_fsprivate2 so we can find it with incore_match()
	 * above.
	 */
	XFS_BUF_SET_FSPRIVATE2(bp, tp);

	xfs_buftrace("TRANS READ", bp);
	xfs_buf_item_trace("READ", bip);
	*bpp = bp;
	return 0;

shutdown_abort:
	/*
	 * the theory here is that buffer is good but we're
	 * bailing out because the filesystem is being forcibly
	 * shut down.  So we should leave the b_flags alone since
	 * the buffer's not staled and just get out.
	 */
#if defined(DEBUG)
	if (XFS_BUF_ISSTALE(bp) && XFS_BUF_ISDELAYWRITE(bp))
		cmn_err(CE_NOTE, "about to pop assert, bp == 0x%p", bp);
#endif
	ASSERT((XFS_BUF_BFLAGS(bp) & (XFS_B_STALE|XFS_B_DELWRI)) !=
						(XFS_B_STALE|XFS_B_DELWRI));

	xfs_buftrace("READ_BUF XFSSHUTDN", bp);
	xfs_buf_relse(bp);
	*bpp = NULL;
	return XFS_ERROR(EIO);
}

/*
 * Release the buffer bp which was previously acquired with one of the
 * xfs_trans_... buffer allocation routines if the buffer has not
 * been modified within this transaction.  If the buffer is modified
 * within this transaction, do decrement the recursion count but do
 * not release the buffer even if the count goes to 0.  If the buffer is not
 * modified within the transaction, decrement the recursion count and
 * release the buffer if the recursion count goes to 0.
 *
 * If the buffer is to be released and it was not modified before
 * this transaction began, then free the buf_log_item associated with it.
 *
 * If the transaction pointer is NULL, make this just a normal
 * brelse() call.
 */
void
xfs_trans_brelse(xfs_trans_t	*tp,
		 xfs_buf_t	*bp)
{
	xfs_buf_log_item_t	*bip;
	xfs_log_item_t		*lip;
	xfs_log_item_desc_t	*lidp;

	/*
	 * Default to a normal brelse() call if the tp is NULL.
	 */
	if (tp == NULL) {
		ASSERT(XFS_BUF_FSPRIVATE2(bp, void *) == NULL);
		/*
		 * If there's a buf log item attached to the buffer,
		 * then let the AIL know that the buffer is being
		 * unlocked.
		 */
		if (XFS_BUF_FSPRIVATE(bp, void *) != NULL) {
			lip = XFS_BUF_FSPRIVATE(bp, xfs_log_item_t *);
			if (lip->li_type == XFS_LI_BUF) {
				bip = XFS_BUF_FSPRIVATE(bp,xfs_buf_log_item_t*);
				xfs_trans_unlocked_item(
						bip->bli_item.li_mountp,
						lip);
			}
		}
		xfs_buf_relse(bp);
		return;
	}

	ASSERT(XFS_BUF_FSPRIVATE2(bp, xfs_trans_t *) == tp);
	bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t *);
	ASSERT(bip->bli_item.li_type == XFS_LI_BUF);
	ASSERT(!(bip->bli_flags & XFS_BLI_STALE));
	ASSERT(!(bip->bli_format.blf_flags & XFS_BLI_CANCEL));
	ASSERT(atomic_read(&bip->bli_refcount) > 0);

	/*
	 * Find the item descriptor pointing to this buffer's
	 * log item.  It must be there.
	 */
	lidp = xfs_trans_find_item(tp, (xfs_log_item_t*)bip);
	ASSERT(lidp != NULL);

	/*
	 * If the release is just for a recursive lock,
	 * then decrement the count and return.
	 */
	if (bip->bli_recur > 0) {
		bip->bli_recur--;
		xfs_buf_item_trace("RELSE RECUR", bip);
		return;
	}

	/*
	 * If the buffer is dirty within this transaction, we can't
	 * release it until we commit.
	 */
	if (lidp->lid_flags & XFS_LID_DIRTY) {
		xfs_buf_item_trace("RELSE DIRTY", bip);
		return;
	}

	/*
	 * If the buffer has been invalidated, then we can't release
	 * it until the transaction commits to disk unless it is re-dirtied
	 * as part of this transaction.  This prevents us from pulling
	 * the item from the AIL before we should.
	 */
	if (bip->bli_flags & XFS_BLI_STALE) {
		xfs_buf_item_trace("RELSE STALE", bip);
		return;
	}

	ASSERT(!(bip->bli_flags & XFS_BLI_LOGGED));
	xfs_buf_item_trace("RELSE", bip);

	/*
	 * Free up the log item descriptor tracking the released item.
	 */
	xfs_trans_free_item(tp, lidp);

	/*
	 * Clear the hold flag in the buf log item if it is set.
	 * We wouldn't want the next user of the buffer to
	 * get confused.
	 */
	if (bip->bli_flags & XFS_BLI_HOLD) {
		bip->bli_flags &= ~XFS_BLI_HOLD;
	}

	/*
	 * Drop our reference to the buf log item.
	 */
	atomic_dec(&bip->bli_refcount);

	/*
	 * If the buf item is not tracking data in the log, then
	 * we must free it before releasing the buffer back to the
	 * free pool.  Before releasing the buffer to the free pool,
	 * clear the transaction pointer in b_fsprivate2 to dissolve
	 * its relation to this transaction.
	 */
	if (!xfs_buf_item_dirty(bip)) {
/***
		ASSERT(bp->b_pincount == 0);
***/
		ASSERT(atomic_read(&bip->bli_refcount) == 0);
		ASSERT(!(bip->bli_item.li_flags & XFS_LI_IN_AIL));
		ASSERT(!(bip->bli_flags & XFS_BLI_INODE_ALLOC_BUF));
		xfs_buf_item_relse(bp);
		bip = NULL;
	}
	XFS_BUF_SET_FSPRIVATE2(bp, NULL);

	/*
	 * If we've still got a buf log item on the buffer, then
	 * tell the AIL that the buffer is being unlocked.
	 */
	if (bip != NULL) {
		xfs_trans_unlocked_item(bip->bli_item.li_mountp,
					(xfs_log_item_t*)bip);
	}

	xfs_buf_relse(bp);
	return;
}

/*
 * Add the locked buffer to the transaction.
 * The buffer must be locked, and it cannot be associated with any
 * transaction.
 *
 * If the buffer does not yet have a buf log item associated with it,
 * then allocate one for it.  Then add the buf item to the transaction.
 */
void
xfs_trans_bjoin(xfs_trans_t	*tp,
		xfs_buf_t	*bp)
{
	xfs_buf_log_item_t	*bip;

	ASSERT(XFS_BUF_ISBUSY(bp));
	ASSERT(XFS_BUF_FSPRIVATE2(bp, void *) == NULL);

	/*
	 * The xfs_buf_log_item pointer is stored in b_fsprivate.  If
	 * it doesn't have one yet, then allocate one and initialize it.
	 * The checks to see if one is there are in xfs_buf_item_init().
	 */
	xfs_buf_item_init(bp, tp->t_mountp);
	bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t *);
	ASSERT(!(bip->bli_flags & XFS_BLI_STALE));
	ASSERT(!(bip->bli_format.blf_flags & XFS_BLI_CANCEL));
	ASSERT(!(bip->bli_flags & XFS_BLI_LOGGED));

	/*
	 * Take a reference for this transaction on the buf item.
	 */
	atomic_inc(&bip->bli_refcount);

	/*
	 * Get a log_item_desc to point at the new item.
	 */
	(void) xfs_trans_add_item(tp, (xfs_log_item_t *)bip);

	/*
	 * Initialize b_fsprivate2 so we can find it with incore_match()
	 * in xfs_trans_get_buf() and friends above.
	 */
	XFS_BUF_SET_FSPRIVATE2(bp, tp);

	xfs_buf_item_trace("BJOIN", bip);
}

/*
 * Mark the buffer as not needing to be unlocked when the buf item's
 * IOP_UNLOCK() routine is called.  The buffer must already be locked
 * and associated with the given transaction.
 */
/* ARGSUSED */
void
xfs_trans_bhold(xfs_trans_t	*tp,
		xfs_buf_t	*bp)
{
	xfs_buf_log_item_t	*bip;

	ASSERT(XFS_BUF_ISBUSY(bp));
	ASSERT(XFS_BUF_FSPRIVATE2(bp, xfs_trans_t *) == tp);
	ASSERT(XFS_BUF_FSPRIVATE(bp, void *) != NULL);

	bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t *);
	ASSERT(!(bip->bli_flags & XFS_BLI_STALE));
	ASSERT(!(bip->bli_format.blf_flags & XFS_BLI_CANCEL));
	ASSERT(atomic_read(&bip->bli_refcount) > 0);
	bip->bli_flags |= XFS_BLI_HOLD;
	xfs_buf_item_trace("BHOLD", bip);
}

/*
 * Cancel the previous buffer hold request made on this buffer
 * for this transaction.
 */
void
xfs_trans_bhold_release(xfs_trans_t	*tp,
			xfs_buf_t	*bp)
{
	xfs_buf_log_item_t	*bip;

	ASSERT(XFS_BUF_ISBUSY(bp));
	ASSERT(XFS_BUF_FSPRIVATE2(bp, xfs_trans_t *) == tp);
	ASSERT(XFS_BUF_FSPRIVATE(bp, void *) != NULL);

	bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t *);
	ASSERT(!(bip->bli_flags & XFS_BLI_STALE));
	ASSERT(!(bip->bli_format.blf_flags & XFS_BLI_CANCEL));
	ASSERT(atomic_read(&bip->bli_refcount) > 0);
	ASSERT(bip->bli_flags & XFS_BLI_HOLD);
	bip->bli_flags &= ~XFS_BLI_HOLD;
	xfs_buf_item_trace("BHOLD RELEASE", bip);
}

/*
 * This is called to mark bytes first through last inclusive of the given
 * buffer as needing to be logged when the transaction is committed.
 * The buffer must already be associated with the given transaction.
 *
 * First and last are numbers relative to the beginning of this buffer,
 * so the first byte in the buffer is numbered 0 regardless of the
 * value of b_blkno.
 */
void
xfs_trans_log_buf(xfs_trans_t	*tp,
		  xfs_buf_t	*bp,
		  uint		first,
		  uint		last)
{
	xfs_buf_log_item_t	*bip;
	xfs_log_item_desc_t	*lidp;

	ASSERT(XFS_BUF_ISBUSY(bp));
	ASSERT(XFS_BUF_FSPRIVATE2(bp, xfs_trans_t *) == tp);
	ASSERT(XFS_BUF_FSPRIVATE(bp, void *) != NULL);
	ASSERT((first <= last) && (last < XFS_BUF_COUNT(bp)));
	ASSERT((XFS_BUF_IODONE_FUNC(bp) == NULL) ||
	       (XFS_BUF_IODONE_FUNC(bp) == xfs_buf_iodone_callbacks));

	/*
	 * Mark the buffer as needing to be written out eventually,
	 * and set its iodone function to remove the buffer's buf log
	 * item from the AIL and free it when the buffer is flushed
	 * to disk.  See xfs_buf_attach_iodone() for more details
	 * on li_cb and xfs_buf_iodone_callbacks().
	 * If we end up aborting this transaction, we trap this buffer
	 * inside the b_bdstrat callback so that this won't get written to
	 * disk.
	 */
	XFS_BUF_DELAYWRITE(bp);
	XFS_BUF_DONE(bp);

	bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t *);
	ASSERT(atomic_read(&bip->bli_refcount) > 0);
	XFS_BUF_SET_IODONE_FUNC(bp, xfs_buf_iodone_callbacks);
	bip->bli_item.li_cb = (void(*)(xfs_buf_t*,xfs_log_item_t*))xfs_buf_iodone;

	/*
	 * If we invalidated the buffer within this transaction, then
	 * cancel the invalidation now that we're dirtying the buffer
	 * again.  There are no races with the code in xfs_buf_item_unpin(),
	 * because we have a reference to the buffer this entire time.
	 */
	if (bip->bli_flags & XFS_BLI_STALE) {
		xfs_buf_item_trace("BLOG UNSTALE", bip);
		bip->bli_flags &= ~XFS_BLI_STALE;
		ASSERT(XFS_BUF_ISSTALE(bp));
		XFS_BUF_UNSTALE(bp);
		bip->bli_format.blf_flags &= ~XFS_BLI_CANCEL;
	}

	lidp = xfs_trans_find_item(tp, (xfs_log_item_t*)bip);
	ASSERT(lidp != NULL);

	tp->t_flags |= XFS_TRANS_DIRTY;
	lidp->lid_flags |= XFS_LID_DIRTY;
	lidp->lid_flags &= ~XFS_LID_BUF_STALE;
	bip->bli_flags |= XFS_BLI_LOGGED;
	xfs_buf_item_log(bip, first, last);
	xfs_buf_item_trace("BLOG", bip);
}

/*
 * This called to invalidate a buffer that is being used within
 * a transaction.  Typically this is because the blocks in the
 * buffer are being freed, so we need to prevent it from being
 * written out when we're done.  Allowing it to be written again
 * might overwrite data in the free blocks if they are reallocated
 * to a file.
 *
 * We prevent the buffer from being written out by clearing the
 * B_DELWRI flag.  We can't always
 * get rid of the buf log item at this point, though, because
 * the buffer may still be pinned by another transaction.  If that
 * is the case, then we'll wait until the buffer is committed to
 * disk for the last time (we can tell by the ref count) and
 * free it in xfs_buf_item_unpin().  Until it is cleaned up we
 * will keep the buffer locked so that the buffer and buf log item
 * are not reused.
 */
void
xfs_trans_binval(
	xfs_trans_t	*tp,
	xfs_buf_t	*bp)
{
	xfs_log_item_desc_t	*lidp;
	xfs_buf_log_item_t	*bip;

	ASSERT(XFS_BUF_ISBUSY(bp));
	ASSERT(XFS_BUF_FSPRIVATE2(bp, xfs_trans_t *) == tp);
	ASSERT(XFS_BUF_FSPRIVATE(bp, void *) != NULL);

	bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t *);
	lidp = xfs_trans_find_item(tp, (xfs_log_item_t*)bip);
	ASSERT(lidp != NULL);
	ASSERT(atomic_read(&bip->bli_refcount) > 0);

	if (bip->bli_flags & XFS_BLI_STALE) {
		/*
		 * If the buffer is already invalidated, then
		 * just return.
		 */
		ASSERT(!(XFS_BUF_ISDELAYWRITE(bp)));
		ASSERT(XFS_BUF_ISSTALE(bp));
		ASSERT(!(bip->bli_flags & (XFS_BLI_LOGGED | XFS_BLI_DIRTY)));
		ASSERT(!(bip->bli_format.blf_flags & XFS_BLI_INODE_BUF));
		ASSERT(bip->bli_format.blf_flags & XFS_BLI_CANCEL);
		ASSERT(lidp->lid_flags & XFS_LID_DIRTY);
		ASSERT(tp->t_flags & XFS_TRANS_DIRTY);
		xfs_buftrace("XFS_BINVAL RECUR", bp);
		xfs_buf_item_trace("BINVAL RECUR", bip);
		return;
	}

	/*
	 * Clear the dirty bit in the buffer and set the STALE flag
	 * in the buf log item.  The STALE flag will be used in
	 * xfs_buf_item_unpin() to determine if it should clean up
	 * when the last reference to the buf item is given up.
	 * We set the XFS_BLI_CANCEL flag in the buf log format structure
	 * and log the buf item.  This will be used at recovery time
	 * to determine that copies of the buffer in the log before
	 * this should not be replayed.
	 * We mark the item descriptor and the transaction dirty so
	 * that we'll hold the buffer until after the commit.
	 *
	 * Since we're invalidating the buffer, we also clear the state
	 * about which parts of the buffer have been logged.  We also
	 * clear the flag indicating that this is an inode buffer since
	 * the data in the buffer will no longer be valid.
	 *
	 * We set the stale bit in the buffer as well since we're getting
	 * rid of it.
	 */
	XFS_BUF_UNDELAYWRITE(bp);
	XFS_BUF_STALE(bp);
	bip->bli_flags |= XFS_BLI_STALE;
	bip->bli_flags &= ~(XFS_BLI_LOGGED | XFS_BLI_DIRTY);
	bip->bli_format.blf_flags &= ~XFS_BLI_INODE_BUF;
	bip->bli_format.blf_flags |= XFS_BLI_CANCEL;
	memset((char *)(bip->bli_format.blf_data_map), 0,
	      (bip->bli_format.blf_map_size * sizeof(uint)));
	lidp->lid_flags |= XFS_LID_DIRTY|XFS_LID_BUF_STALE;
	tp->t_flags |= XFS_TRANS_DIRTY;
	xfs_buftrace("XFS_BINVAL", bp);
	xfs_buf_item_trace("BINVAL", bip);
}

/*
 * This call is used to indicate that the buffer contains on-disk
 * inodes which must be handled specially during recovery.  They
 * require special handling because only the di_next_unlinked from
 * the inodes in the buffer should be recovered.  The rest of the
 * data in the buffer is logged via the inodes themselves.
 *
 * All we do is set the XFS_BLI_INODE_BUF flag in the buffer's log
 * format structure so that we'll know what to do at recovery time.
 */
/* ARGSUSED */
void
xfs_trans_inode_buf(
	xfs_trans_t	*tp,
	xfs_buf_t	*bp)
{
	xfs_buf_log_item_t	*bip;

	ASSERT(XFS_BUF_ISBUSY(bp));
	ASSERT(XFS_BUF_FSPRIVATE2(bp, xfs_trans_t *) == tp);
	ASSERT(XFS_BUF_FSPRIVATE(bp, void *) != NULL);

	bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t *);
	ASSERT(atomic_read(&bip->bli_refcount) > 0);

	bip->bli_format.blf_flags |= XFS_BLI_INODE_BUF;
}

/*
 * This call is used to indicate that the buffer is going to
 * be staled and was an inode buffer. This means it gets
 * special processing during unpin - where any inodes
 * associated with the buffer should be removed from ail.
 * There is also special processing during recovery,
 * any replay of the inodes in the buffer needs to be
 * prevented as the buffer may have been reused.
 */
void
xfs_trans_stale_inode_buf(
	xfs_trans_t	*tp,
	xfs_buf_t	*bp)
{
	xfs_buf_log_item_t	*bip;

	ASSERT(XFS_BUF_ISBUSY(bp));
	ASSERT(XFS_BUF_FSPRIVATE2(bp, xfs_trans_t *) == tp);
	ASSERT(XFS_BUF_FSPRIVATE(bp, void *) != NULL);

	bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t *);
	ASSERT(atomic_read(&bip->bli_refcount) > 0);

	bip->bli_flags |= XFS_BLI_STALE_INODE;
	bip->bli_item.li_cb = (void(*)(xfs_buf_t*,xfs_log_item_t*))
		xfs_buf_iodone;
}

/*
 * Mark the buffer as being one which contains newly allocated
 * inodes.  We need to make sure that even if this buffer is
 * relogged as an 'inode buf' we still recover all of the inode
 * images in the face of a crash.  This works in coordination with
 * xfs_buf_item_committed() to ensure that the buffer remains in the
 * AIL at its original location even after it has been relogged.
 */
/* ARGSUSED */
void
xfs_trans_inode_alloc_buf(
	xfs_trans_t	*tp,
	xfs_buf_t	*bp)
{
	xfs_buf_log_item_t	*bip;

	ASSERT(XFS_BUF_ISBUSY(bp));
	ASSERT(XFS_BUF_FSPRIVATE2(bp, xfs_trans_t *) == tp);
	ASSERT(XFS_BUF_FSPRIVATE(bp, void *) != NULL);

	bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t *);
	ASSERT(atomic_read(&bip->bli_refcount) > 0);

	bip->bli_flags |= XFS_BLI_INODE_ALLOC_BUF;
}

/*
 * Similar to xfs_trans_inode_buf(), this marks the buffer as a cluster of
 * dquots. However, unlike in inode buffer recovery, dquot buffers get
 * recovered in their entirety. (Hence, no XFS_BLI_DQUOT_ALLOC_BUF flag).
 * The only thing that makes dquot buffers different from regular
 * buffers is that we must not replay dquot bufs when recovering
 * if a _corresponding_ quotaoff has happened. We also have to distinguish
 * between usr dquot bufs and grp dquot bufs, because usr and grp quotas
 * can be turned off independently.
 */
/* ARGSUSED */
void
xfs_trans_dquot_buf(
	xfs_trans_t	*tp,
	xfs_buf_t	*bp,
	uint		type)
{
	xfs_buf_log_item_t	*bip;

	ASSERT(XFS_BUF_ISBUSY(bp));
	ASSERT(XFS_BUF_FSPRIVATE2(bp, xfs_trans_t *) == tp);
	ASSERT(XFS_BUF_FSPRIVATE(bp, void *) != NULL);
	ASSERT(type == XFS_BLI_UDQUOT_BUF ||
	       type == XFS_BLI_PDQUOT_BUF ||
	       type == XFS_BLI_GDQUOT_BUF);

	bip = XFS_BUF_FSPRIVATE(bp, xfs_buf_log_item_t *);
	ASSERT(atomic_read(&bip->bli_refcount) > 0);

	bip->bli_format.blf_flags |= type;
}

/*
 * Check to see if a buffer matching the given parameters is already
 * a part of the given transaction.  Only check the first, embedded
 * chunk, since we don't want to spend all day scanning large transactions.
 */
STATIC xfs_buf_t *
xfs_trans_buf_item_match(
	xfs_trans_t	*tp,
	xfs_buftarg_t	*target,
	xfs_daddr_t	blkno,
	int		len)
{
	xfs_log_item_chunk_t	*licp;
	xfs_log_item_desc_t	*lidp;
	xfs_buf_log_item_t	*blip;
	xfs_buf_t		*bp;
	int			i;

	bp = NULL;
	len = BBTOB(len);
	licp = &tp->t_items;
	if (!XFS_LIC_ARE_ALL_FREE(licp)) {
		for (i = 0; i < licp->lic_unused; i++) {
			/*
			 * Skip unoccupied slots.
			 */
			if (XFS_LIC_ISFREE(licp, i)) {
				continue;
			}

			lidp = XFS_LIC_SLOT(licp, i);
			blip = (xfs_buf_log_item_t *)lidp->lid_item;
			if (blip->bli_item.li_type != XFS_LI_BUF) {
				continue;
			}

			bp = blip->bli_buf;
			if ((XFS_BUF_TARGET(bp) == target) &&
			    (XFS_BUF_ADDR(bp) == blkno) &&
			    (XFS_BUF_COUNT(bp) == len)) {
				/*
				 * We found it.  Break out and
				 * return the pointer to the buffer.
				 */
				break;
			} else {
				bp = NULL;
			}
		}
	}
	return bp;
}

/*
 * Check to see if a buffer matching the given parameters is already
 * a part of the given transaction.  Check all the chunks, we
 * want to be thorough.
 */
STATIC xfs_buf_t *
xfs_trans_buf_item_match_all(
	xfs_trans_t	*tp,
	xfs_buftarg_t	*target,
	xfs_daddr_t	blkno,
	int		len)
{
	xfs_log_item_chunk_t	*licp;
	xfs_log_item_desc_t	*lidp;
	xfs_buf_log_item_t	*blip;
	xfs_buf_t		*bp;
	int			i;

	bp = NULL;
	len = BBTOB(len);
	for (licp = &tp->t_items; licp != NULL; licp = licp->lic_next) {
		if (XFS_LIC_ARE_ALL_FREE(licp)) {
			ASSERT(licp == &tp->t_items);
			ASSERT(licp->lic_next == NULL);
			return NULL;
		}
		for (i = 0; i < licp->lic_unused; i++) {
			/*
			 * Skip unoccupied slots.
			 */
			if (XFS_LIC_ISFREE(licp, i)) {
				continue;
			}

			lidp = XFS_LIC_SLOT(licp, i);
			blip = (xfs_buf_log_item_t *)lidp->lid_item;
			if (blip->bli_item.li_type != XFS_LI_BUF) {
				continue;
			}

			bp = blip->bli_buf;
			if ((XFS_BUF_TARGET(bp) == target) &&
			    (XFS_BUF_ADDR(bp) == blkno) &&
			    (XFS_BUF_COUNT(bp) == len)) {
				/*
				 * We found it.  Break out and
				 * return the pointer to the buffer.
				 */
				return bp;
			}
		}
	}
	return NULL;
}


text:
layout: page
title: Noble Solutions Award Ceremony
date: 2016-05-24
author: Jennifer Fritz
tags: weekly links, java
status: published
summary: In arcu massa, venenatis eu magna id, lobortis semper.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 03/03/2016
  endDate: 03/06/2016
  ctyhocn: CVGKIHX
  groupCode: NSAC
published: true
---
Vestibulum massa lacus, luctus vitae dignissim id, varius nec turpis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam erat velit, suscipit at quam id, interdum venenatis ligula. Nullam id dolor et mauris efficitur luctus. Maecenas porta ex at ex ornare, id accumsan orci scelerisque. Nullam mattis, tellus eu gravida aliquam, eros libero imperdiet velit, sed suscipit massa neque at turpis. Donec et mi et elit hendrerit bibendum. Suspendisse potenti. Maecenas at nisl lectus. Vestibulum commodo nulla enim, ac dictum dolor posuere at. Sed sagittis arcu vitae metus cursus, ac mattis ex elementum. In bibendum ante euismod magna dignissim, at rhoncus augue condimentum.

* Vestibulum quis justo eget nunc cursus eleifend.

Curabitur auctor pulvinar venenatis. Fusce eget turpis placerat, facilisis massa quis, consequat purus. Phasellus nec faucibus ex. Fusce sagittis bibendum blandit. Fusce sodales, orci vitae viverra rhoncus, nisl elit aliquet lacus, vel volutpat nisi elit lacinia felis. Morbi malesuada nisl quis erat iaculis, id viverra tortor dapibus. Morbi vestibulum eros lectus, in lobortis purus laoreet in. Curabitur quis pellentesque enim, et gravida massa.


text:
/**
 * Created by pmeijer on 3/13/14.
 *
 * This script illustrates how you can pass arguments and options to a script.
 * This is a refactoring with some additions to Dana Zhang's script.
 *
 * This script is no module and only makes sense to execute from the command-line.
 * To see it in action you need to experiment on your own by passing values.
 * See some examples at the bottom.
 * For more options;
 * https://github.com/visionmedia/commander.js/
 * Or the Readmd.md after installing it.
 */

'use strict';
// We need the external library 'commander' for this script.
var program = require('commander');
// Add a simple true/false flag. (Will be undefined if not passed which translates to false in if-clauses.)
program.option('-v, --verbose', 'Do a lot of printing.');
// Add an option that takes a value and stores it. If not defined it will be undefined.
program.option('-s, --studentName <name>', 'Add a student name');
// Add an option that takes a value and stores it, and if not defined will get a default value.
program.option('-f, --fileName <name>', 'Add a file with given name. [info.txt]', 'info.txt');
// You can automatically get the parsed floats/integers. Note that dash in name translated in to camel-case.
// N.B. if not parseable parseable null will be returned. parseInt rounds to float.
program.option('-r, --a-float <value>', 'Pass a float.', parseFloat);
program.option('-n, --an-integer <value>', 'Pass an integer.', parseInt);
// You can pass any function as action.
function list(value) {
    return value.split(';');
}
// Be careful when you pass spaces, add quotes to fix this potential issue.
program.option('-p, --paths <items>', 'Paths, (separated by semicolons), to some resources.', list);

// Parsing of the arguments.
program.parse(process.argv);

console.log('verbose     : (%j, %j)', program.verbose, typeof program.verbose);
console.log('studentName : (%j, %j)', program.studentName, typeof program.studentName);
console.log('fileName    : (%j, %j)', program.fileName, typeof program.fileName);
console.log('aFloat      : (%j, %j)', program.aFloat, typeof program.aFloat);
console.log('anInteger   : (%j, %j)', program.anInteger, typeof program.anInteger);
console.log('paths       : (%j, %j)', program.paths, typeof program.paths);
// args contains all other arguments that are not an argument of a flag
console.log('Arguments  :: (%j, %j)', program.args, typeof program.args);

// commander has a built-in flag -h or --help that lists all the available options that can be set
// > node argparser.js -h
// > node argparser.js -v
// > node argparser.js -s olle
// > node argparser.js -r 3.14
// > node argparser.js -n 3.14
// > node argparser.js -n three
// > node argparser.js -p "C:\folder w sp\trk.txt;C:\file.txt"
// > node argparser.js -p C:\folder w sp\trk.txt;C:\file.txt


text:
#ifndef QVARIANT_H
#define QVARIANT_H

#include <QtCore/qatomic.h>
#include <QtCore/qbytearray.h>
#include <QtCore/qlist.h>
#include <QtCore/qmetatype.h>
#include <QtCore/qmap.h>
#include <QtCore/qhash.h>
#include <QtCore/qstring.h>
#include <QtCore/qobject.h>

QT_BEGIN_NAMESPACE

class QBitArray;
class QDataStream;
class QDate;
class QDateTime;
class QEasingCurve;
class QLine;
class QLineF;
class QLocale;
class QMatrix;
class QTransform;
class QStringList;
class QTime;
class QPoint;
class QPointF;
class QSize;
class QSizeF;
class QRect;
class QRectF;
#ifndef QT_NO_REGEXP
class QRegExp;
#endif // QT_NO_REGEXP
#ifndef QT_NO_REGULAREXPRESSION
class QRegularExpression;
#endif // QT_NO_REGULAREXPRESSION
class QTextFormat;
class QTextLength;
class QUrl;
class QVariant;
class QVariantComparisonHelper;

template <typename T>
inline QVariant qVariantFromValue(const T &);

template<typename T>
inline T qvariant_cast(const QVariant &);

namespace QtPrivate {

    template <typename Derived, typename Argument, typename ReturnType>
    struct ObjectInvoker
    {
        static ReturnType invoke(Argument a)
        {
            return Derived::object(a);
        }
    };

    template <typename Derived, typename Argument, typename ReturnType>
    struct MetaTypeInvoker
    {
        static ReturnType invoke(Argument a)
        {
            return Derived::metaType(a);
        }
    };

    template <typename Derived, typename T, typename Argument, typename ReturnType, bool = IsPointerToTypeDerivedFromQObject<T>::Value>
    struct TreatAsQObjectBeforeMetaType : ObjectInvoker<Derived, Argument, ReturnType>
    {
    };

    template <typename Derived, typename T, typename Argument, typename ReturnType>
    struct TreatAsQObjectBeforeMetaType<Derived, T, Argument, ReturnType, false> : MetaTypeInvoker<Derived, Argument, ReturnType>
    {
    };

    template<typename T> struct QVariantValueHelper;
}

class Q_CORE_EXPORT QVariant
{
 public:
    enum Type {
        Invalid = QMetaType::UnknownType,
        Bool = QMetaType::Bool,
        Int = QMetaType::Int,
        UInt = QMetaType::UInt,
        LongLong = QMetaType::LongLong,
        ULongLong = QMetaType::ULongLong,
        Double = QMetaType::Double,
        Char = QMetaType::QChar,
        Map = QMetaType::QVariantMap,
        List = QMetaType::QVariantList,
        String = QMetaType::QString,
        StringList = QMetaType::QStringList,
        ByteArray = QMetaType::QByteArray,
        BitArray = QMetaType::QBitArray,
        Date = QMetaType::QDate,
        Time = QMetaType::QTime,
        DateTime = QMetaType::QDateTime,
        Url = QMetaType::QUrl,
        Locale = QMetaType::QLocale,
        Rect = QMetaType::QRect,
        RectF = QMetaType::QRectF,
        Size = QMetaType::QSize,
        SizeF = QMetaType::QSizeF,
        Line = QMetaType::QLine,
        LineF = QMetaType::QLineF,
        Point = QMetaType::QPoint,
        PointF = QMetaType::QPointF,
        RegExp = QMetaType::QRegExp,
        RegularExpression = QMetaType::QRegularExpression,
        Hash = QMetaType::QVariantHash,
        EasingCurve = QMetaType::QEasingCurve,
        Uuid = QMetaType::QUuid,
        ModelIndex = QMetaType::QModelIndex,
        LastCoreType = QMetaType::LastCoreType,

        Font = QMetaType::QFont,
        Pixmap = QMetaType::QPixmap,
        Brush = QMetaType::QBrush,
        Color = QMetaType::QColor,
        Palette = QMetaType::QPalette,
        Image = QMetaType::QImage,
        Polygon = QMetaType::QPolygon,
        Region = QMetaType::QRegion,
        Bitmap = QMetaType::QBitmap,
        Cursor = QMetaType::QCursor,
        KeySequence = QMetaType::QKeySequence,
        Pen = QMetaType::QPen,
        TextLength = QMetaType::QTextLength,
        TextFormat = QMetaType::QTextFormat,
        Matrix = QMetaType::QMatrix,
        Transform = QMetaType::QTransform,
        Matrix4x4 = QMetaType::QMatrix4x4,
        Vector2D = QMetaType::QVector2D,
        Vector3D = QMetaType::QVector3D,
        Vector4D = QMetaType::QVector4D,
        Quaternion = QMetaType::QQuaternion,
        PolygonF = QMetaType::QPolygonF,
        Icon = QMetaType::QIcon,
        LastGuiType = QMetaType::LastGuiType,

        SizePolicy = QMetaType::QSizePolicy,

        UserType = QMetaType::User,
        LastType = 0xffffffff // need this so that gcc >= 3.4 allocates 32 bits for Type
    };

    inline QVariant();
    ~QVariant();
    QVariant(Type type);
    QVariant(int typeId, const void *copy);
    QVariant(int typeId, const void *copy, uint flags);
    QVariant(const QVariant &other);

#ifndef QT_NO_DATASTREAM
    QVariant(QDataStream &s);
#endif

    QVariant(int i);
    QVariant(uint ui);
    QVariant(qlonglong ll);
    QVariant(qulonglong ull);
    QVariant(bool b);
    QVariant(double d);
    QVariant(float f);
#ifndef QT_NO_CAST_FROM_ASCII
    QT_ASCII_CAST_WARN QVariant(const char *str);
#endif

    QVariant(const QByteArray &bytearray);
    QVariant(const QBitArray &bitarray);
    QVariant(const QString &string);
    QVariant(QLatin1String string);
    QVariant(const QStringList &stringlist);
    QVariant(QChar qchar);
    QVariant(const QDate &date);
    QVariant(const QTime &time);
    QVariant(const QDateTime &datetime);
    QVariant(const QList<QVariant> &list);
    QVariant(const QMap<QString,QVariant> &map);
    QVariant(const QHash<QString,QVariant> &hash);
#ifndef QT_NO_GEOM_VARIANT
    QVariant(const QSize &size);
    QVariant(const QSizeF &size);
    QVariant(const QPoint &pt);
    QVariant(const QPointF &pt);
    QVariant(const QLine &line);
    QVariant(const QLineF &line);
    QVariant(const QRect &rect);
    QVariant(const QRectF &rect);
#endif
    QVariant(const QLocale &locale);
#ifndef QT_NO_REGEXP
    QVariant(const QRegExp &regExp);
#endif // QT_NO_REGEXP
#ifndef QT_BOOTSTRAPPED
#ifndef QT_NO_REGULAREXPRESSION
    QVariant(const QRegularExpression &re);
#endif // QT_NO_REGULAREXPRESSION
    QVariant(const QUrl &url);
    QVariant(const QEasingCurve &easing);
    QVariant(const QUuid &uuid);
    QVariant(const QModelIndex &modelIndex);
    QVariant(const QJsonValue &jsonValue);
    QVariant(const QJsonObject &jsonObject);
    QVariant(const QJsonArray &jsonArray);
    QVariant(const QJsonDocument &jsonDocument);
#endif // QT_BOOTSTRAPPED

    QVariant& operator=(const QVariant &other);
#ifdef Q_COMPILER_RVALUE_REFS
    inline QVariant(QVariant &&other) : d(other.d)
    { other.d = Private(); }
    inline QVariant &operator=(QVariant &&other)
    { qSwap(d, other.d); return *this; }
#endif

    inline void swap(QVariant &other) { qSwap(d, other.d); }

    Type type() const;
    int userType() const;
    const char *typeName() const;

    bool canConvert(int targetTypeId) const;
    bool convert(int targetTypeId);

    inline bool isValid() const;
    bool isNull() const;

    void clear();

    void detach();
    inline bool isDetached() const;

    int toInt(bool *ok = 0) const;
    uint toUInt(bool *ok = 0) const;
    qlonglong toLongLong(bool *ok = 0) const;
    qulonglong toULongLong(bool *ok = 0) const;
    bool toBool() const;
    double toDouble(bool *ok = 0) const;
    float toFloat(bool *ok = 0) const;
    qreal toReal(bool *ok = 0) const;
    QByteArray toByteArray() const;
    QBitArray toBitArray() const;
    QString toString() const;
    QStringList toStringList() const;
    QChar toChar() const;
    QDate toDate() const;
    QTime toTime() const;
    QDateTime toDateTime() const;
    QList<QVariant> toList() const;
    QMap<QString, QVariant> toMap() const;
    QHash<QString, QVariant> toHash() const;

#ifndef QT_NO_GEOM_VARIANT
    QPoint toPoint() const;
    QPointF toPointF() const;
    QRect toRect() const;
    QSize toSize() const;
    QSizeF toSizeF() const;
    QLine toLine() const;
    QLineF toLineF() const;
    QRectF toRectF() const;
#endif
    QLocale toLocale() const;
#ifndef QT_NO_REGEXP
    QRegExp toRegExp() const;
#endif // QT_NO_REGEXP
#ifndef QT_BOOTSTRAPPED
#ifndef QT_NO_REGULAREXPRESSION
    QRegularExpression toRegularExpression() const;
#endif // QT_NO_REGULAREXPRESSION
    QUrl toUrl() const;
    QEasingCurve toEasingCurve() const;
    QUuid toUuid() const;
    QModelIndex toModelIndex() const;
    QJsonValue toJsonValue() const;
    QJsonObject toJsonObject() const;
    QJsonArray toJsonArray() const;
    QJsonDocument toJsonDocument() const;
#endif // QT_BOOTSTRAPPED

#ifndef QT_NO_DATASTREAM
    void load(QDataStream &ds);
    void save(QDataStream &ds) const;
#endif
    static const char *typeToName(int typeId);
    static Type nameToType(const char *name);

    void *data();
    const void *constData() const;
    inline const void *data() const { return constData(); }

    template<typename T>
    inline void setValue(const T &value);

    template<typename T>
    inline T value() const
    { return qvariant_cast<T>(*this); }

    template<typename T>
    static inline QVariant fromValue(const T &value)
    { return qVariantFromValue(value); }

    template<typename T>
    bool canConvert() const
    { return canConvert(qMetaTypeId<T>()); }

 public:
#ifndef Q_QDOC
    struct PrivateShared
    {
        inline PrivateShared(void *v) : ptr(v), ref(1) { }
        void *ptr;
        QAtomicInt ref;
    };
    struct Private
    {
        inline Private(): type(Invalid), is_shared(false), is_null(true)
        { data.ptr = 0; }

        // Internal constructor for initialized variants.
        explicit inline Private(uint variantType)
            : type(variantType), is_shared(false), is_null(false)
        {}

        inline Private(const Private &other)
            : data(other.data), type(other.type),
              is_shared(other.is_shared), is_null(other.is_null)
        {}
        union Data
        {
            char c;
            uchar uc;
            short s;
            signed char sc;
            ushort us;
            int i;
            uint u;
            long l;
            ulong ul;
            bool b;
            double d;
            float f;
            qreal real;
            qlonglong ll;
            qulonglong ull;
            QObject *o;
            void *ptr;
            PrivateShared *shared;
        } data;
        uint type : 30;
        uint is_shared : 1;
        uint is_null : 1;
    };
 public:
    typedef void (*f_construct)(Private *, const void *);
    typedef void (*f_clear)(Private *);
    typedef bool (*f_null)(const Private *);
#ifndef QT_NO_DATASTREAM
    typedef void (*f_load)(Private *, QDataStream &);
    typedef void (*f_save)(const Private *, QDataStream &);
#endif
    typedef bool (*f_compare)(const Private *, const Private *);
    typedef bool (*f_convert)(const QVariant::Private *d, int t, void *, bool *);
    typedef bool (*f_canConvert)(const QVariant::Private *d, int t);
    typedef void (*f_debugStream)(QDebug, const QVariant &);
    struct Handler {
        f_construct construct;
        f_clear clear;
        f_null isNull;
#ifndef QT_NO_DATASTREAM
        f_load load;
        f_save save;
#endif
        f_compare compare;
        f_convert convert;
        f_canConvert canConvert;
        f_debugStream debugStream;
    };
#endif

    inline bool operator==(const QVariant &v) const
    { return cmp(v); }
    inline bool operator!=(const QVariant &v) const
    { return !cmp(v); }

protected:
    friend inline bool operator==(const QVariant &, const QVariantComparisonHelper &);
#ifndef QT_NO_DEBUG_STREAM
    friend Q_CORE_EXPORT QDebug operator<<(QDebug, const QVariant &);
#endif
#ifndef Q_NO_TEMPLATE_FRIENDS
    template<typename T>
    friend inline T qvariant_cast(const QVariant &);
    template<typename T> friend struct QtPrivate::QVariantValueHelper;
protected:
#else
public:
#endif
    Private d;
    void create(int type, const void *copy);
    bool cmp(const QVariant &other) const;
    bool convert(const int t, void *ptr) const;

private:
    // force compile error, prevent QVariant(bool) to be called
    inline QVariant(void *) Q_DECL_EQ_DELETE;
    // QVariant::Type is marked as \obsolete, but we don't want to
    // provide a constructor from its intended replacement,
    // QMetaType::Type, instead, because the idea behind these
    // constructors is flawed in the first place. But we also don't
    // want QVariant(QMetaType::String) to compile and falsely be an
    // int variant, so delete this constructor:
    QVariant(QMetaType::Type) Q_DECL_EQ_DELETE;

    // These constructors don't create QVariants of the type associcated
    // with the enum, as expected, but they would create a QVariant of
    // type int with the value of the enum value.
    // Use QVariant v = QColor(Qt::red) instead of QVariant v = Qt::red for
    // example.
    QVariant(Qt::GlobalColor) Q_DECL_EQ_DELETE;
    QVariant(Qt::BrushStyle) Q_DECL_EQ_DELETE;
    QVariant(Qt::PenStyle) Q_DECL_EQ_DELETE;
    QVariant(Qt::CursorShape) Q_DECL_EQ_DELETE;
#ifdef QT_NO_CAST_FROM_ASCII
    // force compile error when implicit conversion is not wanted
    inline QVariant(const char *) Q_DECL_EQ_DELETE;
#endif
public:
    typedef Private DataPtr;
    inline DataPtr &data_ptr() { return d; }
    inline const DataPtr &data_ptr() const { return d; }
};

template <typename T>
inline QVariant qVariantFromValue(const T &t)
{
    return QVariant(qMetaTypeId<T>(), &t, QTypeInfo<T>::isPointer);
}

template <>
inline QVariant qVariantFromValue(const QVariant &t) { return t; }

template <typename T>
inline void qVariantSetValue(QVariant &v, const T &t)
{
    //if possible we reuse the current QVariant private
    const uint type = qMetaTypeId<T>();
    QVariant::Private &d = v.data_ptr();
    if (v.isDetached() && (type == d.type || (type <= uint(QVariant::Char) && d.type <= uint(QVariant::Char)))) {
        d.type = type;
        d.is_null = false;
        T *old = reinterpret_cast<T*>(d.is_shared ? d.data.shared->ptr : &d.data.ptr);
        if (QTypeInfo<T>::isComplex)
            old->~T();
        new (old) T(t); //call the copy constructor
    } else {
        v = QVariant(type, &t, QTypeInfo<T>::isPointer);
    }
}

template <>
inline void qVariantSetValue<QVariant>(QVariant &v, const QVariant &t)
{
    v = t;
}

inline QVariant::QVariant() {}
inline bool QVariant::isValid() const { return d.type != Invalid; }

template<typename T>
inline void QVariant::setValue(const T &avalue)
{ qVariantSetValue(*this, avalue); }

#ifndef QT_NO_DATASTREAM
Q_CORE_EXPORT QDataStream& operator>> (QDataStream& s, QVariant& p);
Q_CORE_EXPORT QDataStream& operator<< (QDataStream& s, const QVariant& p);
Q_CORE_EXPORT QDataStream& operator>> (QDataStream& s, QVariant::Type& p);
Q_CORE_EXPORT QDataStream& operator<< (QDataStream& s, const QVariant::Type p);
#endif

inline bool QVariant::isDetached() const
{ return !d.is_shared || d.data.shared->ref.load() == 1; }

#ifdef Q_QDOC
    inline bool operator==(const QVariant &v1, const QVariant &v2);
    inline bool operator!=(const QVariant &v1, const QVariant &v2);
#else

/* Helper class to add one more level of indirection to prevent
   implicit casts.
*/
class QVariantComparisonHelper
{
public:
    inline QVariantComparisonHelper(const QVariant &var)
        : v(&var) {}
private:
    friend inline bool operator==(const QVariant &, const QVariantComparisonHelper &);
    const QVariant *v;
};

inline bool operator==(const QVariant &v1, const QVariantComparisonHelper &v2)
{
    return v1.cmp(*v2.v);
}

inline bool operator!=(const QVariant &v1, const QVariantComparisonHelper &v2)
{
    return !operator==(v1, v2);
}
#endif

namespace QtPrivate {
    template<typename T>
    struct QVariantValueHelper : TreatAsQObjectBeforeMetaType<QVariantValueHelper<T>, T, const QVariant &, T>
    {
        static T metaType(const QVariant &v)
        {
            const int vid = qMetaTypeId<T>();
            if (vid == v.userType())
                return *reinterpret_cast<const T *>(v.constData());
            if (vid < int(QMetaType::User)) {
                T t;
                if (v.convert(vid, &t))
                    return t;
            }
            return T();
        }
#ifndef QT_NO_QOBJECT
        static T object(const QVariant &v)
        {
            return qobject_cast<T>(QMetaType::typeFlags(v.userType()) & QMetaType::PointerToQObject ? v.d.data.o : 0);
        }
#endif
    };
}

#ifndef QT_MOC
template<typename T> inline T qvariant_cast(const QVariant &v)
{
    return QtPrivate::QVariantValueHelper<T>::invoke(v);
}

template<> inline QVariant qvariant_cast<QVariant>(const QVariant &v)
{
    if (v.userType() == QMetaType::QVariant)
        return *reinterpret_cast<const QVariant *>(v.constData());
    return v;
}

#if QT_DEPRECATED_SINCE(5, 0)
template<typename T>
inline QT_DEPRECATED T qVariantValue(const QVariant &variant)
{ return qvariant_cast<T>(variant); }

template<typename T>
inline QT_DEPRECATED bool qVariantCanConvert(const QVariant &variant)
{ return variant.template canConvert<T>(); }
#endif

#endif
Q_DECLARE_SHARED(QVariant)

#ifndef QT_NO_DEBUG_STREAM
Q_CORE_EXPORT QDebug operator<<(QDebug, const QVariant &);
Q_CORE_EXPORT QDebug operator<<(QDebug, const QVariant::Type);
#endif

QT_END_NAMESPACE

#endif // QVARIANT_H


text:
from __future__ import division

from iecell import IECell

################################################################################

def widgetName():
    """ widgetName() -> str
    Return the name of this widget plugin

    """
    return 'Internet Explorer Control'

def registerWidget(reg, basicModules, basicWidgets):
    """ registerWidget(reg: module_registry,
                       basicModules: python package,
                       basicWidgets: python package) -> None
    Register all widgets in this package to VisTrails module_registry

    """
    reg.add_module(IECell)
    reg.add_input_port(IECell, "Location", basicWidgets.CellLocation)
    reg.add_input_port(IECell, "url", basicModules.String)
    reg.add_input_port(IECell, "file", basicModules.File)


text:
<!doctype html>

  <title>TxtAdv - Text Adventure Javascript Game Engine</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="reset.css" type="text/css" />
<link rel="stylesheet" href="txtadv.css" type="text/css" />

<form onSubmit="return false;"><input type=text  autofocus autocomplete="off" name="command" id="command" value="" class="command-input" onkeydown="if (event.keyCode == 13) {  return false; }" onkeyup="if (event.keyCode == 13) { processCommand(this); return false; }" ><input type=button value="Submit" class="command-button" onClick="processCommand(this.form.command); return false;"></form>

TextAdv © 2014 by Ben McGaughey (type help for command reference)

{

	"title" : "Example Dungeon Game made with TxtAdv",
	"version" : "0.01",
	"firstRoom" : "dungeon",
	"defaultCommand" : "Enter a command below:",
	"inventoryName" : "INVENTORY:",
	"inventoryDefaultText" : "You currently have no items in your inventory.",

	"vars" : [

		{ "varName" : "lookedAtDungeon", "value" : "false" },
		{ "varName" : "lookedAtGrate", "value" : "false" }

	],

	"items" : [

		{

			"name" : "Coin",
			"inventoryName" : "Coin",
			"properties" : {
				"look"  : "A single gold coin is lying on the ground.",
				"desc" : "A single gold coin you found on the floor in the dungeon."
			}

		},
		{

			"name" : "Hammer",
			"inventoryName" : "Hammer",
			"properties" : {
				"look"  : "You see a hammer sitting on the table. You can probably take it, who'd notice?",
				"desc" : "A solid iron hammer."
			}

		}

	],

	"rooms" : [

		{

			"name" : "dungeon",

			"description" : "You find yourself in a cold, dark, damp, dungeon, deep beneath the courtyard of Shadow Castle.

It's dark, but luckily your eyes have mostly adjusted.  Something is different, something has changed over night, you need to look around.",

			"items" : [

				{ "name" : "Coin" }

			],

			"inputs" : [

				{

					"query" : "any",

					"command" : "climb|pull|grab|reach+rope",

					"gotoConditions" : [
						{
							"variable" : "lookedAtDungeon",
							"qualifier" : "=",
							"condition" : "true",
							"errorMessage" : "What rope? Look around first..."
						}
					],

					"gotoRoom" : "grate"

				},

				{

					"query" : "any",

					"command" : "look|examine+around|",

					"moreInfo" : "You've been here for days.  The walls are dripping with cold water from the earth behind them, and moss grows from the crevice of every stone.  Though it's dark, you can somewhat make-out the sight of bones of other prisoners who didn't make it.  They've been there a long time, yet they don't smell, the rats have devoured most of their remains.

You see a grate above you with a bit of light shining through. From it hangs a rope. Someone must have put it there overnight, it wasn't there yesterday.  Someone is trying to help you!

The small amount of light from the grate hurts your eyes.  The light... and the rope... you may be able to survive this ordeal afterall!

You can probably just barely reach the rope if you try.<Coin>

You also notice a small gold coin lying next to a corpse.</Coin>",

					"setVars" : [

						{ "variable" : "lookedAtDungeon", "value" : "true" }

					]

				}

			]

		},

		{

			"name" : "grate",

			"description" : "You climb up the rope slowly, using every last muscle in your body.  But when you reach the top, you find that the grate is locked!  What is this?  A cruel joke?  Someone gives you this rope, this ounce of hope, but nothing more? You still appear to be trapped, and just as you are about to fall from the rope, most certainly crushing your bones as you hit the stone floor, you notice something about the grate...",

			"inputs" : [

				{

					"query" : "any",

					"command" : "look|examine+grate",

					"moreInfo" : "The grate may be locked, but the hinges and bars seem brittle and old.  It would probably take almost nothing to break through them.  They are so high up in the dungeon, no-one either noticed or bothered to replace them.  This could be your chance!",

					"setVars" : [

						{ "variable" : "lookedAtGrate", "value" : "true" }

					]

				},

				{

					"query" : "exact",
					"command" : "unlock|open+grate",
					"moreInfo" : "You don't hav a key."

				},

				{

					"query" : "exact",
					"command" : "push|pull|hit|break|smash+grate",
					"gotoConditions" : [
						{ "variable" : "lookedAtGrate", "qualifier" : "=", "condition" : "true", "errorMessage" : "You should look more closely at the grate first." }
					],
					"gotoRoom" : "courtyard",
					"moreInfo" : "You don't hav a key."

				}

			]

		},

		{

			"name" : "courtyard",

			"description" : "You break through the grate with all your might!  It opens!

Tired, starving, and weak, you muster your last bit of strength to pull your body up and out of the dungeon.

You find yourself standing in the center of a castle courtyard, people are all around, working and minding their own business.  It doesn't appear that anyone has noticed you... yet.

Hide somewhere!

Talk to a passer-bye

Just run away...

",

			"inputs" : [

				{

					"query" : "exact",
					"command" : "hide",
					"gotoRoom" : "blacksmithshop"

				},

				{

					"query" : "any",
					"command" : "talk",
					"moreInfo" : "You try to speak with people around you, but they just look at you in disgust.  You have been living in a dungeon for many days now.  Better not be so forward, what if someone recognizes you as the inmate!"

				},

				{

					"query" : "any",
					"command" : "run",
					"gotoRoom" : "gameover"

				}

			]

		},

		{

			"name" : "blacksmithshop",

			"description" : "You duck and cover in a nearby blacksmith shop.  Nobody seems to be around, most of the tools are put away.  It's dirty and cold, all the tools are cold, the oven has been cleaned out.

You can also go back to the courtyard from here.",

			"items" : [

				{ "name" : "Hammer" }

			],

			"inputs" : [

				{

					"query" : "any",
					"command" : "go|+courtyard",
					"gotoRoom" : "courtyard"

				}

			]

		},

		{

			"name" : "gameover",

			"description" : "You made a terrible decision that has resulted in your immediate death.

Game over."

		}

	]

}


text: I am the adapter used to bridget a SliderModel and a PluggableSliderMorph


text:
package org.sagebionetworks.web.client.widget.table.modal.upload;

import java.util.List;
import org.sagebionetworks.repo.model.table.ColumnModel;
import org.sagebionetworks.repo.model.table.UploadToTableRequest;
import org.sagebionetworks.web.client.widget.table.modal.wizard.ModalPage;

public interface UploadCSVFinishPage extends ModalPage {
	/**
	 * Configure this widget before using it.
	 *
	 * @param fileName
	 * @param parentId
	 * @param request
	 * @param suggestedSchema
	 */
	public void configure(String fileName, String parentId, UploadToTableRequest request, List<ColumnModel> suggestedSchema);

	/**
	 * Get the current state of the schema.
	 *
	 * @return
	 */
	public List<ColumnModel> getCurrentSchema();

}


text:
/* $Id$ */

package org.apache.fop.render.pcl;

import java.io.ObjectStreamException;

/**
 * Enumeration class for PCL rendering modes.
 */
public enum PCLRenderingMode {
    /** "Quality" rendering (mixed native and bitmap for improved quality) */
    QUALITY("quality", 1.0f),
    /** "Speed" rendering (maximum speed with native rendering, reduced visual quality) */
    SPEED("speed", 0.25f),
    /**
     * "Bitmap" rendering (pages are painted entirely as bitmaps, maximum quality,
     * reduced performance)
     */
    BITMAP("bitmap", 1.0f);

    private static final long serialVersionUID = 6359884255324755026L;
    private String name;
    private float defaultDitheringQuality;

    /**
     * Constructor to add a new named item.
     * @param name Name of the item.
     * @param defaultDitheringQuality the default dithering quality (0.0f..1.0f)
     */
    private PCLRenderingMode(String name, float defaultDitheringQuality) {
        this.name = name;
        this.defaultDitheringQuality = defaultDitheringQuality;
    }

    /** @return the name of the enum */
    public String getName() {
        return this.name;
    }

    /**
     * Returns the default dithering quality for this rendering mode.
     * @return the default dithering quality (0.0f..1.0f)
     */
    public float getDefaultDitheringQuality() {
        return this.defaultDitheringQuality;
    }

    /**
     * Returns the enumeration/singleton object based on its name.
     * @param name the name of the enumeration value
     * @return the enumeration object
     */
    public static PCLRenderingMode getValueOf(String name) {
        for (PCLRenderingMode mode : PCLRenderingMode.values()) {
            if (mode.getName().equalsIgnoreCase(name)) {
                return mode;
            }
        }
        throw new IllegalArgumentException("Illegal value for enumeration: " + name);
    }

    private Object readResolve() throws ObjectStreamException {
        return getValueOf(getName());
    }

    /** {@inheritDoc} */
    @Override
    public String toString() {
        return "PCLRenderingMode:" + name;
    }
}


text:
/* !!!! GENERATED FILE - DO NOT EDIT !!!! */

/*
 * Copyright (c) 2014 liblcf authors
 * This file is released under the MIT License
 * http://opensource.org/licenses/MIT
 */

// Headers
#include "ldb_reader.h"
#include "ldb_chunks.h"
#include "reader_struct.h"

// Read BattlerAnimationExtension.

#define LCF_CHUNK_SUFFIX LDB_Reader
#define LCF_CURRENT_STRUCT BattlerAnimationExtension

LCF_STRUCT_FIELDS_BEGIN()
	LCF_STRUCT_TYPED_FIELD(std::string, name),
	LCF_STRUCT_TYPED_FIELD(std::string, battler_name),
	LCF_STRUCT_TYPED_FIELD(int, battler_index),
	LCF_STRUCT_TYPED_FIELD(int, animation_type),
	LCF_STRUCT_TYPED_FIELD(int, animation_id),
LCF_STRUCT_FIELDS_END()

#undef LCF_CURRENT_STRUCT
#undef LCF_CHUNK_SUFFIX


text:
'use strict';

// check if gulp dist was called
if (process.argv.indexOf('dist') !== -1) {
  // add ship options to command call
  process.argv.push('--ship');
}

const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');
const gulpSequence = require('gulp-sequence');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);

// Create clean distrubution package
gulp.task('dist', gulpSequence('clean', 'bundle', 'package-solution'));
// Create clean development package
gulp.task('dev', gulpSequence('clean', 'bundle', 'package-solution'));

/********************************************************************************************
 * Adds an alias for handlebars in order to avoid errors while gulping the project
 * https://github.com/wycats/handlebars.js/issues/1174
 * Adds a loader and a node setting for webpacking the handlebars-helpers correctly
 * https://github.com/helpers/handlebars-helpers/issues/263
 ********************************************************************************************/
build.configureWebpack.mergeConfig({
  additionalConfiguration: (generatedConfiguration) => {

    generatedConfiguration.resolve.alias = { handlebars: 'handlebars/dist/handlebars.min.js' };

    generatedConfiguration.module.rules.push(
      { test: /\.js$/, loader: 'unlazy-loader' }
    );

    generatedConfiguration.node = {
      fs: 'empty'
    }

    return generatedConfiguration;
  }
});

/**
 * StyleLinter configuration
 * Reference and custom gulp task
 */
const stylelint = require('gulp-stylelint');

/* Stylelinter sub task */
let styleLintSubTask = build.subTask('stylelint', (gulp) => {

    console.log('[stylelint]: By default style lint errors will not break your build. If you want to change this behaviour, modify failAfterError parameter in gulpfile.js.');

    return gulp
        .src('src/**/*.scss')
        .pipe(stylelint({
            failAfterError: false,
            reporters: [{
                formatter: 'string',
                console: true
            }]
        }));
});
/* end sub task */

build.initialize(gulp);


text:
<?php
namespace LeagueWrap;

use Memcached;

class Cache implements CacheInterface {

	protected $memcached;

	public function __construct()
	{
		$this->memcached = new Memcached;
		$this->memcached->addServer('localhost', 11211, 100);
	}

	/**
	 * Adds the response string into the cache under the given key.
	 *
	 * @param string $response
	 * @param string $key
	 * @param int $seconds
	 * @return bool
	 */
	public function set($response, $key, $seconds)
	{
		return $this->memcached->set($key, $response, time() + $seconds);
	}

	/**
	 * Determines if the cache has the given key.
	 *
	 * @param string $key
	 * @return bool
	 */
	public function has($key)
	{
		$this->memcached->get($key);
		if ($this->memcached->getResultCode() == Memcached::RES_NOTFOUND)
		{
			return false;
		}
		return true;
	}

	/**
	 * Gets the contents that are stored at the given key.
	 *
	 * @param string $key
	 * @return strig
	 */
	public function get($key)
	{
		return $this->memcached->get($key);
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Victor N. Allen</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/stylish-portfolio.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                Toggle navigation

            </button>
            VNALLEN

Portfolio (current)

About

                    Documents

Risk Assessment

Mitigation Matrix

Executive Update

Mission Vision Values

Access Policy

                    PPI

People

Property

Information

Plans

Contact

Governance

The Joint Commission TJC

Joint Commission standards are the basis of an objective evaluation process that can help health care organizations measure, assess and improve performance. The standards focus on important patient, individual, or resident care and organization functions that are essential to providing safe, high quality care.

Leadership (LD)

Life Safety (LS)

Environment of Care (EC)

Emergency Management (EM)

The Cleary Act

In 1990, Congress enacted the Crime Awareness and Campus Security Act of 1990 (Title II of Public Law 101-542), which amended the Higher Education Act of 1965 (HEA). This act required all post-secondary institutions participating in HEA's Title IV student financial assistance programs to disclose campus crime statistics and security information. The act was amended in 1992, 1998, 2000 and 2008. The 1998 amendments renamed the law the Jeanne Cleary Disclosure of Campus Security Policy and Campus Crime Statistics Act in memory of a student who was slain in her dorm room in 1986. It is generally referred to as the Cleary Act and is in section 485(f) of the HEA.

www2.ed.gov/admins/lead/safety/handbook.pdf

ASIS Guidelines

ASIS Guidelines provides Physical Security Professionals with a comprehensive selection of documents;

This is in response to a concerted need for guidelines regarding security issues in the United States

By addressing specific concerns and issues inherent to security professionals, security guidelines will better serve the needs of security professionals by increasing the effectiveness and productivity of security practices and solutions, as well as enhance the professionalism of the industry

ASIS Standards

ASIS Standard and Guideline publications are developed through a voluntary consensus standards development process.  This process brings together volunteers and /or seeks out the views of persons who have an interest in the topic covered by the publication.

These Standards provide current processes that support appropriate awareness, prevention, preparation, and response to changes in threat conditions.

Standards are structured at a high level, although specific considerations and responses are also addressed for consideration by individual organization based on identifiable risk and requirements

NERC & FERC

On the federal level, 2016 has seen the release of updated Critical Infrastructure Protection (CIP) requirements by the North American Electric Reliability Corporation (NERC), the non-profit empowered by the Federal Energy Regulatory Commission (FERC) with authority to oversee grid security.  The CIP plan is a set of nine standards and some 45 requirements that cover a broad variety of cybersecurity protocols.  Under the CIP plan, utilities are required to identify critical cyber assets and ensure they are protected by electronic security measures, such as encryption and two-factor authentication.  They must develop plans for incident reporting and recovery, and train personnel on response plans.  The CIP standards even govern physical security measures, such as security guards and visitor logs.


text:
jQuery Accordion creates a lightweight accordion menu.

##How to Use
- Requires jQuery
- Include accordion.min.js
- Include accordion.css

=> Use this HTML markup:

```html
    <head>
    <!- Link CSS ->
	 <link href="css/accordion.css" rel="stylesheet">
    </head>

    <body>

    <!- Accordion Setup ->
	<div id="yourUniqueId" class="accordion" data-acc="open">
		<h3>Menu 1 <span></span></h3>
		<div class="accordion_content" > <p> Menu 1 content</p></div>
	</div>

	<div id="yourUniqueId" class="accordion" data-acc="closed">
		<h3>Menu 2 <span></span></h3>
		<div class="accordion_content" > <p>Menu 2 content</p></div>
	</div>

     <!- Link jQuery ->
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
 	 <!- Link Accordion.js ->
	 <script src="js/accordion.min.js" ></script>

	 </body>
```
=> HTML Settings

	id = Setting an unique id on your accordion menu allows you the ability to add #yourUniqueId
         to the end of your url and the accordion with that id will open.

    data-acc = If you want the menu to be open by default set this to "open" if you want it
               to be closed set it to "closed"

##Options

###Auto Close

This makes it so only one accordion menu can be active at a time. By Default you have to click to close an accordion. With "autoClose" set to true when you click on an accordion any previously active accordion will become inactive.

#####Example:

$('.accordion').accordion({autoClose:"true"})

##Demo
[Accordion Demo Site](http://www.jeffreyjpoland.com/jquery/accordion/)