text:
namespace PaintsNow {
	class IStreamBase;
	class IReflectObject;
	class IUniqueAllocator;

	struct IUniqueInfo {
		virtual ~IUniqueInfo() {}
		virtual size_t GetSize() const;
		virtual IReflectObject* Create() const;
		virtual IUniqueAllocator* GetAllocator() const;
		void Endianize(void* buffer) {
			if (IsStdEndian() && IsInteger()) {
				char* p = reinterpret_cast<char*>(buffer);
				for (size_t i = 0; i < size / 2; i++) {
					std::swap(p[i], p[size - i - 1]);
				}
			}
		}
		typedef void* (*Cast)(IReflectObject* from);
		bool IsInteger();
		String GetSubName() const;
		enum INT_STATE { IS_INTEGER, NOT_INTEGER, TBD };

		IUniqueAllocator* allocator;
		size_t size;
		String typeName;
		TWrapper<IReflectObject*> creator;
		std::map<IUniqueInfo*, Cast> interfaces;

		INT_STATE intState;
	};

	struct Unique {
		Unique(IUniqueInfo* f = nullptr);
		bool operator == (const Unique& unique) const;
		bool operator != (const Unique& unique) const;
		bool operator < (const Unique& unique) const;
		const IUniqueInfo* operator -> () const;
		IUniqueInfo* operator -> ();

		IUniqueInfo* info;
	};

	class IUniqueAllocator {
	public:
		virtual ~IUniqueAllocator();
		virtual IUniqueInfo* Alloc(const String& name, size_t size) = 0;
		virtual IUniqueInfo* Get(const String& name) = 0;
	};

	class UniqueAllocator : public IUniqueAllocator {
	public:
		UniqueAllocator(IThread& thread);
		virtual ~UniqueAllocator();
		virtual IUniqueInfo* Alloc(const String& name, size_t size);
		virtual IUniqueInfo* Get(const String& name);
		virtual IThread& GetThreadApi();

	private:
		IThread& thread;
		IThread::Lock* lock;
		std::map<String, IUniqueInfo> mapType;
	};

	IUniqueAllocator* GetGlobalUniqueAllocator();
	void SetGlobalUniqueAllocator(IUniqueAllocator* alloc);

	template <class T>
	struct UniqueTypeEx {
		static std::string Demangle(const char* name) {
		#ifdef __GNUG__
			int status = -4; // some arbitrary value to eliminate the compiler warning
			// enable c++11 by passing the flag -std=c++11 to g++
			std::unique_ptr<char, void(*)(void*)> res {
				abi::__cxa_demangle(name, nullptr, nullptr, &status),
					std::free
			};

			return (status==0) ? res.get() : name;
		#else
			return name;
		#endif
		}

		static void RemovePatterns(String& s, const String& p) {
			size_t size = p.size();
			for (size_t i = s.find(p); i != String::npos; i = s.find(p))
				s.erase(i, size);
		}

		static Unique Get(IUniqueAllocator* allocator = GetGlobalUniqueAllocator()) {
			assert(allocator != nullptr);
			String className = Demangle(typeid(T).name());
			// remove 'class ' or 'struct ' prefix
			const String skipPrefixes[] = { "class ", "struct " };
			for (size_t i = 0; i < sizeof(skipPrefixes) / sizeof(skipPrefixes[0]); i++) {
				RemovePatterns(className, skipPrefixes[i]);
			}
			static IUniqueInfo* value = allocator->Alloc(className, sizeof(typename ReturnType<T>::type));
			return value;
		}
	};

	template <class T>
	struct UniqueType : public String {
		UniqueType(const String& filter = "") : String(filter) {}
		static Unique Get(IUniqueAllocator* allocator = GetGlobalUniqueAllocator()) {
#if defined(_MSC_VER) && _MSC_VER <= 1200
			return UniqueTypeEx<std::remove_reference<T>::type>::Get(allocator);
#else
			return UniqueTypeEx<typename std::remove_reference<T>::type>::Get(allocator);
#endif
		}
	};

	class IReflect;
	class IIterator;
	class IReflectObject : public TObject<IReflect> {
	public:
		IReflectObject();
		// general object construction
		template <class T>
		IReflectObject(const T& t) {}

		virtual ~IReflectObject();
		virtual TObject<IReflect>& operator () (IReflect& reflect);
		virtual const TObject<IReflect>& operator () (IReflect& reflect) const;
		virtual bool IsBaseObject() const; // returns true, any sub-class should return false;
		virtual bool IsIterator() const; // only for IIterators
		virtual Unique GetUnique() const;

		template <class T>
		static T* QueryInterfaceEx(IReflectObject* object, Unique unique, UniqueType<T> target) {
			if (unique == target.Get()) return static_cast<T*>(object);

			std::map<IUniqueInfo*, IUniqueInfo::Cast>::const_iterator p = unique.info->interfaces.find(target.Get().info);
			if (p != unique.info->interfaces.end()) {
				return reinterpret_cast<T*>(p->second(object));
			} else {
				T* result = nullptr;
				for (std::map<IUniqueInfo*, IUniqueInfo::Cast>::const_iterator t = unique.info->interfaces.begin(); result == nullptr && t != unique.info->interfaces.end(); ++t) {
					result = QueryInterfaceEx(object, (*t).first, target);
				}

				return result;
			}
		}

		template <class T>
		T* QueryInterface(UniqueType<T> t) {
			return QueryInterfaceEx(this, GetUnique(), t);
		}

		template <class T>
		const T* QueryInterface(UniqueType<T> t) const {
			return QueryInterfaceEx(const_cast<IReflectObject*>(this), GetUnique(), t);
		}

		virtual IUniqueAllocator* GetUniqueAllocator() const;
		virtual void ReleaseObject();

		// These two functions are work-arounds for gcc compiler.
		static const IReflectObject& TransformReflectObject(IReflectObject& t) {
			return t;
		}

		static const IReflectObject& TransformReflectObject(const IReflectObject& t) {
			static const IReflectObject s;
			return t.IsBaseObject() ? s : t;
		}

		// Not recommended for frequently calls
		template <class T>
		T* Inspect(UniqueType<T> unique, const String& key = "") {
			static Unique u = UniqueType<T>::Get();
			return reinterpret_cast<T*>(InspectEx(u, key));
		}

		virtual bool operator >> (IStreamBase& stream) const;
		virtual bool operator << (IStreamBase& stream);

	protected:
		template <class T>
		static Unique GetUniqueByValue(const T& t, IUniqueAllocator* allocator = GetGlobalUniqueAllocator()) {
			return UniqueType<T>::Get(allocator);
		}

	private:
		virtual void* InspectEx(Unique unique, const String& key);
	};

	class IReflectObjectComplex : public IReflectObject {
	public:
		virtual bool IsBaseObject() const;
		virtual TObject<IReflect>& operator () (IReflect& reflect);
	};

	class IIterator : public IReflectObject {
	public:
		IIterator();
		virtual ~IIterator();
		virtual bool IsBaseObject() const;
		virtual bool IsIterator() const;
		virtual IIterator* New() const = 0;
		virtual void Attach(void* base) = 0;
		virtual void* GetHost() const = 0;
		virtual void Initialize(size_t count) = 0;
		virtual size_t GetTotalCount() const = 0;
		virtual void* Get() = 0;
		virtual const IReflectObject& GetPrototype() const = 0;
		virtual Unique GetPrototypeUnique() const = 0;
		virtual bool IsLayoutLinear() const = 0;
		virtual bool IsLayoutPinned() const = 0;
		virtual bool Next() = 0;
	};

	// for static arrays
	template <class T, class S>
	class ArrayIterator : public IIterator {
	public:
		typedef S value_type;
		ArrayIterator() : pointer(nullptr) {}
		ArrayIterator(T& p) : pointer(p), count(sizeof(p) / sizeof(p[0])), i(0) {}
		virtual void Initialize(size_t c) {
			// cannot create a larger count
			static T p;
			count = Min(c, sizeof(p) / sizeof(p[0]));
		}

		template <class D>
		Unique GetPrototypeUniqueEx(D* d) const {
			return UniqueType<D>::Get();
		}

		virtual Unique GetPrototypeUnique() const {
			static T p;
			return GetPrototypeUniqueEx(p);
		}

		virtual size_t GetTotalCount() const {
			return count;
		}

		virtual void* Get() {
			assert(i != 0);
			return &(*reinterpret_cast<T*>(pointer))[i - 1];
		}

		virtual const IReflectObject& GetPrototype() const {
			static T t;
			static const IReflectObject& object = IReflectObject::TransformReflectObject(t[0]);
			return object;
		}

		virtual bool Next() {
			if (i >= count) {
				return false;
			}

			i++;
			return true;
		}

		virtual IIterator* New() const {
			ArrayIterator* iter = new ArrayIterator();
			iter->pointer = pointer;
			iter->count = count;
			iter->i = 0;
			return iter;
		}

		virtual void Attach(void* p) {
			pointer = p;
			i = 0;
		}

		virtual bool IsLayoutLinear() const {
			return true;
		}

		virtual bool IsLayoutPinned() const {
			return false;
		}

		virtual void* GetHost() const {
			return pointer;
		}

	private:
		void* pointer;
		size_t count;
		size_t i;
	};

	template <class T, class D>
	ArrayIterator<T, D> IterateArrayEx(T& t, D& d) {
		return ArrayIterator<T, D>(t);
	}

#define IterateArray(t) \
	IterateArrayEx(t, t[0])

	// for vector arrays
	template <class T>
	class VectorIterator : public IIterator {
	public:
#if defined(_MSC_VER) && _MSC_VER <= 1200
		typedef T::value_type value_type;
#else
		typedef typename T::value_type value_type;
#endif
		VectorIterator() : base(nullptr), i(0) {}
		VectorIterator(T& p) : base(&p), i(0) {}
		virtual void Initialize(size_t c) {
			assert(base != nullptr);
			base->resize(c);
		}

		virtual size_t GetTotalCount() const {
			assert(base != nullptr);
			return base->size();
		}

		virtual Unique GetPrototypeUnique() const {
#if defined(_MSC_VER) && _MSC_VER <= 1200
			typedef const T::value_type t;
#else
			typedef const typename T::value_type t;
#endif
			return UniqueType<t>::Get();
		}

		virtual const IReflectObject& GetPrototype() const {
#if defined(_MSC_VER) && _MSC_VER <= 1200
			static const T::value_type t;
#else
			static const typename T::value_type t = typename T::value_type();
#endif
			static const IReflectObject& object = IReflectObject::TransformReflectObject(t);
			return object;
		}

		virtual void* Get() {
			assert(i != 0);
			return &(*base)[i - 1];
		}

		virtual bool Next() {
			if (i >= (*base).size()) {
				return false;
			}

			i++;
			return true;
		}

		virtual IIterator* New() const {
			VectorIterator* iter = new VectorIterator(*base);
			return iter;
		}

		virtual void Attach(void* p) {
			base = reinterpret_cast<T*>(p);
			i = 0;
		}

		virtual bool IsLayoutLinear() const {
			return true;
		}

		virtual bool IsLayoutPinned() const {
			return false;
		}

		virtual void* GetHost() const {
			return base;
		}

	private:
		T* base;
		size_t i;
	};

	template <class T>
	VectorIterator<T> IterateVector(T& t) {
		return VectorIterator<T>(t);
	}

