text:
//
//   Copyright 2013 Pixar
//
//   Licensed under the Apache License, Version 2.0 (the "Apache License")
//   with the following modification; you may not use this file except in
//   compliance with the Apache License and the following modification to it:
//   Section 6. Trademarks. is deleted and replaced with:
//
//   6. Trademarks. This License does not grant permission to use the trade
//      names, trademarks, service marks, or product names of the Licensor
//      and its affiliates, except as required to comply with Section 4(c) of
//      the License and to reproduce the content of the NOTICE file.
//
//   You may obtain a copy of the Apache License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the Apache License with the above modification is
//   distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
//   KIND, either express or implied. See the Apache License for the specific
//   language governing permissions and limitations under the Apache License.
//

#ifndef FAR_MESH_FACTORY_H
#define FAR_MESH_FACTORY_H

#include "../version.h"

// Activate Hbr feature adaptive tagging : in order to process the HbrMesh
// adaptively, some tag data is added to HbrFace, HbrVertex and HbrHalfedge.
// While small, these tags incur some performance costs and are by default
// disabled.
#ifndef HBR_ADAPTIVE
#define HBR_ADAPTIVE
#endif

#include "../hbr/mesh.h"
#include "../hbr/bilinear.h"
#include "../hbr/catmark.h"
#include "../hbr/loop.h"

#include "../far/mesh.h"
#include "../far/dispatcher.h"
#include "../far/bilinearSubdivisionTablesFactory.h"
#include "../far/catmarkSubdivisionTablesFactory.h"
#include "../far/loopSubdivisionTablesFactory.h"
#include "../far/patchTables.h"
#include "../far/patchTablesFactory.h"
#include "../far/vertexEditTablesFactory.h"

#include <typeinfo>
#include <set>

namespace OpenSubdiv {
	namespace OPENSUBDIV_VERSION {

		/// \brief Instantiates a FarMesh from an HbrMesh.
		///
		/// FarMeshFactory requires a 2 steps process :
		/// 1. Instantiate a FarMeshFactory object from an HbrMesh
		/// 2. Call "Create" to obtain the FarMesh instance
		///
		/// This tiered factory approach offers client-code the opportunity to access
		/// useful transient information tied to the lifespan of the factory instance.
		/// Specifically, regression code needs to access the remapping tables that
		/// tie HbrMesh vertices to their FarMesh counterparts for comparison.
		///
		template <class T, class U = T> class FarMeshFactory {

		public:

			/// \brief Constructor for the factory.
			/// Analyzes the HbrMesh and stores transient data used to create the
			/// adaptive patch representation. Once the new rep has been instantiated
			/// with 'Create', this factory object can be deleted safely.
			///
			/// @param mesh        The HbrMesh describing the topology (this mesh *WILL* be
			///                    modified by this factory).
			///
			/// @param maxlevel    In uniform subdivision mode : number of levels of
			///                    subdivision. In feature adaptive mode : maximum
			///                    level of isolation around extraordinary topological
			///                    features.
			///
			/// @param adaptive    Switch between uniform and feature adaptive mode
			///
			/// @param firstLevel  First level of subdivision to use when building the
			///                    FarMesh. The default -1 only generates a single patch
			///                    array for the highest level of subdivision)
			///                    Note : firstLevel is only applicable if adaptive is false
			///
			/// @param patchType   The type of patch to create: QUADS or TRIANGLES
			///                    Note : patchType is only applicable if adaptive is false
			///
			FarMeshFactory(HbrMesh<T> * mesh, int maxlevel, bool adaptive = false, int firstLevel = -1,
				FarPatchTables::Type patchType = FarPatchTables::QUADS);

			/// \brief Create a table-based mesh representation
			///
			/// @param requireFVarData create a face-varying table
			///
			/// @return a pointer to the FarMesh created
			///
			FarMesh<U> * Create(bool requireFVarData = false);

			/// \brief Computes the minimum number of adaptive feature isolation levels required
			/// in order for the limit surface to be an accurate representation of the
			/// shape given all the tags and edits.
			///
			/// @param mesh           The HbrMesh describing the topology
			///
			/// @param nfaces         The number of faces in the HbrMesh
			///
			/// @param cornerIsolate  The level of isolation desired for patch corners
			///
			/// @return               The minimum level of isolation of extraordinary
			///                       topological features.
			///
			static int ComputeMinIsolation(HbrMesh<T> const * mesh, int nfaces, int cornerIsolate = 5);

			/// \brief The Hbr mesh that this factory is converting
			HbrMesh<T> const * GetHbrMesh() const { return _hbrMesh; }

			/// \brief Maximum level of subidivision supported by this factory
			int GetMaxLevel() const { return _maxlevel; }

			/// \brief The number of coarse vertices found in the HbrMesh before refinement
			///
			/// @return The number of coarse vertices
			///
			int GetNumCoarseVertices() const { return _numCoarseVertices; }

			/// \brief Total number of faces up to a given level of subdivision
			///
			/// @param level  The number of faces up to 'level' of subdivision
			///
			/// @return       The summation of the number of faces
			///
			int GetNumFacesTotal(int level) const {
				return sumList<HbrFace<T> *>(_facesList, level);
			}

			/// \brief Returns the corresponding index of the HbrVertex<T> in the new
			/// FarMesh
			///
			/// @param v  the vertex
			///
			/// @return   the remapped index of the vertex in the FarMesh
			///
			int GetVertexID(HbrVertex<T> * v);

			/// \brief Returns a the mapping between HbrVertex<T>->GetID() and Far
			/// vertices indices
			///
			/// @return the table that maps HbrMesh to FarMesh vertex indices
			///
			std::vector<int> const & GetRemappingTable() const { return _remapTable; }

		private:
			friend class FarBilinearSubdivisionTablesFactory < T, U > ;
			friend class FarCatmarkSubdivisionTablesFactory < T, U > ;
			friend class FarLoopSubdivisionTablesFactory < T, U > ;
			friend class FarSubdivisionTablesFactory < T, U > ;
			friend class FarVertexEditTablesFactory < T, U > ;
			friend class FarPatchTablesFactory < T > ;

			template <class X> struct VertCompare {
				bool operator()(HbrVertex<X> const * v1, HbrVertex<X> const * v2) const {
					//return v1->GetID() < v2->GetID();
					return (void*)(v1) < (void*)(v2);
				}
			};

			// Non-copyable, so these are not implemented:
			FarMeshFactory(FarMeshFactory const &);
			FarMeshFactory<T, U> & operator=(FarMeshFactory<T, U> const &);

			// True if t1 and t2 are the same, even accounting for plugins
			static bool compareType(std::type_info const & t1, std::type_info const & t2);

			// True if the HbrMesh applies the bilinear subdivision scheme
			static bool isBilinear(HbrMesh<T> const * mesh);

			// True if the HbrMesh applies the Catmull-Clark subdivision scheme
			static bool isCatmark(HbrMesh<T> const * mesh);

			// True if the HbrMesh applies the Loop subdivision scheme
			static bool isLoop(HbrMesh<T> const * mesh);

			// True if the factory is refining adaptively
			bool isAdaptive() { return _adaptive; }

			// False if v prevents a face from being represented with a BSpline
			static bool vertexIsBSpline(HbrVertex<T> * v, bool next);

			// True if a vertex is a regular boundary
			static bool vertexIsRegularBoundary(HbrVertex<T> * v);

			// Non-const accessor to the remapping table
			std::vector<int> & getRemappingTable() { return _remapTable; }

			template <class Type> static int sumList(std::vector<std::vector<Type> > const & list, int level);

			// Calls Hbr to refines the neighbors of v
			static void refineVertexNeighbors(HbrVertex<T> * v);

			// Uniformly refine the Hbr mesh
			static void refine(HbrMesh<T> * mesh, int maxlevel);

			// Adaptively refine the Hbr mesh
			int refineAdaptive(HbrMesh<T> * mesh, int maxIsolate);

			typedef std::vector<std::vector< HbrFace<T> *> > FacesList;

			// Returns sorted vectors of HbrFace<T> pointers sorted by level
			FacesList const & GetFaceList() const { return _facesList; }

		private:
			HbrMesh<T> * _hbrMesh;

			bool _adaptive;

			int _maxlevel,
				_firstlevel,
				_numVertices,
				_numCoarseVertices,
				_numFaces,
				_maxValence,
				_numPtexFaces;

			FarPatchTables::Type _patchType;

			// remapping table to translate vertex ID's between Hbr indices and the
			// order of the same vertices in the tables
			std::vector<int> _remapTable;

			FacesList _facesList;
		};

		template <class T, class U>
		template <class Type> int
			FarMeshFactory<T, U>::sumList(std::vector<std::vector<Type> > const & list, int level) {

			level = std::min(level, (int)list.size() - 1);
			int total = 0;
			for (int i = 0; i <= level; ++i)
				total += (int)list[i].size();
			return total;
		}

		// Refines non-adaptively an Hbr mesh
		template <class T, class U> void
			FarMeshFactory<T, U>::refine(HbrMesh<T> * mesh, int maxlevel) {

			for (int level = 0, firstface = 0; level < maxlevel; ++level) {

				int nfaces = mesh->GetNumFaces();

				for (int i = firstface; i < nfaces; ++i) {

					HbrFace<T> * f = mesh->GetFace(i);

					if (f->GetDepth() == level) {

						if (not f->IsHole()) {
							f->Refine();
						}
						else {

							// Hole faces need to maintain the 1-ring of vertices so we
							// have to create an extra row of children faces around the
							// hole.
							HbrHalfedge<T> * e = f->GetFirstEdge();
							for (int j = 0; j < f->GetNumVertices(); ++j) {
								assert(e);
								if (e->GetRightFace() and(not e->GetRightFace()->IsHole())) {

									// RefineFaceAtVertex only creates a single child face
									// centered on the passed vertex
									HbrSubdivision<T> * s = mesh->GetSubdivision();
									s->RefineFaceAtVertex(mesh, f, e->GetOrgVertex());
									s->RefineFaceAtVertex(mesh, f, e->GetDestVertex());
								}

								e = e->GetNext();
							}
						}
					}
				}

				// Hbr allocates faces sequentially, so there is no need to iterate over
				// faces that have already been refined.
				firstface = nfaces;
			}
		}