	class MetaNodeBase : public IReflectObjectComplex {
	public:
		virtual TObject<IReflect>& operator () (IReflect& reflect) {
			// Do nothing ..
			return *this;
		}
	};

	class MetaChainBase : public IReflectObjectComplex {
	public:
		virtual const MetaChainBase* GetNext() const {
			return nullptr;
		}

		virtual const MetaNodeBase* GetNode() const {
			return nullptr;
		}

	private:
		virtual TObject<IReflect>& operator () (IReflect& reflect) {
			assert(false);
			return *this;
		}
	};

	template <class T, class D, class K, class Base>
	class MetaChain : public MetaChainBase {
	public:
		MetaChain(const K& k, const Base& b) : chainNode(k), base(b) {}

#if defined(_MSC_VER) && _MSC_VER <= 1200
		template <class N>
		inline MetaChain<T, D, N::VC6Type, MetaChain<T, D, K, Base> > operator [] (const N& t) const {
			return MetaChain<T, D, N::VC6Type, MetaChain<T, D, K, Base> >(t(GetObject(), GetMember()), *this);
		}
#else
		template <class N>
		inline MetaChain<T, D, typename N::template RealType<T, D>::Type, MetaChain<T, D, K, Base> > operator [] (const N& t) const {
			return MetaChain<T, D, typename N::template RealType<T, D>::Type, MetaChain<T, D, K, Base> >(t(GetObject(), GetMember()), *this);
		}
#endif

		inline bool IsChain() const {
			return true;
		}

		virtual const MetaChainBase* GetNext() const {
			return base.IsChain() ? &base : nullptr;
		}

		virtual const MetaNodeBase* GetNode() const {
			return &chainNode;
		}

		inline void operator * () const {
			Finish(this);
		}

		void Finish(const MetaChainBase* head) const {
			(const_cast<Base&>(base)).Finish(head);
		}

		inline T* GetObject() const {
			return base.GetObject();
		}

		inline D* GetMember() const {
			return base.GetMember();
		}

		K chainNode;
		const Base& base;
	};

	class IReflect {
	public:
		IReflect(bool a, bool m);
		virtual ~IReflect();

		bool IsReflectAttrib() const;
		bool IsReflectMethod() const;

		void RegisterBuiltinTypes(bool useStdintType = false);
		struct Param {
			Param(Unique t = UniqueType<void>::Get(), const String& n = "") : type(t), name(n) {}
			operator Unique () const {
				return type;
			}

			Unique type;
			String name;
		};

		// static size_t GetUniqueLength(Unique id);

		template <class T>
		inline void OnClass(T& t, const char* name, const char* path, const MetaChainBase* meta) {
			Unique u = UniqueType<T>::Get();
			Class(t, u, name, path, meta);
		}

		template <class T>
		inline void OnAttrib(const T& t, const char* name, void* base, const MetaChainBase* meta) {
			Unique u = UniqueType<T>::Get();
			ForwardProcessAttrib(const_cast<T&>(t), u, name, base, (void*)&t, meta);
		}

		inline void ForwardProcessAttrib(const IReflectObject& s, Unique typeID, const char* name, void* base, void* ptr, const MetaChainBase* meta) {
			ProcessAttrib(const_cast<IReflectObject&>(s), typeID, name, base, ptr, meta);
		}

#if (defined(_MSC_VER) && _MSC_VER < 1800) || defined(COMPATIBLE_PROXY)
		// T == TWrapper<...>
		template <class R, class A, class B, class C, class D, class E, class F, class G, class H, class I, class J, class K, class L, class M, class N, class O, class P>
		inline void OnMethod(const TWrapper<R, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P>& t, const char* name, const MetaChainBase* meta) {
			static Unique params[] = {
				UniqueType<A>::Get(),
				UniqueType<B>::Get(),
				UniqueType<C>::Get(),
				UniqueType<D>::Get(),
				UniqueType<E>::Get(),
				UniqueType<F>::Get(),
				UniqueType<G>::Get(),
				UniqueType<H>::Get(),
				UniqueType<I>::Get(),
				UniqueType<J>::Get(),
				UniqueType<K>::Get(),
				UniqueType<L>::Get(),
				UniqueType<M>::Get(),
				UniqueType<N>::Get(),
				UniqueType<O>::Get(),
				UniqueType<P>::Get()
			};

			static Param retValue = UniqueType<R>::Get();
			std::vector<Param> p;
			for (size_t i = 0; i < sizeof(params) / sizeof(params[0]) && (!(params[i] == UniqueType<Void>::Get())); i++) {
				p.push_back(Param(params[i]));
			}

			static Unique unique = UniqueType<TWrapper<R, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P> >::Get();
			ProcessMethod(unique, name, reinterpret_cast<const TProxy<>*>(&t.GetProxy()), retValue, p, meta);
		}
#else
		template <typename R, typename... Args>
		inline void OnMethod(const TWrapper<R, Args...>& t, const char* name, const MetaChainBase* meta) {
			std::vector<Param> params;
			ParseParams(params, t);
			static Unique u = UniqueType<R>::Get();
			static Param retValue(u);
			static Unique unique = UniqueType<TWrapper<R, Args...> >::Get();
			ProcessMethod(unique, name, reinterpret_cast<const TProxy<>*>(&t.GetProxy()), retValue, params, meta);
		}

		template <typename R, typename V, typename... Args>
		inline void ParseParams(std::vector<Param>& params, const TWrapper<R, V, Args...>&) {
			static Unique u = UniqueType<V>::Get();
			params.push_back(Param(u));
			ParseParams(params, TWrapper<R, Args...>());
		}

		template <typename R>
		inline void ParseParams(std::vector<Param>& params, const TWrapper<R>&) {}
#endif

		virtual void ProcessAttrib(IReflectObject& s, Unique typeID, const char* name, void* base, void* ptr, const MetaChainBase* meta) = 0;
		virtual void ProcessMethod(Unique typeID, const char* name, const TProxy<>* p, const Param& retValue, const std::vector<Param>& params, const MetaChainBase* meta) = 0;
		virtual void Class(IReflectObject& host, Unique id, const char* name, const char* path, const MetaChainBase* meta);

	private:
		bool isReflectAttrib;
		bool isReflectMethod;
	};

	class MetaNote : public MetaNodeBase {
	public:
		MetaNote(const String& v);
		MetaNote operator = (const String& value);

		template <class T, class D>
		inline const MetaNote& operator () (T* t, D* d) const {
			return *this; // do nothing
		}

		template <class T, class D>
		struct RealType {
			typedef MetaNote Type;
		};

		typedef MetaNote VC6Type;

		virtual TObject<IReflect>& operator () (IReflect& reflect);
		const String& value;
	};

	extern MetaNote Note;

	template <class T, class D>
	class WriterBase : public MetaChainBase {
	public:
		WriterBase(IReflect& r, T* p, D* v, const char* n) : reflect(r), object(p), member(v), name(n) {}
		virtual ~WriterBase() {}

		inline bool IsChain() const { return false; }

		virtual void Finish(const MetaChainBase* head) {}

#if defined(_MSC_VER) && _MSC_VER <= 1200
		template <class N>
		inline MetaChain<T, D, N::VC6Type, WriterBase<T, D> > operator [] (const N& t) const {
			return MetaChain<T, D, N::VC6Type, WriterBase<T, D> >(t(object, member), *this);
		}
#else
		template <class N>
		inline MetaChain<T, D, typename N::template RealType<T, D>::Type, WriterBase<T, D> > operator [] (const N& t) const {
			return MetaChain<T, D, typename N::template RealType<T, D>::Type, WriterBase<T, D> >(t(object, member), *this);
		}
#endif

		inline T* GetObject() const {
			return object;
		}

		inline D* GetMember() const {
			return member;
		}

		IReflect& reflect;
		T* object;
		D* member;
		const char* name;
	};

	template <class T, class D>
	class AttribWriter : public WriterBase<T, D> {
	public:
		AttribWriter(IReflect& r, T* p, D* v, const char* n) : WriterBase<T, D>(r, p, v, n) {}
		~AttribWriter() {}

		void operator * () {
			Finish(nullptr);
		}

		virtual void Finish(const MetaChainBase* head) {
			WriterBase<T, D>::reflect.OnAttrib(*WriterBase<T, D>::member, WriterBase<T, D>::name, WriterBase<T, D>::object, head == this ? nullptr : head);
		}
	};

	template <class T, class D>
	AttribWriter<T, D> CreateAttribWriter(IReflect& r, T* p, const D& v, const char* name) {
		return AttribWriter<T, D>(r, p, const_cast<D*>(&v), name);
	}

	template <class T, class D>
	class MethodWriter : public WriterBase<T, D> {
	public:
		MethodWriter(IReflect& r, T* p, D* v, const char* n) : WriterBase<T, D>(r, p, v, n) {}
		virtual ~MethodWriter() {}

		void operator * () {
			Finish(nullptr);
		}

		virtual void Finish(const MetaChainBase* head) {
			WriterBase<T, D>::reflect.OnMethod(Wrap(WriterBase<T, D>::object, *WriterBase<T, D>::member), WriterBase<T, D>::name, head == this ? nullptr : head);
		}
	};

	template <class T, class D>
	MethodWriter<T, D> CreateMethodWriter(IReflect& r, T* p, const D& v, const char* name) {
		return MethodWriter<T, D>(r, p, const_cast<D*>(&v), name);
	}

	template <class T>
	class ClassWriter : public WriterBase<T, const char>  {
	public:
		ClassWriter(IReflect& r, T* p, const char* n, const char* l) : WriterBase<T, const char>(r, p, l, n) {}
		virtual ~ClassWriter() {}

		void operator * () {
			Finish(nullptr);
		}

		virtual void Finish(const MetaChainBase* head) {
			WriterBase<T, const char>::reflect.OnClass(*WriterBase<T, const char>::object, WriterBase<T, const char>::name, WriterBase<T, const char>::member, head);
		}
	};

	template <class T>
	ClassWriter<T> CreateClassWriter(IReflect& r, T* v, const char* name, const char* line) {
		return ClassWriter<T>(r, v, name, line);
	}

	template <class T>
	struct Creatable {
		Creatable() {
			static Unique u = UniqueType<T>::Get();
			u->creator = &Creatable::Create;
		}
		static void Init() {
			static Creatable<T> theInstance;
		}
		static IReflectObject* Create() {
			return new T();
		}
	};

	class MetaConstructable : public MetaNodeBase {
	public:
		template <class T, class D>
		inline const MetaConstructable& operator () (T* t, D* d) const {
			static Creatable<T> theClass;
			return *this; // do nothing
		}

		template <class T, class D>
		struct RealType {
			typedef MetaConstructable Type;
		};

		typedef MetaConstructable VC6Type;
	};

	extern MetaConstructable Constructable;

	template <class T, class P>
	class RegisterInterface {
	public:
		static void* Convert(IReflectObject* v) {
			return static_cast<P*>(static_cast<T*>(v));
		}
		RegisterInterface() {
			static Unique u = UniqueType<T>::Get();
			static Unique p = UniqueType<P>::Get();
			u->interfaces[p.info] = &RegisterInterface<T, P>::Convert;
		}
	};