		// Scan the faces of a mesh and compute the max level of subdivision required
		template <class T, class U> int
			FarMeshFactory<T, U>::ComputeMinIsolation(HbrMesh<T> const * mesh, int nfaces, int cornerIsolate) {

			assert(mesh);

			int editmax = 0;
			float sharpmax = 0.0f;

			float cornerSharp = 0.0;
			if (mesh->GetInterpolateBoundaryMethod() < HbrMesh<T>::k_InterpolateBoundaryEdgeAndCorner)
				cornerSharp = (float)cornerIsolate;

			// Check vertex sharpness
			int nverts = mesh->GetNumVertices();
			for (int i = 0; i < nverts; ++i) {
				HbrVertex<T> * v = mesh->GetVertex(i);
				if (not v->OnBoundary())
					sharpmax = std::max(sharpmax, v->GetSharpness());
				else {
					sharpmax = std::max(sharpmax, cornerSharp);
				}
			}

			// Check edge sharpness and hierarchical edits
			for (int i = 0; i < nfaces; ++i) {

				HbrFace<T> * f = mesh->GetFace(i);

				// We don't need to check non-coarse faces
				if (not f->IsCoarse())
					continue;

				// Check for edits
				if (f->HasVertexEdits()) {

					HbrVertexEdit<T> ** edits = (HbrVertexEdit<T>**)f->GetHierarchicalEdits();

					while (HbrVertexEdit<T> * edit = *edits++) {
						editmax = std::max(editmax, edit->GetNSubfaces());
					}
				}

				// Check for sharpness
				int nv = f->GetNumVertices();
				for (int j = 0; j < nv; ++j) {

					HbrHalfedge<T> * e = f->GetEdge(j);
					if (not e->IsBoundary())
						sharpmax = std::max(sharpmax, f->GetEdge(j)->GetSharpness());
				}
			}

			int result = std::max((int)ceil(sharpmax) + 1, editmax + 1);

			// Cap the result to "infinitely sharp" (10)
			return std::min(result, (int)HbrHalfedge<T>::k_InfinitelySharp);
		}

		// True if a vertex is a regular boundary
		template <class T, class U> bool
			FarMeshFactory<T, U>::vertexIsRegularBoundary(HbrVertex<T> * v) {
			int valence = v->GetValence();
			return (v->OnBoundary() and(valence == 2 or valence == 3));
		}

		// True if the vertex can be incorporated into a B-spline patch
		template <class T, class U> bool
			FarMeshFactory<T, U>::vertexIsBSpline(HbrVertex<T> * v, bool next) {

			int valence = v->GetValence();

			// Boundary & corner vertices
			if (v->OnBoundary()) {
				if (valence == 2) {
					// corner vertex

					HbrFace<T> * f = v->GetFace();
					// the vertex may not need isolation depending on boundary
					// interpolation rule (sharp vs. rounded corner)
					typename HbrMesh<T>::InterpolateBoundaryMethod method =
						f->GetMesh()->GetInterpolateBoundaryMethod();
					if (method == HbrMesh<T>::k_InterpolateBoundaryEdgeAndCorner) {
						if (not next) {
							// if we are checking coarse vertices (next==false),
							// count the number of corners in the face, because we
							// can only have 1 corner vertex in a corner patch.
							int nsharpboundaries = 0;
							for (int i = 0; i < f->GetNumVertices(); ++i) {
								HbrHalfedge<T> * e = f->GetEdge(i);
								if (e->IsBoundary() and
									e->GetSharpness() == HbrHalfedge<T>::k_InfinitelySharp) {
									++nsharpboundaries;
								}
							}
							return nsharpboundaries < 3 ? true : false;
						}
						else
							return true;
					}
					else
						return false;
				}
				else if (valence > 3) {
					// extraordinary boundar vertex (high valence)
					return false;
				}
				// regular boundary vertices have valence 3
				return true;
			}

			// Extraordinary or creased vertices that aren't corner / boundaries
			if (v->IsExtraordinary() or v->IsSharp(next))
				return false;

			return true;
		}

		// Calls Hbr to refines the neighbors of v
		template <class T, class U> void
			FarMeshFactory<T, U>::refineVertexNeighbors(HbrVertex<T> * v) {

			assert(v);

			HbrHalfedge<T> * start = v->GetIncidentEdge(),
				*next = start;
			do {

				HbrFace<T> * lft = next->GetLeftFace(),
					*rgt = next->GetRightFace();

				if (not((lft and lft->IsHole()) and
					(rgt and rgt->IsHole()))) {

					if (rgt)
						rgt->_adaptiveFlags.isTagged = true;

					if (lft)
						lft->_adaptiveFlags.isTagged = true;

					HbrHalfedge<T> * istart = next,
						*inext = istart;
					do {
						if (not inext->IsInsideHole())
							inext->GetOrgVertex()->Refine();
						inext = inext->GetNext();
					} while (istart != inext);
				}
				next = v->GetNextEdge(next);
			} while (next and next != start);
		}

		// Refines an Hbr Catmark mesh adaptively around extraordinary features
		template <class T, class U> int
			FarMeshFactory<T, U>::refineAdaptive(HbrMesh<T> * mesh, int maxIsolate) {

			int ncoarsefaces = mesh->GetNumCoarseFaces(),
				ncoarseverts = mesh->GetNumVertices();

			// First pass : tag coarse vertices & faces that need refinement

			typedef std::set<HbrVertex<T> *, VertCompare<T> > VertSet;
			VertSet verts, nextverts;

			for (int i = 0; i < ncoarseverts; ++i) {
				HbrVertex<T> * v = mesh->GetVertex(i);

				// Non manifold topology may leave un-connected vertices that need to be skipped
				if (not v->IsConnected()) {
					continue;
				}

				// Tag non-BSpline vertices for refinement
				if (not vertexIsBSpline(v, false)) {
					v->_adaptiveFlags.isTagged = true;
					nextverts.insert(v);
				}
			}

			for (int i = 0; i < ncoarsefaces; ++i) {
				HbrFace<T> * f = mesh->GetFace(i);

				if (f->IsHole())
					continue;

				bool extraordinary = mesh->GetSubdivision()->FaceIsExtraordinary(mesh, f);

				int nv = f->GetNumVertices();
				for (int j = 0; j < nv; ++j) {

					HbrHalfedge<T> * e = f->GetEdge(j);
					assert(e);

					// Tag sharp edges for refinement
					if (e->IsSharp(true) and(not e->IsBoundary())) {
						nextverts.insert(e->GetOrgVertex());
						nextverts.insert(e->GetDestVertex());

						e->GetOrgVertex()->_adaptiveFlags.isTagged = true;
						e->GetDestVertex()->_adaptiveFlags.isTagged = true;
					}

					// Tag extraordinary (non-quad) faces for refinement
					if (extraordinary or f->HasVertexEdits()) {
						HbrVertex<T> * v = f->GetVertex(j);
						v->_adaptiveFlags.isTagged = true;
						nextverts.insert(v);
					}

					// Quad-faces with 2 non-consecutive boundaries need to be flagged
					// for refinement as boundary patches.
					//
					//  o ........ o ........ o ........ o
					//  .          |          |          .     ... boundary edge
					//  .          |   needs  |          .
					//  .          |   flag   |          .     --- regular edge
					//  .          |          |          .
					//  o ........ o ........ o ........ o
					//
					if (e->IsBoundary() and(not f->_adaptiveFlags.isTagged) and nv == 4) {

						if (e->GetPrev() and(not e->GetPrev()->IsBoundary()) and
							e->GetNext() and(not e->GetNext()->IsBoundary()) and
							e->GetNext() and e->GetNext()->GetNext() and e->GetNext()->GetNext()->IsBoundary()) {

							// Tag the face so that we don't check for this again
							f->_adaptiveFlags.isTagged = true;

							// Tag all 4 vertices of the face to make sure 4 boundary
							// sub-patches are generated
							for (int k = 0; k < 4; ++k) {
								HbrVertex<T> * v = f->GetVertex(k);
								v->_adaptiveFlags.isTagged = true;
								nextverts.insert(v);
							}
						}
					}
				}
				_maxValence = std::max(_maxValence, nv);
			}

			// Second pass : refine adaptively around singularities

			for (int level = 0; level < maxIsolate; ++level) {

				verts = nextverts;
				nextverts.clear();

				// Refine vertices
				for (typename VertSet::iterator i = verts.begin(); i != verts.end(); ++i) {

					HbrVertex<T> * v = *i;
					assert(v);

					if (level > 0)
						v->_adaptiveFlags.isTagged = true;
					else
						v->_adaptiveFlags.wasTagged = true;

					refineVertexNeighbors(v);

					// Tag non-BSpline vertices for refinement
					if (not vertexIsBSpline(v, true))
						nextverts.insert(v->Subdivide());

					// Refine edges with creases or edits
					int valence = v->GetValence();
					_maxValence = std::max(_maxValence, valence);

					HbrHalfedge<T> * e = v->GetIncidentEdge();
					for (int j = 0; j < valence; ++j) {

						// Skip edges that have already been processed (HasChild())
						if ((not e->HasChild()) and e->IsSharp(false) and(not e->IsBoundary())) {

							if (not e->IsInsideHole()) {
								nextverts.insert(e->Subdivide());
								nextverts.insert(e->GetOrgVertex()->Subdivide());
								nextverts.insert(e->GetDestVertex()->Subdivide());
							}
						}
						HbrHalfedge<T> * next = v->GetNextEdge(e);
						e = next ? next : e->GetPrev();
					}

					// Flag verts with hierarchical edits for neighbor refinement at the next level
					HbrVertex<T> * childvert = v->Subdivide();
					HbrHalfedge<T> * childedge = childvert->GetIncidentEdge();
					assert(childvert->GetValence() == valence);
					for (int j = 0; j < valence; ++j) {
						HbrFace<T> * f = childedge->GetFace();
						if (f->HasVertexEdits()) {
							int nv = f->GetNumVertices();
							for (int k = 0; k < nv; ++k)
								nextverts.insert(f->GetVertex(k));
						}
						if ((childedge = childvert->GetNextEdge(childedge)) == NULL)
							break;
					}
				}

				// Add coarse verts from extraordinary faces
				if (level == 0) {
					for (int i = 0; i < ncoarsefaces; ++i) {
						HbrFace<T> * f = mesh->GetFace(i);
						assert(f->IsCoarse());

						if (mesh->GetSubdivision()->FaceIsExtraordinary(mesh, f))
							nextverts.insert(f->Subdivide());
					}
				}
			}
			return maxIsolate;
		}

		// Assumption : the order of the vertices in the HbrMesh could be set in any
		// random order, so the builder runs 2 passes over the entire vertex list to
		// gather the counters needed to generate the indexing tables.
		template <class T, class U>
		FarMeshFactory<T, U>::FarMeshFactory(HbrMesh<T> * mesh, int maxlevel, bool adaptive, int firstlevel, FarPatchTables::Type patchType) :
			_hbrMesh(mesh),
			_adaptive(adaptive),
			_maxlevel(maxlevel),
			_firstlevel(firstlevel),
			_numVertices(-1),
			_numCoarseVertices(-1),
			_numFaces(-1),
			_maxValence(4),
			_numPtexFaces(-1),
			_patchType(patchType),
			_facesList(maxlevel + 1)
		{
			_numCoarseVertices = mesh->GetNumVertices();
			_numPtexFaces = getNumPtexFaces(mesh);

			// Subdivide the Hbr mesh up to maxlevel.
			//
			// Note : using a placeholder vertex class 'T' can greatly speed up the
			// topological analysis if the interpolation results are not used.
			if (adaptive)
				_maxlevel = refineAdaptive(mesh, maxlevel);
			else
				refine(mesh, maxlevel);

			_numFaces = mesh->GetNumFaces();

			_numVertices = mesh->GetNumVertices();

			if (not adaptive) {

				// Populate the face lists
				int fsize = 0;
				for (int i = 0; i < _numFaces; ++i) {
					HbrFace<T> * f = mesh->GetFace(i);
					assert(f);
					if (f->GetDepth() == 0 and(not f->IsHole()))
						fsize += mesh->GetSubdivision()->GetFaceChildrenCount(f->GetNumVertices());
				}

				_facesList[0].reserve(mesh->GetNumCoarseFaces());
				_facesList[1].reserve(fsize);
				for (int l = 2; l <= maxlevel; ++l)
					_facesList[l].reserve(_facesList[l - 1].capacity() * 4);

				for (int i = 0; i < _numFaces; ++i) {
					HbrFace<T> * f = mesh->GetFace(i);
					if (f->GetDepth() <= maxlevel and(not f->IsHole()))
						_facesList[f->GetDepth()].push_back(f);
				}
			}
		}

		template <class T, class U> bool
			FarMeshFactory<T, U>::compareType(std::type_info const & t1, std::type_info const & t2) {

			if (t1 == t2) {
				return true;
			}

			// On some systems, distinct instances of \c type_info objects compare equal if
			// their name() functions return equivalent strings.  On other systems, distinct
			// type_info objects never compare equal.  The latter can cause problems in the
			// presence of plugins loaded without RTLD_GLOBAL, because typeid(T) returns
			// different \c type_info objects for the same T in the two plugins.
			for (char const * p1 = t1.name(), *p2 = t2.name(); *p1 == *p2; ++p1, ++p2)
				if (*p1 == '\0')
					return true;
			return false;
		}

		template <class T, class U> bool
			FarMeshFactory<T, U>::isBilinear(HbrMesh<T> const * mesh) {
			return compareType(typeid(*(mesh->GetSubdivision())), typeid(HbrBilinearSubdivision<T>));
		}

		template <class T, class U> bool
			FarMeshFactory<T, U>::isCatmark(HbrMesh<T> const * mesh) {
			return compareType(typeid(*(mesh->GetSubdivision())), typeid(HbrCatmarkSubdivision<T>));
		}

		template <class T, class U> bool
			FarMeshFactory<T, U>::isLoop(HbrMesh<T> const * mesh) {
			return compareType(typeid(*(mesh->GetSubdivision())), typeid(HbrLoopSubdivision<T>));
		}

		template <class T, class U> void
			copyVertex(T & /* dest */, U const & /* src */) {
		}

		template <class T> void
			copyVertex(T & dest, T const & src) {
			dest = src;
		}

		template <class T> int
			getNumPtexFaces(HbrMesh<T> const * hmesh) {

			HbrFace<T> * lastface = hmesh->GetFace(hmesh->GetNumFaces() - 1);
			assert(lastface);

			int result = lastface->GetPtexIndex();

			result += (hmesh->GetSubdivision()->FaceIsExtraordinary(hmesh, lastface) ?
				lastface->GetNumVertices() : 1);

			return result;
		}

		template <class T, class U> FarMesh<U> *
			FarMeshFactory<T, U>::Create(bool requireFVarData) {

			assert(GetHbrMesh());

			// Note : we cannot create a Far rep of level 0 (coarse mesh)
			if (GetMaxLevel() < 1)
				return 0;

			FarMesh<U> * result = new FarMesh<U>();

			if (isBilinear(GetHbrMesh())) {
				result->_subdivisionTables = FarBilinearSubdivisionTablesFactory<T, U>::Create(this, &result->_batches);
			}
			else if (isCatmark(GetHbrMesh())) {
				result->_subdivisionTables = FarCatmarkSubdivisionTablesFactory<T, U>::Create(this, &result->_batches);
			}
			else if (isLoop(GetHbrMesh())) {
				result->_subdivisionTables = FarLoopSubdivisionTablesFactory<T, U>::Create(this, &result->_batches);
			}
			else
				assert(0);
			assert(result->_subdivisionTables);

			// If the vertex classes aren't place-holders, copy the data of the coarse
			// vertices into the vertex buffer.
			if (sizeof(U) > 1) {
				result->_vertices.resize(_numVertices);
				for (int i = 0; i < GetNumCoarseVertices(); ++i)
					copyVertex(result->_vertices[i], GetHbrMesh()->GetVertex(i)->GetData());
			}

			int fvarwidth = requireFVarData ? _hbrMesh->GetTotalFVarWidth() : 0;

			// Create the element indices tables (patches for adaptive, quads for non-adaptive)
			if (isAdaptive()) {

				FarPatchTablesFactory<T> factory(GetHbrMesh(), _numFaces, _remapTable);

				// XXXX: currently PatchGregory shader supports up to 29 valence
				result->_patchTables = factory.Create(_maxValence, _numPtexFaces, fvarwidth);

			}
			else {
				result->_patchTables = FarPatchTablesFactory<T>::Create(GetHbrMesh(), _facesList, _remapTable, _firstlevel, _patchType, _numPtexFaces, fvarwidth);
			}
			assert(result->_patchTables);

			// Create VertexEditTables if necessary
			if (GetHbrMesh()->HasVertexEdits()) {
				result->_vertexEditTables = FarVertexEditTablesFactory<T, U>::Create(this, result, &result->_batches, GetMaxLevel());
				assert(result->_vertexEditTables);
			}

			return result;
		}

		template <class T, class U> int
			FarMeshFactory<T, U>::GetVertexID(HbrVertex<T> * v) {
			assert(v  and(v->GetID() < _remapTable.size()));
			return _remapTable[v->GetID()];
		}

	} // end namespace OPENSUBDIV_VERSION
	using namespace OPENSUBDIV_VERSION;

} // end namespace OpenSubdiv

#endif /* FAR_MESH_FACTORY_H */


text:
package org.quartzpowered.protocol.codec.v1_8_R1.play.client;

import org.quartzpowered.network.buffer.Buffer;
import org.quartzpowered.network.protocol.codec.Codec;
import org.quartzpowered.protocol.packet.play.client.EntityLookMovePacket;

public class EntityLookMoveCodec implements Codec<EntityLookMovePacket> {
    @Override
    public void encode(Buffer buffer, EntityLookMovePacket packet) {
        buffer.writeVarInt(packet.getEntityId());
        buffer.writeFixedPointByte(packet.getDeltaX());
        buffer.writeFixedPointByte(packet.getDeltaY());
        buffer.writeFixedPointByte(packet.getDeltaZ());
        buffer.writeAngle((float) packet.getYaw());
        buffer.writeAngle((float) packet.getPitch());
        buffer.writeBoolean(packet.isOnGround());

    }