	template <class P>
	class MetaInterface : public MetaNodeBase {
	public:
		P& object;
		class DummyReflect : public IReflect {
		public:
			DummyReflect() : IReflect(false, false) {}
			virtual void ProcessAttrib(IReflectObject& s, Unique typeID, const char* name, void* base, void* ptr, const MetaChainBase* meta) {};
			virtual void ProcessMethod(Unique typeID, const char* name, const TProxy<>* p, const Param& retValue, const std::vector<Param>& params, const MetaChainBase* meta) {};
		};

		MetaInterface(P& obj) : object(obj) {
			static DummyReflect dummyReflect;
			object.P::operator () (dummyReflect);
		}

		template <class T, class D>
		inline const MetaInterface<P>& operator () (T* t, D* d) const {
			// class T is Interfaced form class P
			static RegisterInterface<T, P> reg;

			return *this; // do nothing
		}

		template <class T, class D>
		struct RealType {
			typedef MetaInterface<P> Type;
		};

		typedef MetaInterface<P> VC6Type;

		virtual TObject<IReflect>& operator () (IReflect& reflect) {
			return object.P::operator () (reflect);
		}
	};

	template <class T>
	class BuiltinTypeWrapper : public IReflectObject {};

#define ReflectBuiltinSubtype(v) \
	{ static BuiltinTypeWrapper<v> proto; reflect.Class(proto, UniqueType<v>::Get(), #v, "C++", nullptr); }

#define ReflectBuiltinType(v) \
	ReflectBuiltinSubtype(v); \
	ReflectBuiltinSubtype(const v); \
	ReflectBuiltinSubtype(v&); \
	ReflectBuiltinSubtype(const v&); \
	ReflectBuiltinSubtype(v*); \
	ReflectBuiltinSubtype(const v*); \
	ReflectBuiltinSubtype(v*&); \
	ReflectBuiltinSubtype(const v*&); \

#define Interface(c) \
	MetaInterface<c>(*this)

#define ReflectClass(v) \
	typedef v CurrentClass; \
	*CreateClassWriter(reflect, this, #v, __FILE__)

#define ReflectAttrib(v) \
	*CreateAttribWriter(reflect, this, v, #v)

#if defined(_MSC_VER) && _MSC_VER <= 1200
#define ReflectMethod(v) \
	*CreateMethodWriter(reflect, this, &CurrentClass::v, #v)
#else
#define ReflectMethod(v) \
	*CreateMethodWriter(reflect, this, &std::remove_reference<decltype(*this)>::type::v, #v)
#endif

	class ISyncObject : public IDevice {
	public:
		ISyncObject(IThread& threadApi);
		virtual ~ISyncObject();
		virtual void DoLock();
		virtual void UnLock();
		virtual bool TryLock();
		size_t GetLockCount() const;
		IThread& GetThreadApi();

	protected:
		IThread& threadApi;
		IThread::Lock* lock;
	};

	class Inspector : public IReflect {
	public:
		Inspector(const IReflectObject& r);

		template <class T>
		T* operator [](UniqueType<T> ut) {
			static Unique u = UniqueType<T>::Get();
			return reinterpret_cast<T*>(Find(u, ut));
		}

		virtual void* Find(Unique unique, const String& key) const;
		virtual void ProcessAttrib(IReflectObject& s, Unique typeID, const char* name, void* base, void* ptr, const MetaChainBase* meta);
		virtual void ProcessMethod(Unique typeID, const char* name, const TProxy<>* p, const Param& retValue, const std::vector<Param>& params, const MetaChainBase* meta);

	private:
		std::map<Unique, std::map<String, void*> > entries;
	};

	class MetaRuntime : public MetaNodeBase {
	public:
		template <class T, class D>
		inline const MetaRuntime& operator () (T* t, D* d) const {
			return *this; // do nothing
		}

		template <class T, class D>
		struct RealType {
			typedef MetaRuntime Type;
		};

		typedef MetaRuntime VC6Type;
		virtual TObject<IReflect>& operator () (IReflect& reflect);
	};

	extern MetaRuntime Runtime;
}

#endif // __IREFLECT_H__


text:
#import "NSWindowController.h"

#import "NSWindowDelegate.h"

@class ABPeoplePickerView;

@interface AddressPicker : NSWindowController <NSWindowDelegate>
{
    ABPeoplePickerView *_pickerView;
    BOOL _selectionIsValid;
}

+ (void)restoreFromDefaults;
+ (void)showOrHideAddressPicker;
@property(nonatomic) BOOL selectionIsValid; // @synthesize selectionIsValid=_selectionIsValid;
- (void)_ensureSelectionIsValid:(id)arg1;
- (id)_formattedAddressForRecord:(id)arg1;
- (void)_putSelectionInHeader:(id)arg1;
- (void)putSelectionInBestHeader:(id)arg1;
- (void)putSelectionInBCC:(id)arg1;
- (void)putSelectionInCC:(id)arg1;
- (void)putSelectionInTo:(id)arg1;
- (id)windowNibName;
- (void)awakeFromNib;
- (void)dealloc;
- (void)windowWillClose:(id)arg1;
- (void)_showOrHideWindow;

@end

redpajama_set_name: RedPajamaGithub


text:
if(!dojo._hasResource["dojox.highlight.languages._dynamic"]){
dojo._hasResource["dojox.highlight.languages._dynamic"]=true;
dojo.provide("dojox.highlight.languages._dynamic");
dojo.require("dojox.highlight.languages.python");
}


text:
'use strict';

let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');

let index = require('./routes/index');
let books = require('./routes/books');
let users = require('./routes/users');
let loans = require('./routes/loans');

let app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/books', books);
app.use('/users', users);
app.use('/loans', loans);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  let err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;


text:
layout: post
status: publish
published: true
title: Avatarize Yourself
author:
  display_name: admin
  login: admin
  email: fabiopereira.me@gmail.com
  url: http://
author_login: admin
author_email: fabiopereira.me@gmail.com
author_url: http://
wordpress_id: 168
wordpress_url: http://fabiopereira.me/blogpt/2010/03/13/avatarize-yourself/
date: '2010-03-13 17:06:58 +1100'
date_gmt: '2010-03-14 00:06:58 +1100'
categories:
- Uncategorized
tags: []
comments: []
---

Gostei da ideia desse site (Avatirize Yourself).

Faça o upload de uma foto sua e se transforme em um Avatar.

<object type="application/x-shockwave-flash" data="http://content.oddcast.com/host/avatar/swf/workshop_518.swf?doorId=518&clientId=215&stem=http://host-d.oddcast.com/php/api/getWorkshopInfo/doorId=518&ds=http://host.oddcast.com/&mId=35412052.4&lId=english&pid=4b9c25dce6878d4f" 	id="w4b01c6c7456da3574b9c25dce6878d4f" height="400" width="420"><param value="http://content.oddcast.com/host/avatar/swf/workshop_518.swf?doorId=518&clientId=215&stem=http://host-d.oddcast.com/php/api/getWorkshopInfo/doorId=518&ds=http://host.oddcast.com/&mId=35412052.4&lId=english&pid=4b9c25dce6878d4f" name="movie" /><param value="opaque" name="wmode"><param value="mId=35412052.4&lId=english&pid=4b9c25dce6878d4f" name="flashvars"><param value="all" name="allowNetworking"><param value="always" name="allowScriptAccess"><param value="true" name="allowFullScreen"></object>

Fiz com outras pessoas também :)

Paulo Neto: http://www.avatarizeyourself.com/?mId=35409255.3
Camila: http://www.avatarizeyourself.com/?mId=35410568.3

Faça o seu e manda pra mim…


text:
package svc.data.textMessages;

import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpSession;

@RunWith(MockitoJUnitRunner.class)
public class SMSSpamProtectorTest {
	MockHttpSession session;

	@Before
    public void setup() {
	 	session = new MockHttpSession();
    }

	@Test
	public void returnsFalseForLockedOut(){
		Boolean lockedOut = SMSSpamProtector.isLockedOut(session);
		assertEquals(lockedOut,false);
	}

	@Test
	public void addsErrorsAndLocksOut(){
		SMSSpamProtector.addError(session);
		SMSSpamProtector.addError(session);
		SMSSpamProtector.addError(session);
		SMSSpamProtector.addError(session);
		SMSSpamProtector.addError(session);
		Boolean lockedOut = SMSSpamProtector.isLockedOut(session);
		assertEquals(lockedOut,true);
	}

	@Test
	public void clearsErrorsCorrectly(){
		SMSSpamProtector.addError(session);
		SMSSpamProtector.addError(session);
		SMSSpamProtector.addError(session);
		SMSSpamProtector.addError(session);
		SMSSpamProtector.clearErrors(session);
		SMSSpamProtector.addError(session);
		Boolean lockedOut = SMSSpamProtector.isLockedOut(session);
		assertEquals(lockedOut,false);
	}

}


text:
class AddAttachmentLogoToTeams < ActiveRecord::Migration
  def self.up
    change_table :teams do |t|
      t.attachment :logo
    end
  end

  def self.down
    remove_attachment :teams, :logo
  end
end


text:
/**
 * Created by JongHyeok Choi on 2017. 6. 5..
 */

let _ = require('underscore');

module.exports = {
    /**
     * overwrite Config from behind Parameter.
     * @Param Object
     */
    mixinConfig(config, ...overwriteConfigs) {

        let mixinObj = _.clone(config);

        for(let i=0, len=overwriteConfigs.length; i<len; i++) {
            let overwriteConfig = overwriteConfigs[i];
            for(let prop in overwriteConfig) {
                if(overwriteConfig.hasOwnProperty(prop)) {
                    mixinObj[prop] = overwriteConfig[prop];
                }
            }
        }

        return mixinObj;
    },
    /**
     * Check that the property values of the object correspond to the value passed to the second value factor.
     */
    contains(objArr, value, func) {
        return objArr.some(obj => func.call(null, obj) === value);
    },
    /**
     * Check that the property values of the object corresponsd to the value passed to the second value array factor
     */
    containsByValArr(objArr, valueArr, func) {
        return valueArr.some(value => this.contains(objArr, value, func));
    },
}


text:
UCLASS(MinimalAPI)
class UControlPointMeshComponent : public UStaticMeshComponent
{
	GENERATED_UCLASS_BODY()

#if WITH_EDITORONLY_DATA
	UPROPERTY(transient)
	uint32 bSelected:1;
#endif

	//Begin UPrimitiveComponent Interface
#if WITH_EDITOR
	virtual bool ShouldRenderSelected() const override
	{
		return Super::ShouldRenderSelected() || bSelected;
	}
#endif
	//End UPrimitiveComponent Interface
};


text:
require File.join(File.dirname(__FILE__), 'test_helper')

class SqlSubqueryTest < Test::Unit::TestCase
  def test_analyze_select_type
    query = get_query(:select_type => "DEPENDENT UNION")
    query.send :analyze_select_type!
    query.should_warn("DEPENDENT UNION", 2)

    query = get_query(:select_type => "UNCACHEABLE SUBQUERY")
    query.send :analyze_select_type!
    query.should_warn("UNCACHEABLE SUBQUERY", 10)
  end

  def get_query(options)
    SqlSubQuery.new(options)
  end
end


text:
<?php

namespace Pimcore\Model\Object\ClassDefinition\Data;

use Pimcore\Model;
use Pimcore\Model\Object;

class Geobounds extends Model\Object\ClassDefinition\Data\Geo\AbstractGeo {

    /**
     * Static type of this element
     *
     * @var string
     */
    public $fieldtype = "geobounds";

    /**
     * Type for the column to query
     *
     * @var array
     */
    public $queryColumnType = array(
        "NElongitude" => "double",
        "NElatitude" => "double",
        "SWlongitude" => "double",
        "SWlatitude" => "double"
    );

    /**
     * Type for the column
     *
     * @var array
     */
    public $columnType = array(
        "NElongitude" => "double",
        "NElatitude" => "double",
        "SWlongitude" => "double",
        "SWlatitude" => "double"
    );

    /**
     * Type for the generated phpdoc
     *
     * @var string
     */
    public $phpdocType = "\\Pimcore\\Model\\Object\\Data\\Geobounds";

    /**
     * @see Object\ClassDefinition\Data::getDataForResource
     * @param Object\Data\Geobounds $data
     * @param null|Model\Object\AbstractObject $object
     * @return string
     */
    public function getDataForResource($data, $object = null) {
        if ($data instanceof Object\Data\Geobounds) {
            return array(
                $this->getName() . "__NElongitude" => $data->getNorthEast()->getLongitude(),
                $this->getName() . "__NElatitude" => $data->getNorthEast()->getLatitude(),
                $this->getName() . "__SWlongitude" => $data->getSouthWest()->getLongitude(),
                $this->getName() . "__SWlatitude" => $data->getSouthWest()->getLatitude()
            );
        }
        return array(
            $this->getName() . "__NElongitude" => null,
            $this->getName() . "__NElatitude" => null,
            $this->getName() . "__SWlongitude" => null,
            $this->getName() . "__SWlatitude" => null
        );
    }

    /**
     * @see Object\ClassDefinition\Data::getDataFromResource
     * @param array $data
     * @return string
     */
    public function getDataFromResource($data) {
        if($data[$this->getName() . "__NElongitude"] && $data[$this->getName() . "__NElatitude"] && $data[$this->getName() . "__SWlongitude"] && $data[$this->getName() . "__SWlatitude"]) {
            $ne = new Object\Data\Geopoint($data[$this->getName() . "__NElongitude"], $data[$this->getName() . "__NElatitude"]);
            $sw = new Object\Data\Geopoint($data[$this->getName() . "__SWlongitude"], $data[$this->getName() . "__SWlatitude"]);

            return new Object\Data\Geobounds($ne,$sw);
        }
        return;
    }

    /**
     * @see Object\ClassDefinition\Data::getDataForQueryResource
     * @param Object\Data\Geobounds $data
     * @param null|Model\Object\AbstractObject $object
     * @return string
     */
    public function getDataForQueryResource($data, $object = null) {
        return $this->getDataForResource($data, $object);
    }

    /**
     * @see Object\ClassDefinition\Data::getDataForEditmode
     * @param Object\Data\Geobounds $data
     * @param null|Model\Object\AbstractObject $object
     * @return array
     */
    public function getDataForEditmode($data, $object = null) {
        if($data instanceof Object\Data\Geobounds) {
            return array(
                "NElongitude" => $data->getNorthEast()->getLongitude(),
                "NElatitude" => $data->getNorthEast()->getLatitude(),
                "SWlongitude" => $data->getSouthWest()->getLongitude(),
                "SWlatitude" => $data->getSouthWest()->getLatitude()
            );
        }
        return;
    }

    /**
     * @see Model\Object\ClassDefinition\Data::getDataFromEditmode
     * @param array $data
     * @param null|Model\Object\AbstractObject $object
     * @return Object\Data\Geobounds
     */
    public function getDataFromEditmode($data, $object = null) {
        if($data["NElongitude"] !== null && $data["NElatitude"] !== null && $data["SWlongitude"] !== null && $data["SWlatitude"] !== null) {
            $ne = new Object\Data\Geopoint($data["NElongitude"], $data["NElatitude"]);
            $sw = new Object\Data\Geopoint($data["SWlongitude"], $data["SWlatitude"]);

            return new Object\Data\Geobounds($ne,$sw);
        }
        return;
    }

    /**
     * @see Object\ClassDefinition\Data::getVersionPreview
     * @param Object\Data\Geobounds $data
     * @return string
     */
    public function getVersionPreview($data) {
        if($data instanceof Object\Data\Geobounds) {
            return $data->getNorthEast()->getLongitude() . "," . $data->getNorthEast()->getLatitude() . " " . $data->getSouthWest()->getLongitude() . "," . $data->getSouthWest()->getLatitude();
        }
        return "";
    }

    /**
     * converts object data to a simple string value or CSV Export
     * @abstract
     * @param Model\Object\AbstractObject $object
     * @return string
     */
    public function getForCsvExport($object) {
        $data = $this->getDataFromObjectParam($object);
        if($data instanceof Object\Data\Geobounds){
            return  $data->getNorthEast()->getLongitude().",".$data->getNorthEast()->getLatitude()."|".$data->getSouthWest()->getLongitude().",".$data->getSouthWest()->getLatitude();
        } else return null;
    }

    /**
     * @param string $importValue
     * @return null|Object\ClassDefinition\Data|Object\Data\Geobounds
     */
    public function getFromCsvImport($importValue) {
        $points = explode("|", $importValue);
        $value = null;
        if(is_array($points) and count($points)==2){
            $northEast = explode(",",$points[0]);
            $southWest = explode(",",$points[1]);
            if ($northEast[0] && $northEast[1] && $southWest[0] && $southWest[1]) {
                $value = new Object\Data\Geobounds(new Object\Data\Geopoint($northEast[0],$northEast[1]),new Object\Data\Geopoint($southWest[0],$southWest[1]));
            }
        }

        return $value;
    }

    /**
     * converts data to be exposed via webservices
     * @param string $object
     * @return mixed
     */
    public function getForWebserviceExport ($object) {
        $data = $this->getDataFromObjectParam($object);
        if ($data instanceof Object\Data\Geobounds) {
            return array(
                "NElongitude" => $data->getNorthEast()->getLongitude(),
                "NElatitude" => $data->getNorthEast()->getLatitude(),
                "SWlongitude" => $data->getSouthWest()->getLongitude(),
                "SWlatitude" => $data->getSouthWest()->getLatitude()
            );
        } else return null;
    }

    /**
     * @param mixed $value
     * @param null $object
     * @param null $idMapper
     * @return mixed|void
     * @throws \Exception
     */
    public function getFromWebserviceImport($value, $object = null, $idMapper = null) {
        if(empty($value)){
            return null;
        } else {
            $value = (array) $value;
            if($value["NElongitude"] !== null && $value["NElatitude"] !== null && $value["SWlongitude"] !== null && $value["SWlatitude"] !== null) {
                $ne = new Object\Data\Geopoint($value["NElongitude"], $value["NElatitude"]);
                $sw = new Object\Data\Geopoint($value["SWlongitude"], $value["SWlatitude"]);
                return new Object\Data\Geobounds($ne,$sw);
            } else {
                throw new \Exception("cannot get values from web service import - invalid data");
            }
        }
    }

    /** True if change is allowed in edit mode.
     * @return bool
     */
    public function isDiffChangeAllowed() {
        return true;
    }
}


text:
namespace SS.Integration.Adapter.Model.Enums
{
    public enum FixtureEventType
    {
        Snapshot,
        SnashotDelta,
        StreamUpdate,
        Suspend
    }
}


text:
package org.mini2Dx.ui.xml;

import org.mini2Dx.core.Mdx;
import org.mini2Dx.core.exception.MdxException;
import org.mini2Dx.core.files.FileHandleResolver;
import org.mini2Dx.core.reflect.Field;
import org.mini2Dx.gdx.utils.ObjectMap;
import org.mini2Dx.gdx.xml.XmlReader;
import org.mini2Dx.ui.element.ParentUiElement;
import org.mini2Dx.ui.element.Tab;
import org.mini2Dx.ui.element.TabView;
import org.mini2Dx.ui.element.UiElement;
import org.mini2Dx.ui.xml.spi.*;

import java.io.Reader;

public class UiXmlLoader {
    private final FileHandleResolver fileHandleResolver;
    private ObjectMap<String, UiElementHandler> tagNameToHandler = new ObjectMap<>();

    public UiXmlLoader(FileHandleResolver fileHandleResolver) {
        this.fileHandleResolver = fileHandleResolver;

        CorePopulator corePopulator = new CorePopulator();
        ParentUiElementPopulator parentUiElementPopulator = new ParentUiElementPopulator();

        addTagHandler("animated-image", new AnimatedImageFactory(), corePopulator, new AnimatedImagePopulator());
        addTagHandler("button", new ButtonFactory(), corePopulator, parentUiElementPopulator, new ButtonPopulator());
        addTagHandler("check-box", new CheckBoxFactory(), corePopulator, new CheckboxPopulator());
        addTagHandler("container", new ContainerFactory(), corePopulator, parentUiElementPopulator);
        addTagHandler("div", new DivFactory(), corePopulator, parentUiElementPopulator);
        addTagHandler("flex-row", new FlexRowFactory(), corePopulator, new FlexRowPopulator(), parentUiElementPopulator);
        addTagHandler("image", new ImageFactory(), corePopulator, new ImagePopulator());
        addTagHandler("image-button", new ImageButtonFactory(), corePopulator, new ImageButtonPopulator());
        addTagHandler("label", new LabelFactory(), corePopulator, new LabelPopulator());
        addTagHandler("progress-bar", new ProgressBarFactory(), corePopulator, new ProgressBarPopulator());
        addTagHandler("radio-button", new RadioButtonFactory(), corePopulator, new RadioButtonPopulator());
        addTagHandler("scroll-box", new ScrollBoxFactory(), corePopulator, parentUiElementPopulator, new ScrollBoxPopulator());
        addTagHandler("select", new SelectFactory(), corePopulator, new SelectPopulator());
        addTagHandler("slider", new SliderFactory(), corePopulator, new SliderPopulator());
        addTagHandler("tab", new TabFactory(), new TabPopulator());
        addTagHandler("tab-view", new TabViewFactory(), corePopulator, new TabViewPopulator());
        addTagHandler("text-button", new TextButtonFactory(), corePopulator, new TextButtonPopulator());
        addTagHandler("text-box", new TextBoxFactory(), corePopulator, new TextBoxPopulator());
    }

    /**
     * Add a new tag handler for a XML tag
     *
     * @param tagName    - the XML tag name
     * @param factory    - the factory the creates a new instance of the UI element
     * @param populators - a collection of populators to populate the properties on the UI element
     */
    public void addTagHandler(String tagName, UiElementFactory factory, UiElementPopulator... populators) {
        tagNameToHandler.put(tagName, new UiElementHandler(factory, populators));
    }

    public <T extends UiElement> T load(String filename) {
        try {
            Reader reader = fileHandleResolver.resolve(filename).reader();
            XmlReader xmlReader = new XmlReader();
            XmlReader.Element root = xmlReader.parse(reader);

            return (T) processXmlTag(root);
        } catch (Exception e) {
            throw new MdxException("Failed to load UI file: " + filename, e);
        }
    }

    public <T> T load(String filename, Class<T> model) {
        UiElement container = load(filename);
        if (container != null && model != null) {
            return populateModel(container, model);
        } else {
            throw new MdxException("Failed to populate Ui file " + filename, new Exception("container or model is null"));
        }
    }

    public <T> T load(String filename, T model) {
        UiElement container = load(filename);
        if (container != null && model != null) {
            return populateModel(container, model);
        } else {
            throw new MdxException("Failed to populate Ui file " + filename, new Exception("container or model is null"));
        }
    }

    protected <T extends UiElement, M> M populateModel(T container, Class<M> model) {
        M newInstance = (M) Mdx.reflect.newInstance(model);
        for (Field field : Mdx.reflect.getDeclaredFields(model)) {
            if (field.isAnnotationPresent(org.mini2Dx.ui.annotation.UiElement.class)) {
                String fieldName = field.getName();
                String annotationId = field
                        .getDeclaredAnnotation(org.mini2Dx.ui.annotation.UiElement.class)
                        .getAnnotation(org.mini2Dx.ui.annotation.UiElement.class)
                        .id();
                String id = annotationId.length() > 0 ? annotationId : fieldName;
                UiElement element = container.getElementById(id);
                field.set(newInstance, field.getType().cast(element));
            }
        }
        return newInstance;
    }

    protected <T extends UiElement, M> M populateModel(T container, M model) {
        M newInstance = model;
        for (Field field : Mdx.reflect.getDeclaredFields(model.getClass())) {
            if (field.isAnnotationPresent(org.mini2Dx.ui.annotation.UiElement.class)) {
                String fieldName = field.getName();
                String annotationId = field
                        .getDeclaredAnnotation(org.mini2Dx.ui.annotation.UiElement.class)
                        .getAnnotation(org.mini2Dx.ui.annotation.UiElement.class)
                        .id();
                String id = annotationId.length() > 0 ? annotationId : fieldName;
                UiElement element = container.getElementById(id);
                field.set(newInstance, field.getType().cast(element));
            }
        }
        return newInstance;
    }

    private UiElement processXmlTag(XmlReader.Element root) {
        String tagName = XmlTagUtil.getTagNameWithoutPrefix(root);
        UiElementHandler handler = tagNameToHandler.get(tagName);
        if (handler == null) {
            throw new UnknownUiTagException(tagName);
        }

        boolean childTagsAlreadyProcessed = false;
        UiElement uiElement = handler.factory.build(root);
        for (UiElementPopulator populator : handler.populators) {
            if (populator.populate(root, uiElement)) {
                childTagsAlreadyProcessed = true;
            }
        }

        if (!childTagsAlreadyProcessed && uiElement instanceof ParentUiElement) {
            ParentUiElement parentUiElement = (ParentUiElement) uiElement;
            for (int i = 0; i < root.getChildCount(); i++) {
                UiElement childElement = processXmlTag(root.getChild(i));
                if (parentUiElement instanceof TabView) {
                    TabView tabView = (TabView) parentUiElement;
                    tabView.add((Tab) childElement);
                } else {
                    parentUiElement.add(childElement);
                }
            }
        }

        return uiElement;
    }

    private static class UiElementHandler {
        final UiElementFactory factory;
        final UiElementPopulator[] populators;

        public UiElementHandler(UiElementFactory factory, UiElementPopulator... populators) {
            this.factory = factory;
            this.populators = populators;
        }
    }
}


text:
namespace gfx {

    ///The Dictionary class encapsulates a collection of key-value associations.
    ///
    /// \tparam Key     The Base-derived type used for keys. Defaults to `const String`.
    /// \tparam value   The Base-derived type used for values. Defaults to `Base`.
    ///
    ///All instances of `Dictionary` have mutable storage, to represent an
    ///immutable dictionary, qualify the instance with the const modifier.
    template<typename Key = const String, typename Value = Base>
    class Dictionary : public Base
    {
        static_assert(std::is_base_of<Base, Key>::value, "Dictionary requires Base-derived key types");
        static_assert(std::is_base_of<Base, Value>::value, "Dictionary requires Base-derived value types");
        static_assert(!std::is_pointer<Key>::value, "Key must be a bare type");
        static_assert(!std::is_pointer<Value>::value, "Value must be a bare type");

    public:

        ///A structure that contains a weak reference to a key object,
        ///and value object. Used for simple inline construction.
        struct Pair
        {
            ///The key of the pair.
            Key *key;

            ///The value of the pair.
            Value *value;
        };

    protected:

        ///The storage of the Dictionary.
        CFMutableDictionaryRef mStorage;

    public:

        ///Constructs an empty dictionary.
        Dictionary() :
            mStorage(CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &Base::kDictionaryKeyCallbacks, &Base::kDictionaryValueCallbacks))
        {
        }

        ///Constructs a dictionary by copying a CFDictionary's contents.
        Dictionary(CFDictionaryRef dictionary) :
            mStorage(CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, dictionary))
        {
        }

        ///Constructs a dictionary by copying another dictionary.
        Dictionary(const Dictionary<Key, Value> *dictionary) :
            Dictionary(dictionary->getStorage())
        {
        }

        ///Constructs a dictionary with an initializer list of pairs.
        Dictionary(const std::initializer_list<Pair> &list) :
            Dictionary()
        {
            for (const Pair &pair : list)
                this->set(pair.key, pair.value);
        }

        ///The destructor of the dictionary.
        virtual ~Dictionary()
        {
            CFRelease(mStorage);
        }

#pragma mark - Identity

        HashCode hash() const override
        {
            return CFHash(mStorage);
        }

        const String *description() const override
        {
            String::Builder description;
            description << "{\n";

            iterate([&description](Key *key, Value *value) {
                AutoreleasePool pool;

                description << "\t";
                description << key;
                description << " = ";
                description << value;
                description << ",\n";
            });

            description.string()->deleteRange(Range(description.length() - 1, 1));
            description << "\n}";

            return description.string();
        }

        bool isEqual(const Dictionary<Key, Value> *other) const
        {
            if(!other)
                return false;

            return CFEqual(mStorage, other->mStorage);
        }

        bool isEqual(const Base *other) const override
        {
            if(!other)
                return false;

            if(this->isKindOfClass<Dictionary<Key, Value>>()) {
                return this->isEqual((const Dictionary<Key, Value> *)other);
            }

            return false;
        }

        ///Returns the underlying storage of the dictionary.
        ///
        ///This should be considered an implementation detail,
        ///but is exposed for platform compatibility.
        CFDictionaryRef getStorage() const
        {
            return (CFDictionaryRef)mStorage;
        }
        CFMutableDictionaryRef getStorage()
        {
            return mStorage;
        }

#pragma mark - Accessing Values

        ///Returns the number of key-value associations stored in the dictionary.
        Index count() const
        {
            return CFDictionaryGetCount(mStorage);
        }

        ///Returns the number of instances of a given key are stored in the receiver.
        Index countOfKey(Key *key) const
        {
            gfx_assert_param(key);

            return CFDictionaryGetCountOfKey(mStorage, (const void *)key);
        }

        ///Returns the number of instances of a given value are stored in the receiver.
        Index countOfValue(Value *value) const
        {
            gfx_assert_param(value);

            return CFDictionaryGetCountOfKey(mStorage, (const void *)value);
        }

#pragma mark -

        ///Returns a bool indicating whether or not the receiver contains a given key.
        bool containsKey(Key *key) const
        {
            gfx_assert_param(key);

            return CFDictionaryContainsKey(mStorage, (const void *)key);
        }

        ///Returns a bool indicating whether or not the receiver contains a given value.
        bool containsValue(Value *value) const
        {
            gfx_assert_param(value);

            return CFDictionaryContainsValue(mStorage, (const void *)value);
        }

#pragma mark -

        ///Returns the value associated with a given key, if any.
        Value *get(Key *key) const
        {
            gfx_assert_param(key);

            return retained_autoreleased((Value *)CFDictionaryGetValue(mStorage, key));
        }

    private:

        static void applierAdaptor(Key *key, Value *value, std::function<void(Key *key, Value *value)> *function)
        {
            (*function)(key, value);
        }

    public:

        ///Enumerate over each key-value pair contained within the dictionary, applying a given function to each.
        void iterate(std::function<void(Key *key, Value *value)> function) const
        {
            CFDictionaryApplyFunction(mStorage, (CFDictionaryApplierFunction)&applierAdaptor, &function);
        }

#pragma mark - Changing Values

        ///Set the value associated with a given key.
        void set(Key *key, Value *value)
        {
            gfx_assert_param(key);

            CFDictionarySetValue(mStorage, key, value);
        }

        ///Take all of the values contained in a
        ///given dictionary and add them to the receiver.
        void takeValuesFrom(const Dictionary<Key, Value> *other)
        {
            other->iterate([this](Key *key, Value *value) {
                this->set(key, value);
            });
        }

        ///Remove the value associated with a given key.
        void remove(Key *key)
        {
            gfx_assert_param(key);

            CFDictionaryRemoveValue(mStorage, key);
        }

        ///Removes all of the contents of the receiver.
        void removeAll()
        {
            CFDictionaryRemoveAllValues(mStorage);
        }

#pragma mark - Utilities

        ///Creates and returns a new object that can be used in place of a given object
        ///within a dictionary when it is not appropriate the retain the given object.
        ///
        /// \param  object  The object it is not appropriate to retain. May not be null.
        ///
        /// \result A new object guaranteed to always have the same hash code given the same object.
        ///
        ///The object returned by this function is an implementation detail and subject to change.
        static Base *weakKeyForObject(const Base *object)
        {
            gfx_assert_param(object);

            return (String::Builder() << (void *)object);

        }
    };
}

#endif


text:
package pl.szczepanik.silencio.stubs;

import java.util.Arrays;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.ArrayUtils;

/**
 * Stub of @link {@link ObjectMapper} that has only stub methods.
 *
 * @author Damian Szczepanik (damianszczepanik@github)
 */
public class StubObjectMapper extends ObjectMapper {

    private Iterator<String> jsons;

    private JsonMappingException exception;

    public StubObjectMapper(JsonMappingException exception) {
        this.exception = exception;
    }

    public StubObjectMapper(String... jsons) {
        if (ArrayUtils.isEmpty(jsons)) {
            this.jsons = Arrays.asList(jsons).iterator();
        }
    }

    public <T> T readValue(String content, Class<T> valueType)throws JsonProcessingException, JsonMappingException {
        if (exception != null) {
            throw exception;
        } else if (jsons == null) {
            return null;
        } else {
            return super.readValue(jsons.next(), valueType);
        }
    }
}


text:
"""
The MIT License (MIT)

Copyright (c) 2015-present Rapptz

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""

from __future__ import annotations

from io import BytesIO

import discord

FILE = BytesIO()

def test_file_with_no_name():
    f = discord.File('.gitignore')
    assert f.filename == '.gitignore'

def test_io_with_no_name():
    f = discord.File(FILE)
    assert f.filename == 'untitled'

def test_file_with_name():
    f = discord.File('.gitignore', 'test')
    assert f.filename == 'test'

def test_io_with_name():
    f = discord.File(FILE, 'test')
    assert f.filename == 'test'

def test_file_with_no_name_and_spoiler():
    f = discord.File('.gitignore', spoiler=True)
    assert f.filename == 'SPOILER_.gitignore'
    assert f.spoiler == True

def test_file_with_spoiler_name_and_implicit_spoiler():
    f = discord.File('.gitignore', 'SPOILER_.gitignore')
    assert f.filename == 'SPOILER_.gitignore'
    assert f.spoiler == True

def test_file_with_spoiler_name_and_spoiler():
    f = discord.File('.gitignore', 'SPOILER_.gitignore', spoiler=True)
    assert f.filename == 'SPOILER_.gitignore'
    assert f.spoiler == True

def test_file_with_spoiler_name_and_not_spoiler():
    f = discord.File('.gitignore', 'SPOILER_.gitignore', spoiler=False)
    assert f.filename == '.gitignore'
    assert f.spoiler == False

def test_file_with_name_and_double_spoiler_and_implicit_spoiler():
    f = discord.File('.gitignore', 'SPOILER_SPOILER_.gitignore')
    assert f.filename == 'SPOILER_.gitignore'
    assert f.spoiler == True

def test_file_with_name_and_double_spoiler_and_spoiler():
    f = discord.File('.gitignore', 'SPOILER_SPOILER_.gitignore', spoiler=True)
    assert f.filename == 'SPOILER_.gitignore'
    assert f.spoiler == True

def test_file_with_name_and_double_spoiler_and_not_spoiler():
    f = discord.File('.gitignore', 'SPOILER_SPOILER_.gitignore', spoiler=False)
    assert f.filename == '.gitignore'
    assert f.spoiler == False

def test_file_with_spoiler_with_overriding_name_not_spoiler():
    f = discord.File('.gitignore', spoiler=True)
    f.filename = '.gitignore'
    assert f.filename == '.gitignore'
    assert f.spoiler == False

def test_file_with_spoiler_with_overriding_name_spoiler():
    f = discord.File('.gitignore', spoiler=True)
    f.filename = 'SPOILER_.gitignore'
    assert f.filename == 'SPOILER_.gitignore'
    assert f.spoiler == True

def test_file_not_spoiler_with_overriding_name_not_spoiler():
    f = discord.File('.gitignore')
    f.filename = '.gitignore'
    assert f.filename == '.gitignore'
    assert f.spoiler == False

def test_file_not_spoiler_with_overriding_name_spoiler():
    f = discord.File('.gitignore')
    f.filename = 'SPOILER_.gitignore'
    assert f.filename == 'SPOILER_.gitignore'
    assert f.spoiler == True

def test_file_not_spoiler_with_overriding_name_double_spoiler():
    f = discord.File('.gitignore')
    f.filename = 'SPOILER_SPOILER_.gitignore'
    assert f.filename == 'SPOILER_.gitignore'
    assert f.spoiler == True


text:
class AlembicWriteJob {
 private:
  XSI::CString mFileName;

  std::vector<std::string> mSelection;

  // XSI::CRefArray mSelection;
  std::vector<double> mFrames;
  Abc::OArchive mArchive;
  Abc::OObject mTop;
  unsigned int mTs;

  std::vector<AlembicObjectPtr> mObjects;
  std::map<std::string, AlembicObjectPtr> mObjectsNames;
  float mFrameRate;

  SceneNodePtr exoSceneRoot;

 public:
  std::map<XSI::CString, XSI::CValue> mOptions;

  AlembicWriteJob(const XSI::CString& in_FileName,
                  const std::vector<std::string>& in_Selection,
                  const XSI::CDoubleArray& in_Frames);
  ~AlembicWriteJob();

  Abc::OArchive GetArchive() { return mArchive; }
  Abc::OObject GetTop() { return mTop; }
  const std::vector<double>& GetFrames() { return mFrames; }
  const XSI::CString& GetFileName() { return mFileName; }
  unsigned int GetAnimatedTs() { return mTs; }
  void SetOption(const XSI::CString& in_Name, const XSI::CValue& in_Value);
  bool HasOption(const XSI::CString& in_Name);
  XSI::CValue GetOption(const XSI::CString& in_Name);
  // AlembicObjectPtr GetObject(const XSI::CRef & in_Ref);
  bool AddObject(AlembicObjectPtr in_Obj);
  size_t GetNbObjects() { return mObjects.size(); }
  XSI::CStatus PreProcess();
  XSI::CStatus Process(double frame);
};

#endif


text:
package com.youama.nexus.core.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

/**
 * This package protected class reads a single PDF file.
 *
 * @since 0.1.0
 * @author david
 */
class PdfReader {

    /**
     * File path to the target PDF file.
     */
    private String filePath;

    /**
     * It sets the file path to property.
     *
     * @param filePath
     *        File path to the target PDF file.
     */
    void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    /**
     * It retrieves the content of PDF file.
     *
     * @return The String content of the PDF file.
     * @throws FileNotFoundException
     * @throws IOException
     */
    String getContentFromPdf() throws FileNotFoundException, IOException {
        return getText(getPdfDocument(getInputStream()));
    }

    /**
     * It retrieves the input stream for the PDF file.
     *
     * @return Input stream.
     * @throws FileNotFoundException
     */
    private FileInputStream getInputStream() throws FileNotFoundException {
        File file = new File(filePath);
        return new FileInputStream(file);
    }

    /**
     * It retrieves the PDF document by the input stream.
     *
     * @param inputStream
     *        Input stream of the PDF file.
     * @return PDF document.
     * @throws IOException
     */
    private PDDocument getPdfDocument(FileInputStream inputStream) throws IOException {
        PDFParser parser = new PDFParser(inputStream);
        parser.parse();
        COSDocument cosDoc = parser.getDocument();

        return new PDDocument(cosDoc);
    }

    /**
     * It retrieves the text content from the PDF file by the PDF document.
     *
     * @param pdfDocument
     *        The loaded PDF document.
     * @return The content of the PDF file.
     * @throws IOException
     */
    private String getText(PDDocument pdfDocument) throws IOException {
        PDFTextStripper pdfStripper = new PDFTextStripper();
        return pdfStripper.getText(pdfDocument);
    }

}


text:
/*
 * Created on Oct 22, 2005
 */
package org.cobraparser.html.domimpl;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

class LocalErrorHandler implements ErrorHandler {
  private static final Logger logger = Logger.getLogger(LocalErrorHandler.class.getName());

  /**
   * @param context
   */
  public LocalErrorHandler() {
  }

  public void warning(final SAXParseException exception) throws SAXException {
    logger.log(Level.WARNING, exception.getMessage(), exception.getCause());
  }

  public void error(final SAXParseException exception) throws SAXException {
    logger.log(Level.SEVERE, exception.getMessage(), exception.getCause());
  }

  public void fatalError(final SAXParseException exception) throws SAXException {
    logger.log(Level.SEVERE, exception.getMessage(), exception.getCause());
  }
}


text:
// Code generated by go-swagger; DO NOT EDIT.

package mod

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"net/http"

	"github.com/go-openapi/runtime"

	"github.com/kleister/kleister-api/pkg/api/v1/models"
)

// ShowVersionOKCode is the HTTP code returned for type ShowVersionOK
const ShowVersionOKCode int = 200

/*ShowVersionOK The fetched version details

swagger:response showVersionOK
*/
type ShowVersionOK struct {

	/*
	  In: Body
	*/
	Payload *models.Version `json:"body,omitempty"`
}

// NewShowVersionOK creates ShowVersionOK with default headers values
func NewShowVersionOK() *ShowVersionOK {

	return &ShowVersionOK{}
}

// WithPayload adds the payload to the show version o k response
func (o *ShowVersionOK) WithPayload(payload *models.Version) *ShowVersionOK {
	o.Payload = payload
	return o
}

// SetPayload sets the payload to the show version o k response
func (o *ShowVersionOK) SetPayload(payload *models.Version) {
	o.Payload = payload
}

// WriteResponse to the client
func (o *ShowVersionOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(200)
	if o.Payload != nil {
		payload := o.Payload
		if err := producer.Produce(rw, payload); err != nil {
			panic(err) // let the recovery middleware deal with this
		}
	}
}

// ShowVersionForbiddenCode is the HTTP code returned for type ShowVersionForbidden
const ShowVersionForbiddenCode int = 403

/*ShowVersionForbidden User is not authorized

swagger:response showVersionForbidden
*/
type ShowVersionForbidden struct {

	/*
	  In: Body
	*/
	Payload *models.GeneralError `json:"body,omitempty"`
}

// NewShowVersionForbidden creates ShowVersionForbidden with default headers values
func NewShowVersionForbidden() *ShowVersionForbidden {

	return &ShowVersionForbidden{}
}

// WithPayload adds the payload to the show version forbidden response
func (o *ShowVersionForbidden) WithPayload(payload *models.GeneralError) *ShowVersionForbidden {
	o.Payload = payload
	return o
}

// SetPayload sets the payload to the show version forbidden response
func (o *ShowVersionForbidden) SetPayload(payload *models.GeneralError) {
	o.Payload = payload
}

// WriteResponse to the client
func (o *ShowVersionForbidden) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(403)
	if o.Payload != nil {
		payload := o.Payload
		if err := producer.Produce(rw, payload); err != nil {
			panic(err) // let the recovery middleware deal with this
		}
	}
}

// ShowVersionNotFoundCode is the HTTP code returned for type ShowVersionNotFound
const ShowVersionNotFoundCode int = 404

/*ShowVersionNotFound Version or mod not found

swagger:response showVersionNotFound
*/
type ShowVersionNotFound struct {

	/*
	  In: Body
	*/
	Payload *models.GeneralError `json:"body,omitempty"`
}

// NewShowVersionNotFound creates ShowVersionNotFound with default headers values
func NewShowVersionNotFound() *ShowVersionNotFound {

	return &ShowVersionNotFound{}
}

// WithPayload adds the payload to the show version not found response
func (o *ShowVersionNotFound) WithPayload(payload *models.GeneralError) *ShowVersionNotFound {
	o.Payload = payload
	return o
}

// SetPayload sets the payload to the show version not found response
func (o *ShowVersionNotFound) SetPayload(payload *models.GeneralError) {
	o.Payload = payload
}

// WriteResponse to the client
func (o *ShowVersionNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(404)
	if o.Payload != nil {
		payload := o.Payload
		if err := producer.Produce(rw, payload); err != nil {
			panic(err) // let the recovery middleware deal with this
		}
	}
}

/*ShowVersionDefault Some error unrelated to the handler

swagger:response showVersionDefault
*/
type ShowVersionDefault struct {
	_statusCode int

	/*
	  In: Body
	*/
	Payload *models.GeneralError `json:"body,omitempty"`
}

// NewShowVersionDefault creates ShowVersionDefault with default headers values
func NewShowVersionDefault(code int) *ShowVersionDefault {
	if code <= 0 {
		code = 500
	}

	return &ShowVersionDefault{
		_statusCode: code,
	}
}

// WithStatusCode adds the status to the show version default response
func (o *ShowVersionDefault) WithStatusCode(code int) *ShowVersionDefault {
	o._statusCode = code
	return o
}

// SetStatusCode sets the status to the show version default response
func (o *ShowVersionDefault) SetStatusCode(code int) {
	o._statusCode = code
}

// WithPayload adds the payload to the show version default response
func (o *ShowVersionDefault) WithPayload(payload *models.GeneralError) *ShowVersionDefault {
	o.Payload = payload
	return o
}

// SetPayload sets the payload to the show version default response
func (o *ShowVersionDefault) SetPayload(payload *models.GeneralError) {
	o.Payload = payload
}

// WriteResponse to the client
func (o *ShowVersionDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(o._statusCode)
	if o.Payload != nil {
		payload := o.Payload
		if err := producer.Produce(rw, payload); err != nil {
			panic(err) // let the recovery middleware deal with this
		}
	}
}


text:
package config

// Constants for Amazon AWS
const (
	AWSAccessKeyID                     = ""
	AWSSecretAccessKey                 = ""
	AWSS3RegionName                    = ""
	AWSS3BucketName                    = ""
	AWSS3BucketPrefix                  = ""
	AWSS3TestBucketName                = ""
	AWSS3TestBucketPrefix              = ""
	AWSStaticS3BucketName              = ""
	AWSElasticBeanstalkS3BucketName    = ""
	AWSElasticBeanstalkRegion          = ""
	AWSElasticBeanstalkAppName         = ""
	AWSElasticBeanstalkEnvironmentID   = ""
	AWSElasticBeanstalkEnvironmentName = ""
	AWSCloudfrontURL                   = ""
)


text: export { Pending32 as default } from "../../";


text:
import { initBackend } from 'src/backend'
import Bridge from 'src/bridge'

const bridge = new Bridge({
    listen (fn) {
        window.addEventListener('message', evt => fn(evt.data))
    },
    send (data) {
        console.log('backend -> devtools', data)
        window.parent.postMessage(data, '*')
    }
})

initBackend(bridge)


text:
FROM pantinor/fuse
# https://registry.hub.docker.com/u/pantinor/fuse/dockerfile/
# https://github.com/paoloantinori/dockerfiles/tree/master/centos/fuse
# Base dockerfile: https://github.com/paoloantinori/dockerfiles/blob/master/centos/fuse/base/Dockerfile
# can use this fabric8 distro as the fuse version:
# http://repository.jboss.org/nexus/content/groups/ea/io/fabric8/fabric8-karaf/1.0.0.redhat-396/fabric8-karaf-1.0.0.redhat-396.zip

MAINTAINER Christian Posta <christian.posta@gmail.com>
# twitter @christianposta

CMD service sshd start

EXPOSE 22 8101 8181 44444 1099 61616 2181


text:
#ifdef _MSC_VER
    #ifdef _PointAPI
        #define PointAPI _declspec(dllimport)
    #else
        #define PointAPI _declspec(dllexport)
    #endif
#else
    #if defined(__GNUC__) && __GNUC__ >= 4
        #define PointAPI __attribute__ ((visibility("default")))
    #else
        #define PointAPI
    #endif
#endif

#if defined(STATIC_LIB)
    #undef PointAPI
    #define PointAPI
#endif


text:
package core

import (
	"crypto/tls"
	"errors"
	"github.com/aacebedo/dnsdock/src/servers"
	"github.com/aacebedo/dnsdock/src/utils"
	"github.com/docker/engine-api/client"
	"github.com/docker/engine-api/types"
	eventtypes "github.com/docker/engine-api/types/events"
	"github.com/vdemeester/docker-events"
	"golang.org/x/net/context"
	"net"
	"regexp"
	"strconv"
	"strings"
)

// DockerManager is the entrypoint to the docker daemon
type DockerManager struct {
	config *utils.Config
	list   servers.ServiceListProvider
	client *client.Client
	cancel context.CancelFunc
}

// NewDockerManager creates a new DockerManager
func NewDockerManager(c *utils.Config, list servers.ServiceListProvider, tlsConfig *tls.Config) (*DockerManager, error) {
	defaultHeaders := map[string]string{"User-Agent": "engine-api-cli-1.0"}
	dclient, err := client.NewClient(c.DockerHost, "v1.22", nil, defaultHeaders)

	if err != nil {
		return nil, err
	}

	return &DockerManager{config: c, list: list, client: dclient}, nil
}

// Start starts the DockerManager
func (d *DockerManager) Start() error {
	ctx, cancel := context.WithCancel(context.Background())
	d.cancel = cancel
	startHandler := func(m eventtypes.Message) {
		logger.Debugf("Started container '%s'", m.ID)
		service, err := d.getService(m.ID)
		if err != nil {
			logger.Errorf("%s", err)
		} else {
			d.list.AddService(m.ID, *service)
		}
	}

	stopHandler := func(m eventtypes.Message) {
		logger.Debugf("Stopped container '%s'", m.ID)
		if !d.config.All {
			d.list.RemoveService(m.ID)
		} else {
			logger.Debugf("Stopped container '%s' not removed as --all argument is true", m.ID)
		}
	}

	renameHandler := func(m eventtypes.Message) {
		oldName, ok := m.Actor.Attributes["oldName"]
		name, ok2 := m.Actor.Attributes["oldName"]
		if ok && ok2 {
			logger.Debugf("Renamed container '%s' into '%s'", oldName, name)
			d.list.RemoveService(oldName)
			service, err := d.getService(m.ID)
			if err != nil {
				logger.Errorf("%s", err)
			} else {
				d.list.AddService(m.ID, *service)
			}
		}
	}

	destroyHandler := func(m eventtypes.Message) {
		logger.Debugf("Destroy container '%s'", m.ID)
		if d.config.All {
			d.list.RemoveService(m.ID)
		}
	}

	eventHandler := events.NewHandler(events.ByAction)
	eventHandler.Handle("start", startHandler)
	eventHandler.Handle("stop", stopHandler)
	eventHandler.Handle("die", stopHandler)
	eventHandler.Handle("kill", stopHandler)
	eventHandler.Handle("destroy", destroyHandler)
	eventHandler.Handle("rename", renameHandler)

	events.MonitorWithHandler(ctx, d.client, types.EventsOptions{}, eventHandler)

	containers, err := d.client.ContainerList(context.Background(), types.ContainerListOptions{})
	if err != nil {
		return errors.New("Error getting containers: " + err.Error())
	}

	for _, container := range containers {
		service, err := d.getService(container.ID)
		if err != nil {
			logger.Errorf("%s", err)
			continue
		}
		d.list.AddService(container.ID, *service)
	}

	return nil
}

// Stop stops the DockerManager
func (d *DockerManager) Stop() {
	d.cancel()
}

func (d *DockerManager) getService(id string) (*servers.Service, error) {
	desc, err := d.client.ContainerInspect(context.Background(), id)
	if err != nil {
		return nil, err
	}

	service := servers.NewService()
	service.Aliases = make([]string, 0)

	service.Image = getImageName(desc.Config.Image)
	if imageNameIsSHA(service.Image, desc.Image) {
		logger.Warningf("Warning: Can't route %s, image %s is not a tag.", id[:10], service.Image)
		service.Image = ""
	}
	service.Name = cleanContainerName(desc.Name)

	switch len(desc.NetworkSettings.Networks) {
	case 0:
		logger.Warningf("Warning, no IP address found for container '%s' ", desc.Name)
	default:
		for _, value := range desc.NetworkSettings.Networks {
			ip := net.ParseIP(value.IPAddress)
			if ip != nil {
				service.IPs = append(service.IPs, ip)
			}
		}
	}

	service = overrideFromLabels(service, desc.Config.Labels)
	service = overrideFromEnv(service, splitEnv(desc.Config.Env))
	if service == nil {
		return nil, errors.New("Skipping " + id)
	}

	if d.config.CreateAlias {
		service.Aliases = append(service.Aliases, service.Name)
	}
	return service, nil
}

func getImageName(tag string) string {
	if index := strings.LastIndex(tag, "/"); index != -1 {
		tag = tag[index+1:]
	}
	if index := strings.LastIndex(tag, ":"); index != -1 {
		tag = tag[:index]
	}
	return tag
}

func imageNameIsSHA(image, sha string) bool {
	// Hard to make a judgement on small image names.
	if len(image) < 4 {
		return false
	}
	// Image name is not HEX
	matched, _ := regexp.MatchString("^[0-9a-f]+$", image)
	if !matched {
		return false
	}
	return strings.HasPrefix(sha, image)
}

func cleanContainerName(name string) string {
	return strings.Replace(name, "/", "", -1)
}

func splitEnv(in []string) (out map[string]string) {
	out = make(map[string]string, len(in))
	for _, exp := range in {
		parts := strings.SplitN(exp, "=", 2)
		var value string
		if len(parts) > 1 {
			value = strings.Trim(parts[1], " ") // trim just in case
		}
		out[strings.Trim(parts[0], " ")] = value
	}
	return
}

func overrideFromLabels(in *servers.Service, labels map[string]string) (out *servers.Service) {
	var region string
	for k, v := range labels {
		if k == "com.dnsdock.ignore" {
			return nil
		}

		if k == "com.dnsdock.alias" {
			in.Aliases = strings.Split(v, ",")
		}

		if k == "com.dnsdock.name" {
			in.Name = v
		}

		if k == "com.dnsdock.tags" {
			if len(v) == 0 {
				in.Name = ""
			} else {
				in.Name = strings.Split(v, ",")[0]
			}
		}

		if k == "com.dnsdock.image" {
			in.Image = v
		}

		if k == "com.dnsdock.ttl" {
			if ttl, err := strconv.Atoi(v); err == nil {
				in.TTL = ttl
			}
		}

		if k == "com.dnsdock.region" {
			region = v
		}

		if k == "com.dnsdock.ip_addr" {
			ipAddr := net.ParseIP(v)
			if ipAddr != nil {
				in.IPs = in.IPs[:0]
				in.IPs = append(in.IPs, ipAddr)
			}
		}

		if k == "com.dnsdock.prefix" {
			addrs := make([]net.IP, 0)
			for _, value := range in.IPs {
				if strings.HasPrefix(value.String(), v) {
					addrs = append(addrs, value)
				}
			}
			if len(addrs) == 0 {
				logger.Warningf("The prefix '%s' didn't match any IP addresses of service '%s', the service will be ignored", v, in.Name)
			}
			in.IPs = addrs
		}
	}

	if len(region) > 0 {
		in.Image = in.Image + "." + region
	}
	out = in
	return
}

func overrideFromEnv(in *servers.Service, env map[string]string) (out *servers.Service) {
	var region string
	for k, v := range env {
		if k == "DNSDOCK_IGNORE" || k == "SERVICE_IGNORE" {
			return nil
		}

		if k == "DNSDOCK_ALIAS" {
			in.Aliases = strings.Split(v, ",")
		}

		if k == "DNSDOCK_NAME" {
			in.Name = v
		}

		if k == "SERVICE_TAGS" {
			if len(v) == 0 {
				in.Name = ""
			} else {
				in.Name = strings.Split(v, ",")[0]
			}
		}

		if k == "DNSDOCK_IMAGE" || k == "SERVICE_NAME" {
			in.Image = v
		}

		if k == "DNSDOCK_TTL" {
			if ttl, err := strconv.Atoi(v); err == nil {
				in.TTL = ttl
			}
		}

		if k == "SERVICE_REGION" {
			region = v
		}

		if k == "DNSDOCK_IPADDRESS" {
			ipAddr := net.ParseIP(v)
			if ipAddr != nil {
				in.IPs = in.IPs[:0]
				in.IPs = append(in.IPs, ipAddr)
			}
		}

		if k == "DNSDOCK_PREFIX" {
			addrs := make([]net.IP, 0)
			for _, value := range in.IPs {
				if strings.HasPrefix(value.String(), v) {
					addrs = append(addrs, value)
				}
			}
			if len(addrs) == 0 {
				logger.Warningf("The prefix '%s' didn't match any IP address of  service '%s', the service will be ignored", v, in.Name)
			}
			in.IPs = addrs
		}
	}

	if len(region) > 0 {
		in.Image = in.Image + "." + region
	}
	out = in
	return
}


text:
/*******************************************************************************
 MRF24WG External Interrupt Stub Functions

  Summary: Functions to control MRF24WG External Interrupt.

 *******************************************************************************/

/* MRF24WG0M Universal Driver
*
* Copyright (c) 2012-2013, Microchip <www.microchip.com>
* Contact Microchip for the latest version.
*
* This program is free software; distributed under the terms of BSD
* license:
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1.    Redistributions of source code must retain the above copyright notice, this
*        list of conditions and the following disclaimer.
* 2.    Redistributions in binary form must reproduce the above copyright notice,
*        this list of conditions and the following disclaimer in the documentation
*        and/or other materials provided with the distribution.
* 3.    Neither the name(s) of the above-listed copyright holder(s) nor the names
*        of its contributors may be used to endorse or promote products derived
*        from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/

//==============================================================================
//                                  INCLUDES
//==============================================================================
// board-specific includes
#include <NetworkProfile.x>
#include "./ud_inc/shared/wf_universal_driver.h"

/*****************************************************************************
  Function:
    void WF_EintInit(void);

  Summary:
    Configure host processor external interrupt.  This line is asserted low by
    MRF24WG.

  Description:
    Called by Universal Driver during initialization.

 Parameters:
    None

  Returns:
    None

  Remarks:
    Should not be called directly from application code.
*****************************************************************************/
void WF_EintInit(void)
{
    WIFI_IECxCLR = WIFI_INT_MASK;       // disable INT1 interrupt

    // configure INT1 pin
    WF_INT_IO       = 1;                // set the level of I/O pin high to deassert interrupt (no pullup on board)
    WF_INT_TRIS     = 1;                // configure pin as an input
    WIFI_INT_EDGE   = 0;                // falling edge triggered

    // ensure the interrupt is cleared
    WIFI_IFSxCLR    = WIFI_INT_MASK;    // clear INT1IF bit (clears any pending interrupt)

    // set INT1 interrupt priority and subpriority fields (INT1IP and INT1IS fields)
//    IPC1CLR    = 0xFF000000;      // first clear priority and subpriority fields
//    IPC1SET    = 0x0C000000;      // set INT1 priority=3, subpriority=0
    WIFI_IPC_IP = WF_IPL;           // set priority=3
    WIFI_IPC_IS = WF_SUB_IPL;       // sub priority=0

    // enable the interrupt
    WIFI_IECxSET    = WIFI_INT_MASK;      // enable INT1
}

/*****************************************************************************
  Function:
    void WF_EintEnable(void);

  Summary:
    Enables the MRF24WG external interrupt

  Description:
    Called by Universal Driver during normal operations to enable the MRF24WG
    external interrupt.

    Note: When using level-triggered interrupts it is possible that host MCU
          could miss a falling edge; this can occur because during normal
          operations as the Universal Driver disables the external interrupt for
          short periods.  If the MRF24WG asserts the interrupt line while the
          interrupt is disabled the falling edge won't be detected.  So, a
          check must be made to determine if an interrupt is pending; if so, the
          interrupt must be forced.

          This is not an issue for level-triggered interrupts.

 Parameters:
    None

  Returns:
    None

  Remarks:
    Should not be called directly from application code.
*****************************************************************************/
void WF_EintEnable(void)
{
    // PIC32 uses level-triggered interrupts, so it is possible the Universal Driver
    // may have temporarily disabled the external interrupt, and then missed the
    // falling edge when the MRF24WG asserted the interrupt line.  The code below
    // checks for this condition and forces the interrupt if needed.

    // if interrupt line is low, then PIC32 may have missed the falling edge
    // while the interrupt was disabled.
    if ( WF_INT_IO == 0 )
    {
        // Need to force the interrupt for two reasons:
        //   1) there is an event that needs to be serviced
        //   2) MRF24WG won't generate another falling edge until the interrupt
        //      is processed.
        WIFI_IFSxSET = WIFI_INT_MASK; // this will force the INT1 interrupt as soon as we
                             // we enabled it below.
    }

    /* enable the external interrupt */
    WIFI_IECxSET = WIFI_INT_MASK;
}

/*****************************************************************************
  Function:
    void WF_EintDisable(void);

  Summary:
    Disables the MRF24WG external interrupt

  Description:
    Called by Universal Driver during normal operations to disable the MRF24WG
    external interrupt.

 Parameters:
    None

  Returns:
    None

  Remarks:
    Should not be called directly from application code.
*****************************************************************************/
void WF_EintDisable(void)
{
    WIFI_IECxCLR = WIFI_INT_MASK;
}

/*****************************************************************************
  Function:
    bool WF_isEintDisabled(void);

  Summary:
    Determines if the external interrupt is disabled

  Description:
    Called by Universal Driver during normal operations to check if the current
    state of the external interrupt is disabled.

 Parameters:
    None

  Returns:
    True if interrupt is disabled, else False

  Remarks:
    Should not be called directly from application code.
*****************************************************************************/
bool WF_isEintDisabled(void)
{
    return (WIFI_INT_IE == 0);
}

/*****************************************************************************
  Function:
    bool WF_isEintPending(void);

  Summary:
    Determines if the external interrupt is pending.

  Description:
    Called by Universal Driver during normal operations to check if an external
    interrupt is pending.

 Parameters:
    None

  Returns:
    True if interrupt is pending, else False

  Remarks:
    Should not be called directly from application code.
*****************************************************************************/
bool WF_isEintPending(void)
{
    // if interrupt line is low, but interrupt request has not occurred
    return(((WF_INT_IO == 0) && (WIFI_INT_IF == 0)));
}

/*****************************************************************************
  Function:
    void _WFInterrupt(void);

  Summary:
    MRF24WG external interrupt handler

  Description:
    This interrupt handler should:
        1) ensure the interrupt is disabled upon exit (Universal Driver will reenable it)
        1) clear the interrupt
        2) call WFEintHandler()

 Parameters:
    None

  Returns:
    None

  Remarks:
    None
*****************************************************************************/
#if defined(__PIC32MZXX__)
void __attribute((interrupt(WF_IPL_ISR), at_vector(WF_INT_VEC), nomips16)) _WFInterrupt(void)
#else
void __attribute((interrupt(WF_IPL_ISR), vector(WF_INT_VEC), nomips16)) _WFInterrupt(void)
#endif
{
    // clear EINT
    WIFI_IFSxCLR = WIFI_INT_MASK;        // clear the interrupt
    WIFI_IECxCLR = WIFI_INT_MASK;        // disable external interrupt
    WF_EintHandler();           // call Univeral Driver handler function
}


text:
global.assert = require('chai').assert;
global.expect = require('chai').expect;


text:
#ifndef IMATH_H
#define IMATH_H

#include <cmath>

static const double MATH_PI = 3.14159265358979323846;
#define radtodeg(rad) ( rad * (180/MATH_PI) )
#define degtorad(deg) ( deg * (MATH_PI/180) )

/*class Rect {
public:
    float x, y, width, height;
    Rect( float x = 0, float y = 0, float width = 0, float height = 0 ) : x(x), y(y), width(width), height(height) {};
};*/

class Vector2Df {
public:
    float x, y;

    Vector2Df( float x = 0, float y = 0 ) : x(x), y(y) {};
    Vector2Df operator+ (Vector2Df rhs);
    Vector2Df operator- (Vector2Df rhs);
    Vector2Df operator* (float scalar);
    Vector2Df operator/ (float scalar);

    Vector2Df getRotated( float angle );
    Vector2Df getNormal();
    float getDistance(Vector2Df rhs) const;
    float getDot(Vector2Df rhs) const;
    float getLength() const;
    float getLengthSqr() const;
    float getAngle() const;
};

#endif


text:
ROOT = $(PEGASUS_ROOT)

PEGASUS_ZOS_PROGRAM_OBJECT = yes

DIR = Providers/ManagedSystem/DNSService/tests/testclient

include $(ROOT)/mak/config.mak
include ../../../libraries.mak

PROGRAM = DNSTestClient
SOURCES = DNSTestClient.cpp

include $(ROOT)/mak/program.mak

tests:

poststarttests:
	$(PROGRAM)


text:
<title>@code{GIMPLE_ASM} - GNU Compiler Collection (GCC) Internals</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="GNU Compiler Collection (GCC) Internals">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Tuple-specific-accessors.html#Tuple-specific-accessors" title="Tuple specific accessors">
<link rel="next" href="_0040code_007bGIMPLE_005fASSIGN_007d.html#g_t_0040code_007bGIMPLE_005fASSIGN_007d" title="@code{GIMPLE_ASSIGN}">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

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

Next: <code>GIMPLE_ASSIGN</code>,
Up: Tuple specific accessors

11.8.1 GIMPLE_ASM

— GIMPLE function: gasm *gimple_build_asm_vec (<var> const char *string, vec<tree, va_gc> *inputs, vec<tree, va_gc> *outputs, vec<tree, va_gc> *clobbers, vec<tree, va_gc> *labels</var>)<var></var>

Build a GIMPLE_ASM statement.  This statement is used for
building in-line assembly constructs.  STRING is the assembly
code.  INPUTS, OUTPUTS, CLOBBERS  and LABELS
are the inputs, outputs, clobbered registers and labels.

— GIMPLE function: unsigned gimple_asm_ninputs (<var>const gasm *g</var>)<var></var>

Return the number of input operands for GIMPLE_ASM G.

— GIMPLE function: unsigned gimple_asm_noutputs (<var>const gasm *g</var>)<var></var>

Return the number of output operands for GIMPLE_ASM G.

— GIMPLE function: unsigned gimple_asm_nclobbers (<var>const gasm *g</var>)<var></var>

Return the number of clobber operands for GIMPLE_ASM G.

— GIMPLE function: tree gimple_asm_input_op (<var>const gasm *g, unsigned index</var>)<var></var>

Return input operand INDEX of GIMPLE_ASM G.

— GIMPLE function: void gimple_asm_set_input_op (<var>gasm *g, unsigned index, tree in_op</var>)<var></var>

Set IN_OP to be input operand INDEX in GIMPLE_ASM G.

— GIMPLE function: tree gimple_asm_output_op (<var>const gasm *g, unsigned index</var>)<var></var>

Return output operand INDEX of GIMPLE_ASM G.

— GIMPLE function: void gimple_asm_set_output_op (<var>gasm *g, unsigned index, tree out_op</var>)<var></var>

Set OUT_OP to be output operand INDEX in GIMPLE_ASM G.

— GIMPLE function: tree gimple_asm_clobber_op (<var>const gasm *g, unsigned index</var>)<var></var>

Return clobber operand INDEX of GIMPLE_ASM G.

— GIMPLE function: void gimple_asm_set_clobber_op (<var>gasm *g, unsigned index, tree clobber_op</var>)<var></var>

Set CLOBBER_OP to be clobber operand INDEX in GIMPLE_ASM G.

— GIMPLE function: const char * gimple_asm_string (<var>const gasm *g</var>)<var></var>

Return the string representing the assembly instruction in
GIMPLE_ASM G.

— GIMPLE function: bool gimple_asm_volatile_p (<var>const gasm *g</var>)<var></var>

Return true if G is an asm statement marked volatile.

— GIMPLE function: void gimple_asm_set_volatile (<var>gasm *g, bool volatile_p</var>)<var></var>

Mark asm statement G as volatile or non-volatile based on
VOLATILE_P.