    @Override
    public void decode(Buffer buffer, EntityLookMovePacket packet) {
        packet.setEntityId(buffer.readVarInt());
        packet.setDeltaX(buffer.readFixedPointByte());
        packet.setDeltaY(buffer.readFixedPointByte());
        packet.setDeltaZ(buffer.readFixedPointByte());
        packet.setYaw(buffer.readAngle());
        packet.setPitch(buffer.readAngle());
        packet.setOnGround(buffer.readBoolean());
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Template Name: Publications Type Archive
 */
?>

<?php if (!have_posts()) : ?>

    <?php _e('Sorry, no results were found.', 'sage'); ?>

  <?php get_search_form(); ?>
<?php endif; ?>

<?php while (have_posts()) : the_post(); ?>
  <?php get_template_part('templates/excerpt', 'publication'); ?>
<?php endwhile; ?>


text:
package net.czpilar.dropdrive.core.exception;

/**
 * Exception used when file handling fails.
 *
 * @author David Pilar (david@czpilar.net)
 */
public class FileHandleException extends DropDriveException {

    public FileHandleException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

using error = Microsoft.Build.Shared.ErrorUtilities;

namespace Microsoft.Build.Conversion
{
    /// <summary>
    /// This class implements a custom text reader for the old VS7/Everett
    /// project file format.  The old format allowed certain XML special
    /// characters to be present within an XML attribute value.  For example,
    ///
    ///     <MyElement MyAttribute="My --> Value" />
    ///
    /// However, the System.Xml classes are more strict, and do not allow
    /// the < or > characters to exist within an attribute value.  But
    /// the conversion utility still needs to be able to convert all old
    /// project files.  So the OldVSProjectFileReader class implements
    /// the TextReader interface, thereby effectively intercepting all of
    /// the calls which are used by the XmlTextReader to actually read the
    /// raw text out of the file.  As we are reading the text out of the
    /// file, we replace all > (less-than) characters inside attribute values with ">",
    /// etc.  The XmlTextReader has no idea that this is going on, but
    /// no longer complains about invalid characters.
    /// </summary>
    /// <owner>rgoel</owner>
    internal sealed class OldVSProjectFileReader : TextReader
    {
        // This is the underlying text file where we will be reading the raw text
        // from.
        private StreamReader    oldVSProjectFile;

        // We will be reading one line at a time out of the text file, and caching
        // it here.
        private StringBuilder   singleLine;

        // The "TextReader" interface that we are implementing only allows
        // forward access through the file.  You cannot seek to a random location
        // or read backwards.  This variable is the index into the "singleLine"
        // string above, which indicates how far the caller has read.  Once we
        // reach the end of "singleLine", we'll go read a new line from the file.
        private int             currentReadPositionWithinSingleLine;

        /// <summary>
        /// Constructor, initialized using the filename of an existing old format
        /// project file on disk.
        /// </summary>
        /// <owner>rgoel</owner>
        /// <param name="filename"></param>
        internal OldVSProjectFileReader
            (
            string filename
            )
        {
            this.oldVSProjectFile = new StreamReader(filename, Encoding.Default); // HIGHCHAR: Default means ANSI, ANSI is what VS .NET 2003 wrote. Without this, the project would be read as ASCII.

            this.singleLine = new StringBuilder();
            this.currentReadPositionWithinSingleLine = 0;
        }

        /// <summary>
        /// Releases all locks and closes all handles on the underlying file.
        /// </summary>
        /// <owner>rgoel</owner>
        public override void Close
            (
            )
        {
            oldVSProjectFile.Close();
        }

        /// <summary>
        /// Returns the next character in the file, without actually advancing
        /// the read pointer.  Returns -1 if we're already at the end of the file.
        /// </summary>
        /// <returns></returns>
        /// <owner>rgoel</owner>
        public override int Peek
            (
            )
        {
            // If necessary, read a new line of text into our internal buffer
            // (this.singleLine).
            if (!this.ReadLineIntoInternalBuffer())
            {
                // If we've reached the end of the file, return -1.
                return -1;
            }

            // Return the next character, but don't advance the current position.
            return this.singleLine[this.currentReadPositionWithinSingleLine];
        }

        /// <summary>
        /// Returns the next character in the file, and advances the read pointer.
        /// Returns -1 if we're already at the end of the file.
        /// </summary>
        /// <returns></returns>
        /// <owner>rgoel</owner>
        public override int Read
            (
            )
        {
            // Use our "Peek" functionality above.
            int returnCharacter = this.Peek();

            // If there's a character there, advance the read pointer by one.
            if (returnCharacter != -1)
            {
                this.currentReadPositionWithinSingleLine++;
            }

            return returnCharacter;
        }

        /// <summary>
        /// Reads the specified number of characters into the caller's buffer,
        /// starting at the specified index into the caller's buffer.  Returns
        /// the number of characters read, or 0 if we're already at the end of
        /// the file.
        /// </summary>
        /// <param name="bufferToReadInto"></param>
        /// <param name="startIndexIntoBuffer"></param>
        /// <param name="charactersToRead"></param>
        /// <returns></returns>
        /// <owner>rgoel</owner>
        public override int Read
            (
            char[]  bufferToReadInto,       // The buffer to read the data into.
            int     startIndexIntoBuffer,   // The index into "bufferToReadInto"
            int     charactersToRead        // The number of characters to read.
            )
        {
            // Make sure there's enough room in the caller's buffer for what he's
            // asking us to do.
            if ((startIndexIntoBuffer + charactersToRead) > bufferToReadInto.Length)
            {
                // End-user should never see this message, so it doesn't need to be localized.
                throw new ArgumentException("Cannot write past end of user's buffer.", nameof(charactersToRead));
            }

            int charactersCopied = 0;

            // Keep looping until we've read in the number of characters requested.
            // If we reach the end of file, we'll break out early.
            while (0 < charactersToRead)
            {
                // Read more data from the underlying file if necessary.
                if (!this.ReadLineIntoInternalBuffer())
                {
                    // If we've reached the end of the underlying file, exit the
                    // loop.
                    break;
                }

                // We're going to copy characters from our cached singleLine to the caller's
                // buffer.  The number of characters to copy is the lesser of (the remaining
                // characters in our cached singleLine) and (the number of characters remaining
                // before we've fulfilled the caller's request).
                int charactersToCopy = (this.singleLine.Length - currentReadPositionWithinSingleLine);
                if (charactersToCopy > charactersToRead)
                {
                    charactersToCopy = charactersToRead;
                }

                // Copy characters from our cached "singleLine" to the caller's buffer.
                this.singleLine.ToString().CopyTo(this.currentReadPositionWithinSingleLine, bufferToReadInto,
                    startIndexIntoBuffer, charactersToCopy);

                // Update all counts and indices.
                startIndexIntoBuffer += charactersToCopy;
                this.currentReadPositionWithinSingleLine += charactersToCopy;
                charactersCopied += charactersToCopy;
                charactersToRead -= charactersToCopy;
            }

            return charactersCopied;
        }

        /// <summary>
        /// Not implemented.  Our class only supports reading from a file, which
        /// can't change beneath the covers while we're reading from it.  Therefore,
        /// a blocking read doesn't make sense for our scenario.  (A blocking read
        /// is where you wait until the requested number of characters actually
        /// become available ... which is never going to happen if you've already
        /// reached the end of a file.)
        /// </summary>
        /// <param name="bufferToReadInto"></param>
        /// <param name="startIndexIntoBuffer"></param>
        /// <param name="charactersToRead"></param>
        /// <returns></returns>
        /// <owner>rgoel</owner>
        public override int ReadBlock
            (
            char[]  bufferToReadInto,
            int     startIndexIntoBuffer,
            int     charactersToRead
            )
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Reads a single line of text, and returns it as a string, not including the
        /// terminating line-ending characters.  If we were at the end of the file,
        /// return null.
        /// </summary>
        /// <returns></returns>
        /// <owner>rgoel</owner>
        public override string ReadLine
            (
            )
        {
            // Read a new line from the underlying file if necessary (that is, only
            // if our currently cached singleLine has already been used up).
            if (!this.ReadLineIntoInternalBuffer())
            {
                // If we reached the end of the underlying file, return null.
                return null;
            }

            // We now have a single line of text cached in our "singleLine" variable.
            // Just return that, or the portion of that which hasn't been already read
            // by the caller).
            string result = this.singleLine.ToString(this.currentReadPositionWithinSingleLine,
                this.singleLine.Length - this.currentReadPositionWithinSingleLine);

            // The caller has read the entirety of our cached "singleLine", so update
            // our read pointer accordingly.
            this.currentReadPositionWithinSingleLine = this.singleLine.Length;

            // Strip off the line endings before returning to caller.
            char[] lineEndingCharacters = new char[] {'\r', '\n'};
            return result.Trim(lineEndingCharacters);
        }

        /// <summary>
        /// Reads the remainder of the file, and returns it as a string.  Returns
        /// an empty string if we've already reached the end of the file.
        /// </summary>
        /// <returns></returns>
        /// <owner>rgoel</owner>
        public override string ReadToEnd
            (
            )
        {
            // This is what we're going to return to the caller.
            StringBuilder result = new StringBuilder();

            // Keep reading lines of text out of the underlying file, one line at
            // a time.
            while (true)
            {
                if (!this.ReadLineIntoInternalBuffer())
                {
                    // Exit the loop when we've reached the end of the underlying
                    // file.
                    break;
                }

                // Append the line of text to the resulting output.
                result.Append(this.singleLine.ToString(this.currentReadPositionWithinSingleLine,
                    this.singleLine.Length - this.currentReadPositionWithinSingleLine));

                this.currentReadPositionWithinSingleLine = this.singleLine.Length;
            }

            return result.ToString();
        }

        /// <summary>
        /// And this is where the real magic happens.  If our currently cached
        /// "singleLine" has been used up, we read a new line of text from the
        /// underlying text file.  But as we read the line of text from the file,
        /// we immediately replace all instances of special characters that occur
        /// within double-quotes with the corresponding XML-friendly equivalents.
        /// For example, if the underlying text file contained this:
        ///
        ///     <MyElement MyAttribute="My --> Value" />
        ///
        /// then we would read it in and immediately convert it to this:
        ///
        ///     <MyElement MyAttribute="My --> Value" />
        ///
        /// and we would store it this way in our "singleLine", so that the callers
        /// never know the difference.
        ///
        /// This method returns true on success, and false if we were unable to
        /// read a new line (due to end of file).
        /// </summary>
        /// <returns></returns>
        /// <owner>rgoel</owner>
        private bool ReadLineIntoInternalBuffer
            (
            )
        {
            // Only do the work if we've already used up the data in the currently
            // cached "singleLine".
            if (this.currentReadPositionWithinSingleLine >= this.singleLine.Length)
            {
                // Read a line of text from the underlying file.
                string lineFromProjectFile = this.oldVSProjectFile.ReadLine();
                if (lineFromProjectFile == null)
                {
                    // If we've reached the end of the file, return false.
                    return false;
                }

                // Take the line of text just read, and replace all special characters
                // with the escaped XML-friendly string equivalents.
                this.singleLine = new StringBuilder(this.ReplaceSpecialCharacters(lineFromProjectFile));

                // The underlying StreamReader.ReadLine method doesn't give us the
                // trailing line endings, so add them back ourselves.
                this.singleLine.Append(Environment.NewLine);

                // So now we have a new cached "singleLine".  Reset the read pointer
                // to the beginning of the new line just read.
                this.currentReadPositionWithinSingleLine = 0;
            }

            return true;
        }

        /// <summary>
        /// This method uses a regular expression to search for the stuff in
        /// between double-quotes.  We obviously don't want to touch the stuff
        /// OUTSIDE of double-quotes, because then we would be mucking with the
        /// real angle-brackets that delimit the XML element names, etc.
        /// </summary>
        /// <param name="originalLine"></param>
        /// <returns></returns>
        /// <owner>rgoel</owner>
        private string ReplaceSpecialCharacters
            (
            string originalLine
            )
        {
            // Find the stuff within double-quotes, and send it off to the
            // "ReplaceSpecialCharactersInXmlAttribute" for proper replacement of
            // the special characters.
            Regex attributeValueInsideDoubleQuotesPattern = new Regex("= *\"[^\"]*\"");

            string replacedStuffInsideDoubleQuotes = attributeValueInsideDoubleQuotesPattern.Replace(originalLine,
                new MatchEvaluator(this.ReplaceSpecialCharactersInXmlAttribute));

            // Find the stuff within single-quotes, and send it off to the
            // "ReplaceSpecialCharactersInXmlAttribute" for proper replacement of
            // the special characters.
            Regex attributeValueInsideSingleQuotesPattern = new Regex("= *'[^']*'");

            string replacedStuffInsideSingleQuotes = attributeValueInsideSingleQuotesPattern.Replace(replacedStuffInsideDoubleQuotes,
                new MatchEvaluator(this.ReplaceSpecialCharactersInXmlAttribute));

            return replacedStuffInsideSingleQuotes;
        }

        /// <summary>
        /// This method is used as the delegate that is passed into Regex.Replace.
        /// It a regular expression to search for the stuff in
        /// between double-quotes.  We obviously don't want to touch the stuff
        /// OUTSIDE of double-quotes, because then we would be mucking with the
        /// real angle-brackets that delimit the XML element names, etc.
        /// </summary>
        /// <param name="xmlAttribute"></param>
        /// <returns></returns>
        /// <owner>RGoel</owner>
        private string ReplaceSpecialCharactersInXmlAttribute
            (
            Match xmlAttribute
            )
        {
            // We've been given the string for the attribute value (i.e., all the stuff
            // within double-quotes, including the double-quotes).  Replace all the special characters
            // within it, and return the new string.
            return ReplaceSpecialCharactersInXmlAttributeString(xmlAttribute.Value);
        }

        /// <summary>
        /// This method actually does the replacement of special characters within the
        /// text of the XML attribute.
        /// </summary>
        /// <param name="xmlAttributeText">Input string</param>
        /// <returns>New string with all the replacements (e.g. "&" becomes "&amp;", etc.)</returns>
        /// <owner>RGoel</owner>
        internal static string ReplaceSpecialCharactersInXmlAttributeString
            (
            string xmlAttributeText
            )
        {
            // Replace the special characters with their XML-friendly escaped equivalents.  The
            // "<" and ">" signs are easy, because if they exist at all within the value of an
            // XML attribute, we know that they need to be replaced with "<" and ">"
            // respectively.
            xmlAttributeText = xmlAttributeText.Replace("<", "<");
            xmlAttributeText = xmlAttributeText.Replace(">", ">");
            xmlAttributeText = ReplaceNonEscapingAmpersands(xmlAttributeText);

            return xmlAttributeText;
        }

        // Note -- the comment below is rendered a little confusing by escaping for XML doc compiler. Read "&" as "&"
        // and "&amp;" as "&". Or just look at the intellisense tooltip.
        /// <summary>
        /// This method scans the strings for "&" characters, and based on what follows
        /// the "&" character, it determines whether the "&" character needs to be replaced
        /// with "&amp;".  The old XML parser used in the VS.NET 2002/2003 project system
        /// was quite inconsistent in its treatment of escaped characters in XML, so here
        /// we're having to make up for those bugs.  The new XML parser (System.Xml)
        /// is much more strict in enforcing proper XML syntax, and therefore doesn't
        /// tolerate "&" characters in the XML attribute value, unless the "&" is being
        /// used to escape some special character.
        /// </summary>
        /// <param name="xmlAttributeText">Input string</param>
        /// <returns>New string with all the replacements (e.g. "&" becomes "&amp;", etc.)</returns>
        /// <owner>RGoel</owner>
        private static string ReplaceNonEscapingAmpersands
            (
            string xmlAttributeText
            )
        {
            // Ampersands are a little trickier, because some instances of "&" we need to leave
            // untouched, and some we need to replace with "&".  For example,
            //      aaa&bbb         should be replaced with         aaa&bbb
            // But:
            //      aaa<bbb      should not be touched.

            // Loop through each instance of "&"
            int indexOfAmpersand = xmlAttributeText.IndexOf('&');
            while (indexOfAmpersand != -1)
            {
                // If an "&" was found, search for the next ";" following the "&".
                int indexOfNextSemicolon = xmlAttributeText.IndexOf(';', indexOfAmpersand);
                if (indexOfNextSemicolon == -1)
                {
                    // No semicolon means that the ampersand was really intended to be a literal
                    // ampersand and therefore we need to replace it with "&".  For example,
                    //
                    //     aaa&bbb          should get replaced with        aaa&bbb
                    xmlAttributeText = ReplaceAmpersandWithLiteral(xmlAttributeText, indexOfAmpersand);
                }
                else
                {
                    // We found the semicolon.  Capture the characters between (but not
                    // including) the "&" and ";".
                    string entityName = xmlAttributeText.Substring(indexOfAmpersand + 1,
                        indexOfNextSemicolon - indexOfAmpersand - 1);

                    // Perf note: Here we are walking through the entire list of entities, and
                    // doing a string comparison for each.  This is expensive, but this code
                    // should only get executed in fairly rare circumstances.  It's not very
                    // common for people to have these embedded into their project files.
                    bool foundEntity = false;
                    for (int i = 0 ; i < entities.Length ; i++)
                    {
                        // Case-sensitive comparison to see if the entity name matches any of
                        // the well-known ones that were emitted by the XML writer in the VS.NET
                        // 2002/2003 project system.
                        if (String.Equals(entityName, entities[i], StringComparison.Ordinal))
                        {
                            foundEntity = true;
                            break;
                        }
                    }

                    // If it didn't match a well-known entity name, then the next thing to
                    // check is if it represents an ASCII code.  For example, in an XML
                    // attribute, if I wanted to represent the "+" sign, I could do this:
                    //
                    //          +
                    //
                    if (!foundEntity && (entityName.Length > 0) && (entityName[0] == '#'))
                    {
                        // At this point, we know entityName is something like "#1234" or "#x1234abcd"
                        bool isNumber = false;

                        // A lower-case "x" in the second position indicates a hexadecimal value.
                        if ((entityName.Length > 2) && (entityName[1] == 'x'))
                        {
                            isNumber = true;

                            // It's a hexadecimal number.  Make sure every character of the entity
                            // is in fact a valid hexadecimal character.
                            for (int i = 2; i < entityName.Length; i++)
                            {
                                if (!Uri.IsHexDigit(entityName[i]))
                                {
                                    isNumber = false;
                                    break;
                                }
                            }
                        }
                        else if (entityName.Length > 1)
                        {
                            // Otherwise it's a decimal value.
                            isNumber = true;

                            // ake sure every character of the entity is in fact a valid decimal number.
                            for (int i = 1; i < entityName.Length; i++)
                            {
                                if (!Char.IsNumber(entityName[i]))
                                {
                                    isNumber = false;
                                    break;
                                }
                            }
                        }

                        if (isNumber)
                        {
                            foundEntity = true;
                        }
                    }

                    // If the ampersand did not precede an actual well-known entity, then we DO want to
                    // replace the "&" with a "&".  Otherwise we don't.
                    if (!foundEntity)
                    {
                        xmlAttributeText = ReplaceAmpersandWithLiteral(xmlAttributeText, indexOfAmpersand);
                    }
                }

                // We're done process that particular "&".  Now find the next one.
                indexOfAmpersand = xmlAttributeText.IndexOf('&', indexOfAmpersand + 1);
            }

            return xmlAttributeText;
        }

        // Note -- the comment below is rendered a little confusing by escaping for XML doc compiler. Read "&" as "&"
        // and "&amp;" as "&". Or just look at the intellisense tooltip.
        /// <summary>
        /// Replaces a single instance of an "&" character in a string with "&amp;" and returns the new string.
        /// </summary>
        /// <param name="originalString">Original string where we should find an "&" character.</param>
        /// <param name="indexOfAmpersand">The index of the "&" which we want to replace.</param>
        /// <returns>The new string with the "&" replaced with "&amp;".</returns>
        /// <owner>RGoel</owner>
        internal static string ReplaceAmpersandWithLiteral
            (
            string originalString,
            int indexOfAmpersand
            )
        {
            error.VerifyThrow(originalString[indexOfAmpersand] == '&',
                "Caller passed in a string that doesn't have an '&' character in the specified location.");

            StringBuilder replacedString = new StringBuilder();

            replacedString.Append(originalString, 0, indexOfAmpersand);
            replacedString.Append("&");
            replacedString.Append(originalString, indexOfAmpersand + 1, originalString.Length - indexOfAmpersand + 1);

            return replacedString.ToString();
        }

        // This is the complete list of well-known entity names that were written out
        // by the XML writer in the VS.NET 2002/2003 project system.  This list was
        // taken directly from the source code.
        private static readonly string[] entities =
        {
            "quot",          //
            "amp",           // & - ampersand
            "apos",          // ' - apostrophe //// not part of HTML!
            "lt",            // < less than
            "gt",            // > greater than
            "nbsp",         // Non breaking space
            "iexcl",        //
            "cent",         // cent
            "pound",        // pound
            "curren",       // currency
            "yen",          // yen
            "brvbar",       // vertical bar
            "sect",         // section
            "uml",          //
            "copy",         // Copyright
            "ordf",         //
            "laquo",        //
            "not",          //
            "shy",          //
            "reg",          // Registered TradeMark
            "macr",         //
            "deg",          //
            "plusmn",       //
            "sup2",         //
            "sup3",         //
            "acute",        //
            "micro",        //
            "para",         //
            "middot",       //
            "cedil",        //
            "sup1",         //
            "ordm",         //
            "raquo",        //
            "frac14",       // 1/4
            "frac12",       // 1/2
            "frac34",       // 3/4
            "iquest",       // Inverse question mark
            "Agrave",       // Capital A grave accent
            "Aacute",       // Capital A acute accent
            "Acirc",        // Capital A circumflex accent
            "Atilde",       // Capital A tilde
            "Auml",         // Capital A dieresis or umlaut mark
            "Aring",        // Capital A ring
            "AElig",        // Capital AE dipthong (ligature)
            "Ccedil",       // Capital C cedilla
            "Egrave",       // Capital E grave accent
            "Eacute",       // Capital E acute accent
            "Ecirc",        // Capital E circumflex accent
            "Euml",         // Capital E dieresis or umlaut mark
            "Igrave",       // Capital I grave accent
            "Iacute",       // Capital I acute accent
            "Icirc",        // Capital I circumflex accent
            "Iuml",         // Capital I dieresis or umlaut mark
            "ETH",          // Capital Eth Icelandic
            "Ntilde",       // Capital N tilde
            "Ograve",       // Capital O grave accent
            "Oacute",       // Capital O acute accent
            "Ocirc",        // Capital O circumflex accent
            "Otilde",       // Capital O tilde
            "Ouml",         // Capital O dieresis or umlaut mark
            "times",        // multiply or times
            "Oslash",       // Capital O slash
            "Ugrave",       // Capital U grave accent
            "Uacute",       // Capital U acute accent
            "Ucirc",        // Capital U circumflex accent
            "Uuml",         // Capital U dieresis or umlaut mark;
            "Yacute",       // Capital Y acute accent
            "THORN",        // Capital THORN Icelandic
            "szlig",        // Small sharp s German (sz ligature)
            "agrave",       // Small a grave accent
            "aacute",       // Small a acute accent
            "acirc",        // Small a circumflex accent
            "atilde",       // Small a tilde
            "auml",         // Small a dieresis or umlaut mark
            "aring",        // Small a ring
            "aelig",        // Small ae dipthong (ligature)
            "ccedil",       // Small c cedilla
            "egrave",       // Small e grave accent
            "eacute",       // Small e acute accent
            "ecirc",        // Small e circumflex accent
            "euml",         // Small e dieresis or umlaut mark
            "igrave",       // Small i grave accent
            "iacute",       // Small i acute accent
            "icirc",        // Small i circumflex accent
            "iuml",         // Small i dieresis or umlaut mark
            "eth",          // Small eth Icelandic
            "ntilde",       // Small n tilde
            "ograve",       // Small o grave accent
            "oacute",       // Small o acute accent
            "ocirc",        // Small o circumflex accent
            "otilde",       // Small o tilde
            "ouml",         // Small o dieresis or umlaut mark
            "divide",       // divide
            "oslash",       // Small o slash
            "ugrave",       // Small u grave accent
            "uacute",       // Small u acute accent
            "ucirc",        // Small u circumflex accent
            "uuml",         // Small u dieresis or umlaut mark
            "yacute",       // Small y acute accent
            "thorn",        // Small thorn Icelandic
            "yuml",         // Small y dieresis or umlaut mark
            "OElig",        // latin capital ligature oe, U0152 ISOlat2
            "oelig",        // latin small ligature oe, U0153 ISOlat2
            "Scaron",       // latin capital letter s with caron, U0160 ISOlat2
            "scaron",       // latin small letter s with caron, U0161 ISOlat2
            "Yuml",         // latin capital letter y with diaeresis, U0178 ISOlat2
            "fnof",         // latin small f with hook, =function, =florin, U0192 ISOtech
            "circ",         // modifier letter circumflex accent, U02C6 ISOpub
            "tilde",        // small tilde, U02DC ISOdia
            "Alpha",        // greek capital letter alpha
            "Beta",         // greek capital letter beta
            "Gamma",        // greek capital letter gamma
            "Delta",        // greek capital letter delta
            "Epsilon",      // greek capital letter epsilon
            "Zeta",         // greek capital letter zeta
            "Eta",          // greek capital letter eta
            "Theta",        // greek capital letter theta
            "Iota",         // greek capital letter iota
            "Kappa",        // greek capital letter kappa
            "Lambda",       // greek capital letter lambda
            "Mu",           // greek capital letter mu
            "Nu",           // greek capital letter nu
            "Xi",           // greek capital letter xi
            "Omicron",      // greek capital letter omicron
            "Pi",           // greek capital letter pi
            "Rho",          // greek capital letter rho
            "Sigma",        // greek capital letter sigma
            "Tau",          // greek capital letter tau
            "Upsilon",      // greek capital letter upsilon
            "Phi",          // greek capital letter phi
            "Chi",          // greek capital letter chi
            "Psi",          // greek capital letter psi
            "Omega",        // greek capital letter omega
            "alpha",        // greek small letter alpha
            "beta",         // greek small letter beta
            "gamma",        // greek small letter gamma
            "delta",        // greek small letter delta
            "epsilon",      // greek small letter epsilon
            "zeta",         // greek small letter zeta
            "eta",          // greek small letter eta
            "theta",        // greek small letter theta
            "iota",         // greek small letter iota
            "kappa",        // greek small letter kappa
            "lambda",       // greek small letter lambda
            "mu",           // greek small letter mu
            "nu",           // greek small letter nu
            "xi",           // greek small letter xi
            "omicron",      // greek small letter omicron
            "pi",           // greek small letter pi
            "rho",          // greek small letter rho
            "sigmaf",       // greek small final sigma
            "sigma",        // greek small letter sigma
            "tau",          // greek small letter tau
            "upsilon",      // greek small letter upsilon
            "phi",          // greek small letter phi
            "chi",          // greek small letter chi
            "psi",          // greek small letter psi
            "omega",        // greek small letter omega
            "thetasym",     // greek small letter theta symbol, U03D1 NEW
            "upsih",        // greek upsilon with hook symbol
            "piv",          // greek pi symbol
            "ensp",        // en space, U2002 ISOpub
            "emsp",        // em space, U2003 ISOpub
            "thinsp",      // thin space, U2009 ISOpub
            "zwnj",        // zero width non-joiner, U200C NEW RFC 2070
            "zwj",         // zero width joiner, U200D NEW RFC 2070
            "lrm",         // left-to-right mark, U200E NEW RFC 2070
            "rlm",         // right-to-left mark, U200F NEW RFC 2070
            "ndash",       // en dash, U2013 ISOpub
            "mdash",       // em dash, U2014 ISOpub
            "lsquo",       // left single quotation mark, U2018 ISOnum
            "rsquo",       // right single quotation mark, U2019 ISOnum
            "sbquo",       // single low-9 quotation mark, U201A NEW
            "ldquo",       // left double quotation mark, U201C ISOnum
            "rdquo",       // right double quotation mark, U201D ISOnum
            "bdquo",       // double low-9 quotation mark, U201E NEW
            "dagger",      // dagger, U2020 ISOpub
            "Dagger",      // double dagger, U2021 ISOpub
            "bull",        // bullet, =black small circle, U2022 ISOpub
            "hellip",      // horizontal ellipsis, =three dot leader, U2026 ISOpub
            "permil",      // per mille sign, U2030 ISOtech
            "prime",       // prime, =minutes, =feet, U2032 ISOtech
            "Prime",       // double prime, =seconds, =inches, U2033 ISOtech
            "lsaquo",      // single left-pointing angle quotation mark, U2039 ISO proposed
            "rsaquo",      // single right-pointing angle quotation mark, U203A ISO proposed
            "oline",       // overline, spacing overscore
            "frasl",       // fraction slash
            "image",       // blackletter capital I, =imaginary part, U2111 ISOamso
            "weierp",      // script capital P, =power set, =Weierstrass p, U2118 ISOamso
            "real",        // blackletter capital R, =real part symbol, U211C ISOamso
            "trade",       // trade mark sign, U2122 ISOnum
            "alefsym",     // alef symbol, =first transfinite cardinal, U2135 NEW
            "larr",        // leftwards arrow, U2190 ISOnum
            "uarr",        // upwards arrow, U2191 ISOnum
            "rarr",        // rightwards arrow, U2192 ISOnum
            "darr",        // downwards arrow, U2193 ISOnum
            "harr",        // left right arrow, U2194 ISOamsa
            "crarr",       // downwards arrow with corner leftwards, =carriage return, U21B5 NEW
            "lArr",        // leftwards double arrow, U21D0 ISOtech
            "uArr",        // upwards double arrow, U21D1 ISOamsa
            "rArr",        // rightwards double arrow, U21D2 ISOtech
            "dArr",        // downwards double arrow, U21D3 ISOamsa
            "hArr",        // left right double arrow, U21D4 ISOamsa
            "forall",      // for all, U2200 ISOtech
            "part",        // partial differential, U2202 ISOtech
            "exist",       // there exists, U2203 ISOtech
            "empty",       // empty set, =null set, =diameter, U2205 ISOamso
            "nabla",       // nabla, =backward difference, U2207 ISOtech
            "isin",        // element of, U2208 ISOtech
            "notin",       // not an element of, U2209 ISOtech
            "ni",          // contains as member, U220B ISOtech
            "prod",        // n-ary product, =product sign, U220F ISOamsb
            "sum",         // n-ary sumation, U2211 ISOamsb
            "minus",       // minus sign, U2212 ISOtech
            "lowast",      // asterisk operator, U2217 ISOtech
            "radic",       // square root, =radical sign, U221A ISOtech
            "prop",        // proportional to, U221D ISOtech
            "infin",       // infinity, U221E ISOtech
            "ang",         // angle, U2220 ISOamso
            "and",         // logical and, =wedge, U2227 ISOtech
            "or",          // logical or, =vee, U2228 ISOtech
            "cap",         // intersection, =cap, U2229 ISOtech
            "cup",         // union, =cup, U222A ISOtech
            "int",         // integral, U222B ISOtech
            "there4",      // therefore, U2234 ISOtech
            "sim",         // tilde operator, =varies with, =similar to, U223C ISOtech
            "cong",        // approximately equal to, U2245 ISOtech
            "asymp",       // almost equal to, =asymptotic to, U2248 ISOamsr
            "ne",          // not equal to, U2260 ISOtech
            "equiv",       // identical to, U2261 ISOtech
            "le",          // less-than or equal to, U2264 ISOtech
            "ge",          // greater-than or equal to, U2265 ISOtech
            "sub",         // subset of, U2282 ISOtech
            "sup",         // superset of, U2283 ISOtech
            "nsub",        // not a subset of, U2284 ISOamsn
            "sube",        // subset of or equal to, U2286 ISOtech
            "supe",        // superset of or equal to, U2287 ISOtech
            "oplus",       // circled plus, =direct sum, U2295 ISOamsb
            "otimes",      // circled times, =vector product, U2297 ISOamsb
            "perp",        // up tack, =orthogonal to, =perpendicular, U22A5 ISOtech
            "sdot",        // dot operator, U22C5 ISOamsb
            "lceil",       // left ceiling, =apl upstile, U2308, ISOamsc
            "rceil",       // right ceiling, U2309, ISOamsc
            "lfloor",      // left floor, =apl downstile, U230A, ISOamsc
            "rfloor",      // right floor, U230B, ISOamsc
            "lang",        // left-pointing angle bracket, =bra, U2329 ISOtech
            "rang",        // right-pointing angle bracket, =ket, U232A ISOtech
            "loz",         // lozenge, U25CA ISOpub
            "spades",      // black spade suit, U2660 ISOpub
            "clubs",       // black club suit, =shamrock, U2663 ISOpub
            "hearts",      // black heart suit, =valentine, U2665 ISOpub
            "diams"        // black diamond suit, U2666 ISOpub
        };
    }
}


text:
'use strict';

/**
 * Controller for Account
 **/
accountModule.controller('AccountCtrl', ['Account',  '$scope', '$routeParams', '$http', '$location', '$cookies', 'MessageHandler', 'restURL', function(Account, $scope, $routeParams, $http, $location, $cookies, MessageHandler, restURL) {
	    // edition mode
    $scope.mode = null;

	// list of accounts
    $scope.accounts = [];
	// account to edit
    $scope.account = null;

	// referencies entities
	$scope.items = {};

    /**
     * Load all referencies entities
     */
	$scope.loadAllReferencies = function() {
    };

    /**
     * Refresh accounts list
     */
    $scope.refreshAccountList = function() {
    	try {
			$scope.accounts = [];
        	Account.getAll().then(
				function(success) {
        	        $scope.accounts = success.data;
            	},
	            MessageHandler.manageError);
    	} catch(ex) {
    		MessageHandler.manageException(ex);
    	}
    }
    /**
     * Refresh account
     */
    $scope.refreshAccount = function(uid) {
    	try {
        	$scope.account = null;
	        Account.get(uid).then(
				function(success) {
        	        $scope.account = success.data;
            	},
	            MessageHandler.manageError);
    	  } catch(ex) {
        	MessageHandler.manageException(ex);
    	}
    }

    /**
     * Go to the accounts list page
     */
    $scope.goToAccountList = function() {
        $scope.refreshAccountList();
        $location.path('/account');
    }
    /**
     * Go to the account edit page
     */
    $scope.goToAccount = function(uid) {
        $scope.refreshAccount(uid);
        $location.path('/account/'+uid);
    }

    // Actions

    /**
     * Save account
     */
    $scope.save = function() {
    	try {
			MessageHandler.cleanMessage();
			var save;
			if( $scope.mode === 'create' ) {
        		save = Account.create;
			} else {
				save = Account.update;
			}
			save($scope.account).then(
    	        function(success) {
	                MessageHandler.addSuccess('save ok');
                	$scope.account = success.data;
            	},
        	    MessageHandler.manageError);
    	} catch(ex) {
        	MessageHandler.manageException(ex);
    	}
    };
    /**
     * Delete account
     */
    $scope.delete = function(uid) {
	    try {
			MessageHandler.cleanMessage();
    	    Account.delete(uid).then(
				function(success) {
                	$scope.goToAccountList();
            	},
                MessageHandler.manageError);
        } catch(ex) {
            MessageHandler.manageException(ex);
        }
    };

    // Main
	MessageHandler.cleanMessage();
    if( $location.path().endsWith('/new') ) {
        // Creation page
        $scope.account = {};
        $scope.mode = 'create';
		$scope.loadAllReferencies();
        $scope.bookorderitem = null;
    } else if( $routeParams.uid != null ) {
        // Edit page
		$scope.loadAllReferencies();
		$scope.refreshAccount($routeParams.uid);
    } else {
        // List page
        $scope.refreshAccountList();
    }

}]);


text:
import React from 'react';
import { hot } from 'react-hot-loader';

import AceEditor from '../../../components/AceEditor';

class UpsertTemplatePage extends React.Component {
  render() {
    return (
      <div>
        <AceEditor mode="jsx" theme="github" />
      </div>
    );
  }
}

export default hot(module)(UpsertTemplatePage);


text:
package com.emc.ecs.servicebroker.model;

import java.util.Map;

import static com.emc.ecs.servicebroker.model.Constants.SERVICE_TYPE;

public enum ServiceType {
    NAMESPACE("namespace"),
    BUCKET("bucket");

    public String alias;

    ServiceType(String alias) {
        this.alias = alias;
    }

    public static ServiceType fromSettings(Map<String, Object> settings) {
        String v = (String) settings.get(SERVICE_TYPE);

        for (ServiceType type : values()) {
            if (type.alias.equalsIgnoreCase(v)) {
                return type;
            }
        }

        return ServiceType.valueOf(v);
    }

    public String getAlias() {
        return alias;
    }
}


text:
declare module 'vscode' {

	// https://github.com/microsoft/vscode/issues/84297

	export class TimelineItem {
		/**
		 * A timestamp (in milliseconds since 1 January 1970 00:00:00) for when the timeline item occurred.
		 */
		timestamp: number;

		/**
		 * A human-readable string describing the timeline item.
		 */
		label: string;

		/**
		 * Optional id for the timeline item. It must be unique across all the timeline items provided by this source.
		 *
		 * If not provided, an id is generated using the timeline item's timestamp.
		 */
		id?: string;

		/**
		 * The icon path or {@link ThemeIcon} for the timeline item.
		 */
		iconPath?: Uri | { light: Uri; dark: Uri } | ThemeIcon;

		/**
		 * A human readable string describing less prominent details of the timeline item.
		 */
		description?: string;

		/**
		 * The tooltip text when you hover over the timeline item.
		 */
		tooltip?: string | MarkdownString | undefined;

		/**
		 * The {@link Command} that should be executed when the timeline item is selected.
		 */
		command?: Command;

		/**
		 * Context value of the timeline item. This can be used to contribute specific actions to the item.
		 * For example, a timeline item is given a context value as `commit`. When contributing actions to `timeline/item/context`
		 * using `menus` extension point, you can specify context value for key `timelineItem` in `when` expression like `timelineItem == commit`.
		 * ```
		 *	"contributes": {
		 *		"menus": {
		 *			"timeline/item/context": [
		 *				{
		 *					"command": "extension.copyCommitId",
		 *					"when": "timelineItem == commit"
		 *				}
		 *			]
		 *		}
		 *	}
		 * ```
		 * This will show the `extension.copyCommitId` action only for items where `contextValue` is `commit`.
		 */
		contextValue?: string;

		/**
		 * Accessibility information used when screen reader interacts with this timeline item.
		 */
		accessibilityInformation?: AccessibilityInformation;

		/**
		 * @param label A human-readable string describing the timeline item
		 * @param timestamp A timestamp (in milliseconds since 1 January 1970 00:00:00) for when the timeline item occurred
		 */
		constructor(label: string, timestamp: number);
	}

	export interface TimelineChangeEvent {
		/**
		 * The {@link Uri} of the resource for which the timeline changed.
		 */
		uri: Uri;

		/**
		 * A flag which indicates whether the entire timeline should be reset.
		 */
		reset?: boolean;
	}

	export interface Timeline {
		readonly paging?: {
			/**
			 * A provider-defined cursor specifying the starting point of timeline items which are after the ones returned.
			 * Use `undefined` to signal that there are no more items to be returned.
			 */
			readonly cursor: string | undefined;
		};

		/**
		 * An array of {@link TimelineItem timeline items}.
		 */
		readonly items: readonly TimelineItem[];
	}

	export interface TimelineOptions {
		/**
		 * A provider-defined cursor specifying the starting point of the timeline items that should be returned.
		 */
		cursor?: string;

		/**
		 * An optional maximum number timeline items or the all timeline items newer (inclusive) than the timestamp or id that should be returned.
		 * If `undefined` all timeline items should be returned.
		 */
		limit?: number | { timestamp: number; id?: string };
	}

	export interface TimelineProvider {
		/**
		 * An optional event to signal that the timeline for a source has changed.
		 * To signal that the timeline for all resources (uris) has changed, do not pass any argument or pass `undefined`.
		 */
		onDidChange?: Event<TimelineChangeEvent | undefined>;

		/**
		 * An identifier of the source of the timeline items. This can be used to filter sources.
		 */
		readonly id: string;

		/**
		 * A human-readable string describing the source of the timeline items. This can be used as the display label when filtering sources.
		 */
		readonly label: string;

		/**
		 * Provide {@link TimelineItem timeline items} for a {@link Uri}.
		 *
		 * @param uri The {@link Uri} of the file to provide the timeline for.
		 * @param options A set of options to determine how results should be returned.
		 * @param token A cancellation token.
		 * @return The {@link TimelineResult timeline result} or a thenable that resolves to such. The lack of a result
		 * can be signaled by returning `undefined`, `null`, or an empty array.
		 */
		provideTimeline(uri: Uri, options: TimelineOptions, token: CancellationToken): ProviderResult<Timeline>;
	}

	export namespace workspace {
		/**
		 * Register a timeline provider.
		 *
		 * Multiple providers can be registered. In that case, providers are asked in
		 * parallel and the results are merged. A failing provider (rejected promise or exception) will
		 * not cause a failure of the whole operation.
		 *
		 * @param scheme A scheme or schemes that defines which documents this provider is applicable to. Can be `*` to target all documents.
		 * @param provider A timeline provider.
		 * @return A {@link Disposable} that unregisters this provider when being disposed.
		*/
		export function registerTimelineProvider(scheme: string | string[], provider: TimelineProvider): Disposable;
	}
}


text:
This blog post contains step by step instructions on how to create a virtual network with Azure Resource Manager and Visual Studio
http://www.verboon.info/2016/02/creating-a-virtual-network-using-azure-resource-manager-part-1/

## Creating a Virtual Network Using Azure Resource Manager Part 2
This blog post contains examples on how to create a virtual network with Azure Resource Manager and Powershell
http://www.verboon.info/2016/03/creating-a-virtual-network-using-azure-resource-manager-part-2/

## Content
**Azure Resource Manager Template for new Virtual Network with two subnets**

azuredeploy_virtualnetwork.json

**Azure Resource Manager template parameter file**

azuredeploy_virtualnetwork.parameters.json

**PowerShell command examples**

new-virtualnetwork.ps1

## Other Resources
**Using Azure PowerShell with Azure Resource Manager**

https://github.com/Azure/azure-content/blob/master/articles/powershell-azure-resource-manager.md

**Deploy a Resource Group with Azure Resource Manager template**

https://github.com/Azure/azure-content/blob/master/articles/resource-group-template-deploy.md


text:
package main

import (
	"os"

	"github.com/gtfierro/hod/version"
	"github.com/op/go-logging"
	"github.com/urfave/cli"
)

// logger
var log *logging.Logger

func init() {
	log = logging.MustGetLogger("hod")
	var format = "%{color}%{level} %{shortfile} %{time:Jan 02 15:04:05} %{color:reset} ▶ %{message}"
	var logBackend = logging.NewLogBackend(os.Stderr, "", 0)
	logBackendLeveled := logging.AddModuleLevel(logBackend)
	logging.SetBackend(logBackendLeveled)
	logging.SetFormatter(logging.MustStringFormatter(format))
}

func main() {
	app := cli.NewApp()
	app.Name = "hod"
	app.Version = version.Release
	app.Usage = "BRICK database and query engine"

	app.Commands = []cli.Command{
		{
			Name:   "cli",
			Usage:  "Start hoddb from existing database",
			Action: startCLI,
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "config, c",
					Usage: "Path to hoddb config file",
				},
			},
		},
		{
			Name:   "server",
			Usage:  "Start hoddb server from existing database. Default to HTTP server only, but can do both that and BOSSWAVE",
			Action: startServer,
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "config, c",
					Usage: "Path to hoddb config file",
				},
			},
		},
		{
			Name:   "rebuild",
			Usage:  "Delete old database and rebuild a-new, starting server afterwards",
			Action: rebuildServer,
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "config, c",
					Usage: "Path to hoddb config file",
				},
			},
		},
		{
			Name:   "query",
			Usage:  "Query from command line (non-interactive)",
			Action: doQuery,
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "file, f",
					Usage: "Path to hoddb query file",
				},
				cli.StringFlag{
					Name:  "config, c",
					Usage: "Path to hoddb config file",
				},
				cli.StringFlag{
					Name:  "query, q",
					Usage: "Query string",
				},
				cli.BoolFlag{
					Name:  "prefixes, p",
					Usage: "If true, abbreviate all namespaces. Else, just print the full URI",
				},
			},
		},
		{
			Name:   "benchload",
			Usage:  "Benchmark loading a turtle file",
			Action: benchLoad,
		},
		{
			Name:   "dump",
			Usage:  "Dump contents of turtle file",
			Action: dump,
		},
		{
			Name:   "viewclass",
			Usage:  "PDF visualization of class structure of file",
			Action: classGraph,
		},
		{
			Name:   "dumpgraph",
			Usage:  "PDF visualization of TTL file. WARNING this can get really big",
			Action: dumpGraph,
		},
		{
			Name:   "ttlstat",
			Usage:  "Outputs statistics on the provided TTL file. Loads all file provided as arguments",
			Action: ttlStat,
		},
		{
			Name:   "check",
			Usage:  "Check access to MDAL on behalf of some key",
			Action: doCheck,
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:   "agent,a",
					Value:  "127.0.0.1:28589",
					Usage:  "Local BOSSWAVE Agent",
					EnvVar: "BW2_AGENT",
				},
				cli.StringFlag{
					Name:   "entity,e",
					Value:  "",
					Usage:  "The entity to use",
					EnvVar: "BW2_DEFAULT_ENTITY",
				},
				cli.StringFlag{
					Name:  "key, k",
					Usage: "The key or alias to check",
				},
				cli.StringFlag{
					Name:  "uri, u",
					Usage: "The base URI of MDAL",
				},
			},
		},
		{
			Name:   "grant",
			Usage:  "Grant access to MDAL to some key",
			Action: doGrant,
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:   "agent,a",
					Value:  "127.0.0.1:28589",
					Usage:  "Local BOSSWAVE Agent",
					EnvVar: "BW2_AGENT",
				},
				cli.StringFlag{
					Name:   "entity,e",
					Value:  "",
					Usage:  "The entity to use",
					EnvVar: "BW2_DEFAULT_ENTITY",
				},
				cli.StringFlag{
					Name:   "bankroll, b",
					Value:  "",
					Usage:  "The entity to use for bankrolling",
					EnvVar: "BW2_DEFAULT_BANKROLL",
				},
				cli.StringFlag{
					Name:  "expiry",
					Usage: "Set the expiry on access to MDAL measured from now e.g. 3d7h20m",
				},
				cli.IntFlag{
					Name:  "ttl",
					Usage: "Set the TTL",
					Value: 0,
				},
				cli.StringFlag{
					Name:  "key, k",
					Usage: "The key or alias to check",
				},
				cli.StringFlag{
					Name:  "uri, u",
					Usage: "The base URI of MDAL",
				},
			},
		},
	}
	app.Run(os.Args)
}