text:
#ifndef __VCGLIB_IMPORTERDAE
#define __VCGLIB_IMPORTERDAE

//importer for collada's files

#include <wrap/dae/util_dae.h>
#include <wrap/dae/poly_triangulator.h>

// uncomment one of the following line to enable the Verbose debugging for the parsing
//#define QDEBUG if(1) ; else {assert(0);}
#define QDEBUG qDebug

namespace vcg {
namespace tri {
namespace io {
	template<typename OpenMeshType>
	class ImporterDAE : public UtilDAE
	{
  public:
    class ColladaFace;
    class ColladaVertex;

    class ColladaTypes: public vcg::UsedTypes < vcg::Use<ColladaVertex>::template AsVertexType,
																								vcg::Use<ColladaFace  >::template AsFaceType >{};

    class ColladaVertex  : public vcg::Vertex< ColladaTypes,
      vcg::vertex::Coord3f,           /* 12b */
      vcg::vertex::BitFlags,          /*  4b */
      vcg::vertex::Normal3f,          /* 12b */
      vcg::vertex::Color4b           /*  4b */
      > {};

    class ColladaFace    : public vcg::Face<  ColladaTypes,
          vcg::face::VertexRef,            /*12b */
          vcg::face::BitFlags,             /* 4b */
          vcg::face::Normal3f,             /*12b */
          vcg::face::Color4b,           /* 0b */
          vcg::face::WedgeTexCoord2f     /* 0b */
        > {};

    class ColladaMesh    : public vcg::tri::TriMesh< std::vector<ColladaVertex>, std::vector<ColladaFace> > {};

	private:

		static int WedgeNormalAttribute(ColladaMesh& m,const QStringList face,const QStringList wn,const QDomNode wnsrc,const int meshfaceind,const int faceind,const int component)
		{
			int indnm = -1;
			if (!wnsrc.isNull())
			{
				indnm = face.at(faceind).toInt();
				assert(indnm * 3 < wn.size());
				m.face[meshfaceind].WN(component) = vcg::Point3f(wn.at(indnm * 3).toFloat(),wn.at(indnm * 3 + 1).toFloat(),wn.at(indnm * 3 + 2).toFloat());
			}
			return indnm;
		}

		static int WedgeTextureAttribute(ColladaMesh& m,const QStringList face,int ind_txt,const QStringList wt,const QDomNode wtsrc,const int meshfaceind,const int faceind,const int component,const int stride = 2)
		{
			int indtx = -1;
			if (!wtsrc.isNull())
			{
				indtx = face.at(faceind).toInt();
				//int num = wt.size();
				assert(indtx * stride < wt.size());
				m.face[meshfaceind].WT(component) = vcg::TexCoord2<float>();
				m.face[meshfaceind].WT(component).U() = wt.at(indtx * stride).toFloat();
				m.face[meshfaceind].WT(component).V() = wt.at(indtx * stride + 1).toFloat();

				m.face[meshfaceind].WT(component).N() = ind_txt;

			}
			return indtx;
		}

		// this one is used for the polylist nodes
		static int WedgeTextureAttribute(typename ColladaMesh::FaceType::TexCoordType & WT, const QStringList faceIndexList, int ind_txt, const QStringList wt, const QDomNode wtsrc,const int faceind,const int stride = 2)
		{
			int indtx = -1;
			if (!wtsrc.isNull())
			{
				indtx = faceIndexList.at(faceind).toInt();
				//int num = wt.size();
				assert(indtx * stride < wt.size());
				WT = vcg::TexCoord2<float>();
				WT.U() = wt.at(indtx * stride).toFloat();
				WT.V() = wt.at(indtx * stride + 1).toFloat();
				WT.N() = ind_txt;
			}
			return indtx;
		}

		static int VertexColorAttribute(ColladaMesh& m,const QStringList face,const QStringList wc,const QDomNode wcsrc,const int faceind, const int vertind,const int colorcomponent)
		{
			int indcl = -1;
			if (!wcsrc.isNull())
			{
				indcl = face.at(faceind).toInt();
				assert((colorcomponent == 4) || (colorcomponent == 3));
				assert(indcl * colorcomponent < wc.size());
				vcg::Color4b c;
				if (colorcomponent == 3)
					c[3] = 255;
				for(unsigned int ii = 0;ii < colorcomponent;++ii)
					c[ii] = (unsigned char)(wc.at(indcl * colorcomponent + ii).toFloat()*255.0);
				m.vert[vertind].C() = c;
			}
			return indcl;
		}

		static void FindStandardWedgeAttributes(WedgeAttribute& wed,const QDomNode nd,const QDomDocument doc)
		{
			wed.wnsrc = findNodeBySpecificAttributeValue(nd,"input","semantic","NORMAL");
			wed.offnm = findStringListAttribute(wed.wn,wed.wnsrc,nd,doc,"NORMAL");

			wed.wtsrc = findNodeBySpecificAttributeValue(nd,"input","semantic","TEXCOORD");
			if (!wed.wtsrc.isNull())
			{
				QDomNode src = attributeSourcePerSimplex(nd,doc,"TEXCOORD");
				if (isThereTag(src,"accessor"))
				{
					QDomNodeList wedatts = src.toElement().elementsByTagName("accessor");
					wed.stridetx = wedatts.at(0).toElement().attribute("stride").toInt();
				}
				else
					wed.stridetx = 2;
			}
			//else
			//	wed.stridetx = 2;

			wed.offtx = findStringListAttribute(wed.wt,wed.wtsrc,nd,doc,"TEXCOORD");

			wed.wcsrc = findNodeBySpecificAttributeValue(nd,"input","semantic","COLOR");
			if (!wed.wcsrc.isNull())
			{
				QDomNode src = attributeSourcePerSimplex(nd,doc,"COLOR");
				if (isThereTag(src,"accessor"))
				{
					QDomNodeList wedatts = src.toElement().elementsByTagName("accessor");
					wed.stridecl = wedatts.at(0).toElement().attribute("stride").toInt();
				}
				else
					wed.stridecl = 3;
			}
			/*else
				wed.stridecl = 3;*/
			wed.offcl = findStringListAttribute(wed.wc,wed.wcsrc,nd,doc,"COLOR");
		}

        static DAEError LoadPolygonalMesh(QDomNodeList& polypatch,ColladaMesh& m,const size_t offset,InfoDAE & info)
		{
			return E_NOERROR;
		}

        static DAEError	LoadPolygonalListMesh(QDomNodeList& polylist,ColladaMesh& m,const size_t offset,InfoDAE& info,QMap<QString,QString> &materialBinding)
		{
			if(polylist.isEmpty()) return E_NOERROR;
			QDEBUG("****** LoadPolygonalListMesh (initial mesh size %i %i)",m.vert.size(),m.fn);
			for(int tript = 0; tript < polylist.size();++tript)
			{
				QString materialId =  polylist.at(tript).toElement().attribute(QString("material"));
				QDEBUG("******    material id '%s' -> '%s'",qPrintable(materialId),qPrintable(materialBinding[materialId]));

				QString textureFilename;
                QDomNode img_node = textureFinder(materialBinding[materialId],textureFilename,*(info.doc));
				if(img_node.isNull())
				{
					QDEBUG("******   but we were not able to find the corresponding image node");
				}

				int ind_txt = -1;
				if (!img_node.isNull())
				{
                    if(info.textureIdMap.contains(textureFilename))
                         ind_txt=info.textureIdMap[textureFilename];
					else
					{
						QDEBUG("Found use of Texture %s, adding it to texutres",qPrintable(textureFilename));
                        info.textureIdMap[textureFilename]=m.textures.size();
						m.textures.push_back(qPrintable(textureFilename));
                        ind_txt=info.textureIdMap[textureFilename];
					}
				}
				// number of the attributes associated to each vertex of a face (vert, normal, tex etc)
				int faceAttributeNum = polylist.at(tript).toElement().elementsByTagName("input").size();

				// the list of indexes composing the size of each polygon.
				// The size of this list is the number of the polygons.
				QStringList faceSizeList;
				valueStringList(faceSizeList,polylist.at(tript),"vcount");

				// The long list of indexes composing the various polygons.
				// for each polygon there are numvert*numattrib indexes.
				QStringList faceIndexList;
				valueStringList(faceIndexList,polylist.at(tript),"p");

				//int offsetface = (int)m.face.size();
				if (faceIndexList.size() != 0 && faceSizeList.size() != 0 )
				{
					WedgeAttribute wa;
                    FindStandardWedgeAttributes(wa,polylist.at(tript),*(info.doc));
					QDEBUG("*******                 Start Reading faces. Attributes Offsets: offtx %i - offnm %i - offcl %i",wa.offtx,wa.offnm,wa.offcl);

          int faceIndexCnt=0;
					int jj = 0;
					for(int ff = 0; ff < (int) faceSizeList.size();++ff) // for each polygon
					{
						int curFaceVertNum = faceSizeList.at(ff).toInt();

						MyPolygon<typename ColladaMesh::VertexType>  polyTemp(curFaceVertNum);
						for(int tt = 0;tt < curFaceVertNum ;++tt)  // for each vertex of the polygon
						{
							int indvt = faceIndexList.at(faceIndexCnt).toInt();
							if(faceSizeList.size()<100) QDEBUG("*******                 Reading face[%3i].V(%i) = %4i  (%i-th of the index list) (face has %i vertices)",ff,tt,indvt,faceIndexCnt,curFaceVertNum);
							assert(indvt + offset < m.vert.size());
							polyTemp._pv[tt] = &(m.vert[indvt + offset]);
							faceIndexCnt +=faceAttributeNum;

							WedgeTextureAttribute(polyTemp._txc[tt],faceIndexList,ind_txt, wa.wt ,wa.wtsrc, jj + wa.offtx,wa.stridetx);

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

							if(tri::HasPerWedgeNormal(m)) WedgeNormalAttribute(m,face,wa.wn,wa.wnsrc,ff,jj + wa.offnm,tt);
							if(tri::HasPerWedgeColor(m)) 	WedgeColorAttribute(m,face,wa.wc,wa.wcsrc,ff,jj + wa.offcl,tt);

							if(tri::HasPerWedgeTexCoord(m) && ind_txt != -1)
							{
															WedgeTextureAttribute(m,face,ind_txt,wa.wt,wa.wtsrc,ff,jj + wa.offtx,tt,wa.stride);
							}
									****************/

							jj += faceAttributeNum;
						}

						AddPolygonToMesh(polyTemp,m);
					}
				}

			}
			QDEBUG("****** LoadPolygonalListMesh (final  mesh size vn %i vertsize %i - fn %i facesize %i)",m.vn,m.vert.size(),m.fn,m.face.size());
			return E_NOERROR;
		}

    static DAEError AddPolygonToMesh(MyPolygon<typename ColladaMesh::VertexType>  &polyTemp, ColladaMesh& m)
		{
			int vertNum=polyTemp._pv.size();
			int triNum= vertNum -2;
			typename ColladaMesh::FaceIterator fp=vcg::tri::Allocator<ColladaMesh>::AddFaces(m,triNum);
			// Very simple fan triangulation of the polygon.
			for(int i=0;i<triNum;++i)
			{
				assert(fp!=m.face.end());
				(*fp).V(0)=polyTemp._pv[0];
				(*fp).WT(0)=polyTemp._txc[0];

				(*fp).V(1) =polyTemp._pv [i+1];
				(*fp).WT(1)=polyTemp._txc[i+1];

				(*fp).V(2) =polyTemp._pv[i+2];
				(*fp).WT(2)=polyTemp._txc[i+2];

				++fp;
			}
			assert(fp==m.face.end());
			return E_NOERROR;
		}

        static DAEError	OldLoadPolygonalListMesh(QDomNodeList& polylist,ColladaMesh& m,const size_t offset,InfoDAE& info)
		{
			typedef PolygonalMesh< MyPolygon<typename ColladaMesh::VertexType> > PolyMesh;
			PolyMesh pm;

			//copying vertices
			for(typename ColladaMesh::VertexIterator itv = m.vert.begin();itv != m.vert.end();++itv)
			{
				vcg::Point3f p(itv->P().X(),itv->P().Y(),itv->P().Z());
				typename PolyMesh::VertexType v;
				v.P() = p;
				pm.vert.push_back(v);
			}

			int polylist_size = polylist.size();
			for(int pl = 0; pl < polylist_size;++pl)
			{
				QString mat =  polylist.at(pl).toElement().attribute(QString("material"));
				QString textureFilename;
                QDomNode txt_node = textureFinder(mat,textureFilename,*(info.doc));
				int ind_txt = -1;
				if (!txt_node.isNull())
                    ind_txt = indexTextureByImgNode(*(info.doc),txt_node);

				//PolyMesh::PERWEDGEATTRIBUTETYPE att = PolyMesh::NONE;
				WedgeAttribute wa;
                FindStandardWedgeAttributes(wa,polylist.at(pl),*(info.doc));
				QStringList vertcount;
				valueStringList(vertcount,polylist.at(pl),"vcount");
				int indforpol = findOffSetForASingleSimplex(polylist.at(pl));
				int offpols = 0;
				int npolig = vertcount.size();
				QStringList polyind;
				valueStringList(polyind,polylist.at(pl),"p");
				for(int ii = 0;ii < npolig;++ii)
				{
					int nvert = vertcount.at(ii).toInt();
					typename PolyMesh::FaceType p(nvert);

					for(int iv = 0;iv < nvert;++iv)
					{
						int index = offset + polyind.at(offpols + iv * indforpol).toInt();
						p._pv[iv] = &(pm.vert[index]);
						int nmindex = -1;

						if (!wa.wnsrc.isNull())
							nmindex = offset + polyind.at(offpols + iv * indforpol + wa.offnm).toInt();

						int txindex = -1;
						if (!wa.wtsrc.isNull())
						{
							txindex = offset + polyind.at(offpols + iv * indforpol + wa.offtx).toInt();
							/*p._txc[iv].U() = wa.wt.at(txindex * 2).toFloat();
							p._txc[iv].V() = wa.wt.at(txindex * 2 + 1).toFloat();
							p._txc[iv].N() = ind_txt;*/
						}
					}
					pm._pols.push_back(p);
					offpols += nvert * indforpol;
				}
			}
			pm.triangulate(m);
			return E_NOERROR;
		}
		/*
		 Called to load into a given mesh
		 */
        static DAEError LoadTriangularMesh(QDomNodeList& triNodeList, ColladaMesh& m, const size_t offset, InfoDAE& info,QMap<QString,QString> &materialBinding)
		{
			if(triNodeList.isEmpty()) return E_NOERROR;
			QDEBUG("****** LoadTriangularMesh (initial mesh size %i %i)",m.vn,m.fn);
			for(int tript = 0; tript < triNodeList.size();++tript)
			{
				QString materialId =  triNodeList.at(tript).toElement().attribute(QString("material"));
				QDEBUG("******    material id '%s' -> '%s'",qPrintable(materialId),qPrintable(materialBinding[materialId]));

				QString textureFilename;
                QDomNode img_node = textureFinder(materialBinding[materialId],textureFilename,*(info.doc));
				if(img_node.isNull())
				{
					QDEBUG("******   but we were not able to find the corresponding image node");
				}

				int ind_txt = -1;
				if (!img_node.isNull())
				{
                    if(info.textureIdMap.contains(textureFilename))
                         ind_txt=info.textureIdMap[textureFilename];
					else
					{
						QDEBUG("Found use of Texture %s, adding it to texutres",qPrintable(textureFilename));
                        info.textureIdMap[textureFilename]=m.textures.size();
						m.textures.push_back(qPrintable(textureFilename));
                        ind_txt=info.textureIdMap[textureFilename];
					}
                //	ind_txt = indexTextureByImgNode(*(info.doc),txt_node);
				}
				int faceAttributeNum = triNodeList.at(tript).toElement().elementsByTagName("input").size();

				QStringList face;
				valueStringList(face,triNodeList.at(tript),"p");
				int offsetface = (int)m.face.size();
				if (face.size() != 0)
				{
					vcg::tri::Allocator<ColladaMesh>::AddFaces(m,face.size() / (faceAttributeNum * 3));
					WedgeAttribute wa;
                    FindStandardWedgeAttributes(wa,triNodeList.at(tript),*(info.doc));

					int jj = 0;
					for(int ff = offsetface;ff < (int) m.face.size();++ff)
					{

						for(unsigned int tt = 0;tt < 3;++tt)
						{
							int indvt = face.at(jj).toInt();
							assert(indvt + offset < m.vert.size());
							m.face[ff].V(tt) = &(m.vert[indvt + offset]);

							if(tri::HasPerWedgeNormal(m))
								WedgeNormalAttribute(m,face,wa.wn,wa.wnsrc,ff,jj + wa.offnm,tt);
							if(tri::HasPerVertexColor(m))
							{
								VertexColorAttribute(m,face,wa.wc,wa.wcsrc,jj + wa.offcl,indvt + offset,wa.stridecl);
							}

							if(tri::HasPerWedgeTexCoord(m) && ind_txt != -1)
							{
								WedgeTextureAttribute(m,face,ind_txt,wa.wt,wa.wtsrc,ff,jj + wa.offtx,tt,wa.stridetx);
							}

							jj += faceAttributeNum;
						}
						if( ! ( (m.face[ff].V(0) != m.face[ff].V(1)) &&
										(m.face[ff].V(0) != m.face[ff].V(2)) &&
										(m.face[ff].V(1) != m.face[ff].V(2)) )  )
										QDEBUG("********* WARNING face %i, (%i %i %i) is a DEGENERATE FACE!",ff, m.face[ff].V(0) - &m.vert.front(), m.face[ff].V(1) - &m.vert.front(), m.face[ff].V(2) - &m.vert.front());

					}
				}
			}
			QDEBUG("****** LoadTriangularMesh (final  mesh size %i %i - %i %i)",m.vn,m.vert.size(),m.fn,m.face.size());
			return E_NOERROR;
		}

        static int LoadControllerMesh(ColladaMesh& m, InfoDAE& info, const QDomElement& geo,QMap<QString, QString> materialBindingMap, CallBackPos *cb=0)
		{
			(void)cb;

			assert(geo.tagName() == "controller");
			QDomNodeList skinList = geo.toElement().elementsByTagName("skin");
			if(skinList.size()!=1) return E_CANTOPEN;
			QDomElement skinNode = skinList.at(0).toElement();

			QString geomNode_url;
			referenceToANodeAttribute(skinNode,"source",geomNode_url);
			QDEBUG("Found a controller referencing a skin with url '%s'", qPrintable(geomNode_url));
            QDomNode refNode = findNodeBySpecificAttributeValue(*(info.doc),"geometry","id",geomNode_url);

			QDomNodeList bindingNodes = skinNode.toElement().elementsByTagName("bind_material");
			if(	bindingNodes.size()>0) {
				QDEBUG("**   skin node of a controller has a material binding");
				GenerateMaterialBinding(skinNode,materialBindingMap);
			}
			return LoadGeometry(m, info, refNode.toElement(),materialBindingMap);
		}

		/* before instancing a geometry you can make a binding that allow you to substitute next material names with other names.
		this is very useful for instancing the same geometry with different materials. therefore when you encounter a material name in a mesh, this name can be a 'symbol' that you have to bind.
		*/
		static bool GenerateMaterialBinding(QDomNode instanceGeomNode, QMap<QString,QString> &binding)
		{
			QDomNodeList instanceMaterialList=instanceGeomNode.toElement().elementsByTagName("instance_material");
			QDEBUG("++++ Found %i instance_material binding",instanceMaterialList.size() );
			for(int i=0;i<instanceMaterialList.size();++i)
			{
				QString symbol = instanceMaterialList.at(i).toElement().attribute("symbol");
				QString target = instanceMaterialList.at(i).toElement().attribute("target");
				binding[symbol]=target;
				QDEBUG("++++++ %s -> %s",qPrintable(symbol),qPrintable(target));
			}
			return true;
		}

    /*
		 Basic function that get in input a node <geometry> with a map from material names to texture names.
		 this map is necessary because when using a geometry when it is instanced its material can be bind with different names.
		 if the map fails you should directly search in the material library.

		 */

        static int LoadGeometry(ColladaMesh& m, InfoDAE& info, const QDomElement& geo, QMap<QString,QString> &materialBinding, CallBackPos *cb=0)
		{
			assert(geo.tagName() == "geometry");
			if (!isThereTag(geo,"mesh")) return E_NOMESH;

            if ((cb !=NULL) && (((info.numvert + info.numface)%100)==0) && !(*cb)((100*(info.numvert + info.numface))/(info.numvert + info.numface), "Vertex Loading"))
					return E_CANTOPEN;
			QDEBUG("**** Loading a Geometry Mesh **** (initial mesh size %i %i)",m.vn,m.fn);
			QDomNodeList vertices = geo.toElement().elementsByTagName("vertices");
			if (vertices.size() != 1) return E_INCOMPATIBLECOLLADA141FORMAT;
			QDomElement vertNode = vertices.at(0).toElement();

            QDomNode positionNode = attributeSourcePerSimplex(vertNode,*(info.doc),"POSITION");
			if (positionNode.isNull()) return E_NOVERTEXPOSITION;

			QStringList geosrcposarr;
			valueStringList(geosrcposarr, positionNode, "float_array");

			int geosrcposarr_size = geosrcposarr.size();
			if ((geosrcposarr_size % 3) != 0)
				return E_CANTOPEN;
			int nvert = geosrcposarr_size / 3;
			size_t offset = m.vert.size();
			if (geosrcposarr_size != 0)
			{
					vcg::tri::Allocator<ColladaMesh>::AddVertices(m,nvert);

                    QDomNode srcnodenorm = attributeSourcePerSimplex(vertices.at(0),*(info.doc),"NORMAL");
					QStringList geosrcvertnorm;
					if (!srcnodenorm.isNull())
						valueStringList(geosrcvertnorm,srcnodenorm,"float_array");

                    QDomNode srcnodetext = attributeSourcePerSimplex(vertices.at(0),*(info.doc),"TEXCOORD");
					QStringList geosrcverttext;
					if (!srcnodetext.isNull())
						valueStringList(geosrcverttext,srcnodetext,"float_array");

                    QDomNode srcnodecolor = attributeSourcePerSimplex(vertices.at(0),*(info.doc),"COLOR");
					QDomNodeList accesslist = srcnodecolor.toElement().elementsByTagName("accessor");

					QStringList geosrcvertcol;
					if (!srcnodecolor.isNull())
						valueStringList(geosrcvertcol,srcnodecolor,"float_array");

					int ii = 0;
					for(size_t vv = offset;vv < m.vert.size();++vv)
					{
						Point3f positionCoord(geosrcposarr[ii * 3].toFloat(),geosrcposarr[ii * 3 + 1].toFloat(),geosrcposarr[ii * 3 + 2].toFloat());
						m.vert[vv].P() = positionCoord;

						if (!srcnodenorm.isNull())
						{
							Point3f normalCoord(geosrcvertnorm[ii * 3].toFloat(),
																	geosrcvertnorm[ii * 3 + 1].toFloat(),
																	geosrcvertnorm[ii * 3 + 2].toFloat());
							normalCoord.Normalize();
							m.vert[vv].N() = normalCoord;
						}

						if (!srcnodecolor.isNull())
						{
							if (accesslist.size() > 0)
							{
								//component per color...obviously we assume they are RGB or RGBA if ARGB you get fancy effects....
								if (accesslist.at(0).childNodes().size() == 4)
									m.vert[vv].C() = vcg::Color4b(geosrcvertcol[ii * 4].toFloat()*255.0,geosrcvertcol[ii * 4 + 1].toFloat()*255.0,geosrcvertcol[ii * 4 + 2].toFloat()*255.0,geosrcvertcol[ii * 4 + 3].toFloat()*255.0);
								else
									if (accesslist.at(0).childNodes().size() == 3)
										m.vert[vv].C() = vcg::Color4b(geosrcvertcol[ii * 3].toFloat()*255.0,geosrcvertcol[ii * 3 + 1].toFloat()*255.0,geosrcvertcol[ii * 3 + 2].toFloat()*255.0,255.0);
							}
						}

						if (!srcnodetext.isNull())
						{

							assert((ii * 2 < geosrcverttext.size()) && (ii * 2 + 1 < geosrcverttext.size()));
							m.vert[vv].T() = vcg::TexCoord2<float>();
							m.vert[vv].T().u() = geosrcverttext[ii * 2].toFloat();
							m.vert[vv].T().v() = geosrcverttext[ii * 2 + 1].toFloat();
						}
						++ii;
					}

					QDomNodeList tripatch = geo.toElement().elementsByTagName("triangles");
					QDomNodeList polypatch = geo.toElement().elementsByTagName("polygons");
					QDomNodeList polylist = geo.toElement().elementsByTagName("polylist");
					QStringList vertcount;
					valueStringList(vertcount,polylist.at(0),"vcount");
					int isTri=true;
					for (int i=0; i<vertcount.size(); i++)
					{
						if (vertcount[i]!="3")
						{
							isTri=false;
							break;
						}

					}
					if (isTri && tripatch.isEmpty())
						tripatch=polylist;
					if (tripatch.isEmpty()  && polypatch.isEmpty() && polylist.isEmpty())
						return E_NOPOLYGONALMESH;

					DAEError err = E_NOERROR;
					err = LoadTriangularMesh(tripatch,m,offset,info,materialBinding);
					//err = LoadPolygonalMesh(polypatch,m,offset,info);
			//					err = OldLoadPolygonalListMesh(polylist,m,offset,info);
                    err = LoadPolygonalListMesh(polylist,m,offset,info,materialBinding);
					if (err != E_NOERROR)
						return err;
				}
			QDEBUG("**** Loading a Geometry Mesh **** (final   mesh size %i %i - %i %i)",m.vn,m.vert.size(),m.fn,m.face.size());
			return E_NOERROR;
		}

		static void GetTexCoord(const QDomDocument& doc, QStringList &texturefile)
		{
			QDomNodeList txlst = doc.elementsByTagName("library_images");
			for(int img = 0;img < txlst.at(0).childNodes().size();++img)
			{
				QDomNodeList nlst = txlst.at(0).childNodes().at(img).toElement().elementsByTagName("init_from");
				if (nlst.size() > 0)
				{
                                    texturefile.push_back( nlst.at(0).firstChild().nodeValue());
				}
			}
		}

	// This recursive function add to a mesh the subtree starting from the passed node.
	// When you start from a visual_scene, you can find nodes.
  // nodes can be directly instanced or referred from the node library.

		static void AddNodeToMesh(QDomElement node,
															ColladaMesh& m, Matrix44f curTr,
                                                            InfoDAE& info)
		{
				QDEBUG("Starting processing <node> with id %s",qPrintable(node.attribute("id")));

				curTr = curTr * getTransfMatrixFromNode(node);

				QDomNodeList geomNodeList = node.elementsByTagName("instance_geometry");
				for(int ch = 0;ch < geomNodeList.size();++ch)
				{
					QDomElement instGeomNode= geomNodeList.at(ch).toElement();
					if(instGeomNode.parentNode()==node) // process only direct child
					{
						QDEBUG("** instance_geometry with url %s (intial mesh size %i %i T = %i)",qPrintable(instGeomNode.attribute("url")),m.vn,m.fn,m.textures.size());
						//assert(m.textures.size()>0 == HasPerWedgeTexCoord(m));
						QString geomNode_url;
						referenceToANodeAttribute(instGeomNode,"url",geomNode_url);
                        QDomNode refNode = findNodeBySpecificAttributeValue(*(info.doc),"geometry","id",geomNode_url);
						QDomNodeList bindingNodes = instGeomNode.toElement().elementsByTagName("bind_material");
						QMap<QString,QString> materialBindingMap;
						if(	bindingNodes.size()>0) {
							QDEBUG("**    instance_geometry has a material binding");
							GenerateMaterialBinding(instGeomNode,materialBindingMap);
						}

						ColladaMesh newMesh;
//						newMesh.face.EnableWedgeTex();
						LoadGeometry(newMesh, info, refNode.toElement(),materialBindingMap);
						tri::UpdatePosition<ColladaMesh>::Matrix(newMesh,curTr);
						tri::Append<ColladaMesh,ColladaMesh>::Mesh(m,newMesh);
						QDEBUG("** instance_geometry with url %s (final mesh size %i %i - %i %i)",qPrintable(instGeomNode.attribute("url")),m.vn,m.vert.size(),m.fn,m.face.size());
					}
				}

				QDomNodeList controllerNodeList = node.elementsByTagName("instance_controller");
				for(int ch = 0;ch < controllerNodeList.size();++ch)
				{
					QDomElement instContrNode= controllerNodeList.at(ch).toElement();
					if(instContrNode.parentNode()==node) // process only direct child
					{
						QDEBUG("Found a instance_controller with url %s",qPrintable(instContrNode.attribute("url")));

						QString controllerNode_url;
						referenceToANodeAttribute(instContrNode,"url",controllerNode_url);
						QDEBUG("Found a instance_controller with url '%s'", qPrintable(controllerNode_url));
                        QDomNode refNode = findNodeBySpecificAttributeValue(*(info.doc),"controller","id",controllerNode_url);

						QDomNodeList bindingNodes = instContrNode.toElement().elementsByTagName("bind_material");
						QMap<QString, QString> materialBindingMap;
							if(	bindingNodes.size()>0) {
							QDEBUG("**   instance_controller node of has a material binding");
							GenerateMaterialBinding(instContrNode,materialBindingMap);
						}

						ColladaMesh newMesh;
						LoadControllerMesh(newMesh, info, refNode.toElement(),materialBindingMap);
						tri::UpdatePosition<ColladaMesh>::Matrix(newMesh,curTr);
						tri::Append<ColladaMesh,ColladaMesh>::Mesh(m,newMesh);
					}
				}

				QDomNodeList nodeNodeList = node.elementsByTagName("node");
				for(int ch = 0;ch < nodeNodeList.size();++ch)
				{
					if(nodeNodeList.at(ch).parentNode()==node) // process only direct child
							AddNodeToMesh(nodeNodeList.at(ch).toElement(), m,curTr, info);
				}

				QDomNodeList instanceNodeList = node.elementsByTagName("instance_node");
				for(int ch = 0;ch < instanceNodeList.size();++ch)
				{
					if(instanceNodeList.at(ch).parentNode()==node) // process only direct child
					{
						QDomElement instanceNode =  instanceNodeList.at(ch).toElement();
						QString node_url;
						referenceToANodeAttribute(instanceNode,"url",node_url);
						QDEBUG("Found a instance_node with url '%s'", qPrintable(node_url));
                        QDomNode refNode = findNodeBySpecificAttributeValue(*(info.doc),"node","id",node_url);
						if(refNode.isNull())
							QDEBUG("findNodeBySpecificAttributeValue returned a null node for %s",qPrintable(node_url));

						AddNodeToMesh(refNode.toElement(), m,curTr, info);
					}
				}
		}

// Retrieve the transformation matrix that is defined in the childs of a node.
// used during the recursive descent.
static Matrix44f getTransfMatrixFromNode(const QDomElement parentNode)
{
	QDEBUG("getTrans form node with tag %s",qPrintable(parentNode.tagName()));
	assert(parentNode.tagName() == "node");

	std::vector<QDomNode> rotationList;
	QDomNode matrixNode;
	QDomNode translationNode;
	for(int ch = 0;ch < parentNode.childNodes().size();++ch)
		{
			if (parentNode.childNodes().at(ch).nodeName() == "rotate")
				rotationList.push_back(parentNode.childNodes().at(ch));
			if (parentNode.childNodes().at(ch).nodeName() == "translate")
				translationNode = parentNode.childNodes().at(ch);
			if (parentNode.childNodes().at(ch).nodeName() == "matrix")
				matrixNode = parentNode.childNodes().at(ch);
		}

		Matrix44f rotM;		   rotM.SetIdentity();
		Matrix44f transM; transM.SetIdentity();

		if (!translationNode.isNull()) ParseTranslation(transM,translationNode);
		if (!rotationList.empty()) ParseRotationMatrix(rotM,rotationList);
		if (!matrixNode.isNull())
		{
			ParseMatrixNode(transM,matrixNode);
		  return transM;
		}
	  return transM*rotM;
}

	public:

		//merge all meshes in the collada's file in the templeted mesh m
		//I assume the mesh

        static int Open(OpenMeshType& m,const char* filename, InfoDAE& info, CallBackPos *cb=0)
		{
			(void)cb;

			QDEBUG("----- Starting the processing of %s ------",filename);
            //AdditionalInfoDAE& inf = new AdditionalInfoDAE();
            //info = new InfoDAE();

			QDomDocument* doc = new QDomDocument(filename);
            info.doc = doc;
			QFile file(filename);
			if (!file.open(QIODevice::ReadOnly))
				return E_CANTOPEN;
			if (!doc->setContent(&file))
			{
				file.close();
				return E_CANTOPEN;
			}
			file.close();

            //GetTexture(*(info.doc),inf);

//			GenerateMaterialToTextureMap(info);
			//scene->instance_visual_scene
            QDomNodeList scenes = info.doc->elementsByTagName("scene");
			int scn_size = scenes.size();
			if (scn_size == 0)
				return E_NO3DSCENE;
			QDEBUG("File Contains %i Scenes",scenes.size());
			int problem = E_NOERROR;
			//bool found_a_mesh = false;
			//Is there geometry in the file?
			//bool geoinst_found = false;

			// The main loading loop
			// for each scene in COLLADA FILE
			/*
			Some notes on collada structure.
			top level nodes are :
			<asset>
			<library_images>
			<library_materials>
			<library_effects>
			<library_geometries>
			<library_visual_scene>
			<scene>

			The REAL top root is the <scene> that can contains one of more (instance of) <visual_scene>.
			<visual_scene> can be directly written there (check!) or instanced from their definition in the <library_visual_scene>
			each <visual_scene> contains a hierarchy of <node>
		  each <node> contains
				transformation
				other nodes (to build up a hierarchy)
				instance of geometry
				instance of controller
			instance can be direct or refers name of stuff described in a library.
			An instance of geometry node should contain the <mesh> node and as a son of the <instance geometry> the material node (again referenced from a library)
			-- structure of the geometry node --
			*/
			for(int scn = 0;scn < scn_size;++scn)
			{
				QDomNodeList instscenes = scenes.at(scn).toElement().elementsByTagName("instance_visual_scene");
				int instscn_size = instscenes.size();
				QDEBUG("Scene %i contains %i instance_visual_scene ",scn,instscn_size);
				if (instscn_size == 0)  return E_INCOMPATIBLECOLLADA141FORMAT;

				//for each scene instance in a COLLADA scene
				for(int instscn = 0;instscn < instscn_size; ++instscn)
				{
					QString libscn_url;
					referenceToANodeAttribute(instscenes.at(instscn),"url",libscn_url);
					QDEBUG("instance_visual_scene %i refers %s ",instscn,qPrintable(libscn_url));

//					QDomNode nd = QDomNode(*(inf->doc));
                    QDomNode visscn = findNodeBySpecificAttributeValue(*(info.doc),"visual_scene","id",libscn_url);
					if(visscn.isNull()) return E_UNREFERENCEBLEDCOLLADAATTRIBUTE;

					//assert (visscn.toElement().Attribute("id") == libscn_url);
					//for each node in the libscn_url visual scene
					QDomNodeList visscn_child = visscn.childNodes();
					QDEBUG("instance_visual_scene %s has %i children",qPrintable(libscn_url),visscn_child.size());

					// for each direct child of a visual scene process it
					for(int chdind = 0; chdind < visscn_child.size();++chdind)
					{
						QDomElement node=visscn_child.at(chdind).toElement();
						if(node.isNull()) continue;
						QDEBUG("Processing Visual Scene child %i - of type '%s'",chdind,qPrintable(node.tagName()));
						Matrix44f baseTr; baseTr.SetIdentity();

						if(node.toElement().tagName()=="node")
						{
							ColladaMesh newMesh;
							AddNodeToMesh(node.toElement(), newMesh, baseTr,info);
							tri::Append<OpenMeshType,ColladaMesh>::Mesh(m,newMesh);
						}
					}	// end for each node of a given scene
				} // end for each visual scene instance
			} // end for each scene instance
			return problem;
		}

        static bool LoadMask(const char * filename, InfoDAE& info)
		{
			bool bHasPerWedgeTexCoord = false;
			bool bHasPerWedgeNormal		= false;
			//bool bHasPerWedgeColor		= false;
			bool bHasPerVertexColor		= false;
			bool bHasPerFaceColor			= false;
			bool bHasPerVertexNormal = false;
			bool bHasPerVertexText = false;

			QDomDocument* doc = new QDomDocument(filename);
			QFile file(filename);
			if (!file.open(QIODevice::ReadOnly))
				return false;
			if (!doc->setContent(&file))
			{
				file.close();
				return false;
			}
			file.close();

			QStringList textureFileList;
            info.doc = doc;
            GetTexCoord(*(info.doc),textureFileList);
            QDomNodeList scenes = info.doc->elementsByTagName("scene");
			int scn_size = scenes.size();

			//Is there geometry in the file?
			bool geoinst_found = false;
			//for each scene in COLLADA FILE
			for(int scn = 0;scn < scn_size;++scn)
			{
				QDomNodeList instscenes = scenes.at(scn).toElement().elementsByTagName("instance_visual_scene");
				int instscn_size = instscenes.size();
				if (instscn_size == 0)  return false;

				//for each scene instance in a COLLADA scene
				for(int instscn = 0;instscn < instscn_size; ++instscn)
				{
					QString libscn_url;
					referenceToANodeAttribute(instscenes.at(instscn),"url",libscn_url);
                    QDomNode nd = QDomNode(*(info.doc));
                    QDomNode visscn = findNodeBySpecificAttributeValue(*(info.doc),"visual_scene","id",libscn_url);
					if(visscn.isNull()) 	return false;

					//for each node in the libscn_url visual scene
					//QDomNodeList& visscn_child = visscn.childNodes();
					QDomNodeList visscn_child = visscn.childNodes();

					//for each direct child of a libscn_url visual scene find if there is some geometry instance
					for(int chdind = 0; chdind < visscn_child.size();++chdind)
					{
						//QDomNodeList& geoinst = visscn_child.at(chdind).toElement().elementsByTagName("instance_geometry");
						QDomNodeList geoinst = visscn_child.at(chdind).toElement().elementsByTagName("instance_geometry");
						int geoinst_size = geoinst.size();
						if (geoinst_size != 0)
						{

							geoinst_found |= true;
                            QDomNodeList geolib = info.doc->elementsByTagName("library_geometries");
							//assert(geolib.size() == 1);
							if (geolib.size() != 1)
								return false;
							//!!!!!!!!!!!!!!!!!here will be the code for geometry transformations!!!!!!!!!!!!!!!!!!!!!!
                            info.numvert = 0;
                            info.numface = 0;
							for(int geoinst_ind = 0;geoinst_ind < geoinst_size;++geoinst_ind)
							{
								QString geo_url;
								referenceToANodeAttribute(geoinst.at(geoinst_ind),"url",geo_url);

								QDomNode geo = findNodeBySpecificAttributeValue(geolib.at(0),"geometry","id",geo_url);
								if (geo.isNull())
									return false;

								QDomNodeList vertlist = geo.toElement().elementsByTagName("vertices");

								for(int vert = 0;vert < vertlist.size();++vert)
								{
									QDomNode no;
									no = findNodeBySpecificAttributeValue(vertlist.at(vert),"input","semantic","POSITION");
									QString srcurl;
									referenceToANodeAttribute(no,"source",srcurl);
									no = findNodeBySpecificAttributeValue(geo,"source","id",srcurl);
									QDomNodeList fa = no.toElement().elementsByTagName("float_array");
									assert(fa.size() == 1);
                                    info.numvert += (fa.at(0).toElement().attribute("count").toInt() / 3);
									no = findNodeBySpecificAttributeValue(vertlist.at(vert),"input","semantic","COLOR");
									if (!no.isNull())
										bHasPerVertexColor = true;
									no = findNodeBySpecificAttributeValue(vertlist.at(vert),"input","semantic","NORMAL");
									if (!no.isNull())
										bHasPerVertexNormal = true;
									no = findNodeBySpecificAttributeValue(vertlist.at(vert),"input","semantic","TEXCOORD");
									if (!no.isNull())
										bHasPerVertexText = true;
								}

								const char* arr[] = {"triangles","polylist","polygons"};

								for(unsigned int tt= 0;tt < 3;++tt)
								{
									QDomNodeList facelist = geo.toElement().elementsByTagName(arr[tt]);
									for(int face = 0;face < facelist.size();++face)
									{
                                        info.numface += facelist.at(face).toElement().attribute("count").toInt() ;
										QDomNode no;
										no = findNodeBySpecificAttributeValue(facelist.at(face),"input","semantic","NORMAL");
										if (!no.isNull())
											bHasPerWedgeNormal = true;
										no = findNodeBySpecificAttributeValue(facelist.at(face),"input","semantic","COLOR");
										if (!no.isNull())
											bHasPerVertexColor = true;
										no = findNodeBySpecificAttributeValue(facelist.at(face),"input","semantic","TEXCOORD");
										if (!no.isNull())
											bHasPerWedgeTexCoord = true;
									}
								}
							}
						}
					}
				}
			}

			if (!geoinst_found)
			{
                QDomNodeList geolib = info.doc->elementsByTagName("library_geometries");
				//assert(geolib.size() == 1);
				if (geolib.size() != 1)
					return false;
				QDomNodeList geochild = geolib.at(0).toElement().elementsByTagName("geometry");
				//!!!!!!!!!!!!!!!!!here will be the code for geometry transformations!!!!!!!!!!!!!!!!!!!!!!
                info.numvert = 0;
                info.numface = 0;
				for(int geoinst_ind = 0;geoinst_ind < geochild.size();++geoinst_ind)
				{
					QDomNodeList vertlist = geochild.at(geoinst_ind).toElement().elementsByTagName("vertices");

					for(int vert = 0;vert < vertlist.size();++vert)
					{
						QDomNode no;
						no = findNodeBySpecificAttributeValue(vertlist.at(vert),"input","semantic","POSITION");
						QString srcurl;
						referenceToANodeAttribute(no,"source",srcurl);
						no = findNodeBySpecificAttributeValue(geochild.at(geoinst_ind),"source","id",srcurl);
						QDomNodeList fa = no.toElement().elementsByTagName("float_array");
						assert(fa.size() == 1);
                        info.numvert += (fa.at(0).toElement().attribute("count").toInt() / 3);
						no = findNodeBySpecificAttributeValue(vertlist.at(vert),"input","semantic","COLOR");
						if (!no.isNull())
							bHasPerVertexColor = true;
						no = findNodeBySpecificAttributeValue(vertlist.at(vert),"input","semantic","NORMAL");
						if (!no.isNull())
							bHasPerVertexNormal = true;
						no = findNodeBySpecificAttributeValue(vertlist.at(vert),"input","semantic","TEXCOORD");
						if (!no.isNull())
							bHasPerVertexText = true;
					}

					QDomNodeList facelist = geochild.at(geoinst_ind).toElement().elementsByTagName("triangles");
					for(int face = 0;face < facelist.size();++face)
					{
                        info.numface += facelist.at(face).toElement().attribute("count").toInt() ;
						QDomNode no;
						no = findNodeBySpecificAttributeValue(facelist.at(face),"input","semantic","NORMAL");
						if (!no.isNull())
							bHasPerWedgeNormal = true;
						no = findNodeBySpecificAttributeValue(facelist.at(face),"input","semantic","TEXCOORD");
						if (!no.isNull())
							bHasPerWedgeTexCoord = true;
					}
				}
			}

            info.mask = 0;

			if (bHasPerWedgeTexCoord)
                info.mask |= vcg::tri::io::Mask::IOM_WEDGTEXCOORD;
			if (bHasPerWedgeNormal)
                info.mask |= vcg::tri::io::Mask::IOM_WEDGNORMAL;
			if (bHasPerVertexColor)
                info.mask |= vcg::tri::io::Mask::IOM_VERTCOLOR;
			if (bHasPerFaceColor)
                info.mask |= vcg::tri::io::Mask::IOM_FACECOLOR;
			if (bHasPerVertexNormal)
                info.mask |= vcg::tri::io::Mask::IOM_VERTNORMAL;
			if (bHasPerVertexText)
                info.mask |= vcg::tri::io::Mask::IOM_VERTTEXCOORD;

            delete (info.doc);
            info.doc = NULL;
            //addinfo = info;
			return true;
		}
	};
}
}
}

#endif


text:
#if NETSTANDARD2_1
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;

namespace NetEscapades.Configuration.Validation
{
    /// <summary>
    /// An <see cref="IHostedService"/> that validates <see cref="IValidatable"/> objects are valid on app startup
    /// </summary>
    public class SettingValidationHostedService : IHostedService
    {
        readonly IEnumerable<IValidatable> _validatableObjects;

        /// <summary>
        /// Create a new instance of <see cref="SettingValidationHostedService"/>
        /// </summary>
        /// <param name="validatableObjects"></param>
        public SettingValidationHostedService(IEnumerable<IValidatable> validatableObjects)
        {
            _validatableObjects = validatableObjects;
        }

        /// <inheritdoc />
        public Task StartAsync(CancellationToken cancellationToken)
        {
            foreach (var validatableObject in _validatableObjects)
            {
                validatableObject.Validate();
            }

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
    }
}
#endif

redpajama_set_name: RedPajamaGithub


text:
#ifndef JNILIB_JAVAFUNCTIONMANAGER_H_
#define JNILIB_JAVAFUNCTIONMANAGER_H_

namespace alinous {namespace system {
class AlinousCore;
}}

namespace java { namespace util{
template <typename T>
class ArrayList;
}}

namespace alinous {namespace runtime {namespace dom {
class IAlinousVariable;
}}}
namespace alinous {namespace runtime {namespace dom {
class IDomVariable;
}}}

namespace alinous { namespace compile { namespace analyse {
class AlinousType;
}}}

namespace alinous{ namespace jdk{ namespace functions{

using namespace alinous::system;
using ::java::util::ArrayList;
using ::alinous::runtime::dom::IAlinousVariable;
using ::alinous::runtime::dom::IDomVariable;
using ::alinous::compile::analyse::AlinousType;

class JavaFunctionManager : public IObject {
public:
	JavaFunctionManager(AlinousCore* core, ThreadContext* ctx);
	virtual ~JavaFunctionManager() {
		ThreadContext *ctx = ThreadContext::getCurentContext();
		if(ctx != nullptr){ctx->incGcDenial();}
		__releaseRegerences(false, ctx);
		if(ctx != nullptr){ctx->decGcDenial();}
	}

	virtual void __releaseRegerences(bool prepare, ThreadContext* ctx) throw();

	IAlinousVariable* invoke(UnicodeString* prefix, UnicodeString* name, ArrayList<IDomVariable>* arguments, ThreadContext* ctx);

	void init(ThreadContext* ctx);
	void dispose(ThreadContext* ctx);

	AlinousType* getFunctionReturnType(UnicodeString* prefix, UnicodeString* name, ThreadContext* ctx);
	bool isFunctionPrefix(UnicodeString* prefix, ThreadContext* ctx);
	bool isJavaFunction(UnicodeString* prefix, UnicodeString* funcName, ThreadContext* ctx);

	class ThLogParam{
	public:
		JavaFunctionManager* _this;
		jobject obj;
		jstring jstr;
		jobject jthrowable;
		const char* msg;
		JNIEnv* env;
	};

	static jstring AlinousSystemWrappergetHome(JNIEnv* env, jobject obj);
	static void LoggerWrapperlogError(JNIEnv* env, jobject obj, jobject jthrowable);
	static void LoggerWrapperlogWarning(JNIEnv* env, jobject obj, jstring jstr);
	static void LoggerWrapperlogInfo(JNIEnv* env, jobject obj, jstring jstr);

	static jobject CallbackWrappercallback(JNIEnv* env, jstring jstr, jobjectArray params, jobject clazz);

	// strong ref
	static jclass alinousCoreClass;
	static jclass javaConnectorClass;
	static jclass loggerWrapperClass;
	static jclass callbackWrapperClass;

	static jclass functionModelClass;
	static jclass iDomVariableClass;
	static jclass domVariable;
	static jclass domArray;

	static jclass timeSpecClass;
	static jclass timestampClass;
	static jclass bigDecimalClass;

	static jclass iteratorClass;
private:
	AlinousCore* core;
	JavaVM *jvm;
	JNIEnv jni;
	JavaVM vmi;
	JavaVMInitArgs vm_args;
	JavaVMOption options[4];
	bool enabled;

	jobject javaConnector;

	JNIThread* jniThread;

	void registerNatives(JNIEnv *env);

	bool initEnv(JNIEnv **env);

};

}}}

#endif /* JNILIB_JAVAFUNCTIONMANAGER_H_ */


text:
pymatgen.analysis.excitation module
===================================

.. automodule:: pymatgen.analysis.excitation
    :members:
    :undoc-members:
    :show-inheritance:


text:
package com.touwolf.mailchimp.data.condiction.types;

public class McSocialNetworkMember extends McParent {
    private McSocialNetworkMemberOpEnum op;

    private McSocialNetworkMemberFieldEnum field;

    private McSocialNetworkMemberValueEnum value;

    /**
     * Members who are or are not on a specific social network.
     * Possible Values:
     *

     * member
     * notmember
     */
    public McSocialNetworkMemberOpEnum getOp() {
        return op;
    }

    public void setOp(McSocialNetworkMemberOpEnum op) {
        this.op = op;
    }

    /**
     * The social_network segment field.
     * Possible Values:
     *

     * social_network
     */
    public McSocialNetworkMemberFieldEnum getField() {
        return field;
    }

    public void setField(McSocialNetworkMemberFieldEnum field) {
        this.field = field;
    }

    /**
     * The social network to segment on.
     * Possible Values:
     *

     * twitter
     * facebook
     * linkedin
     * flickr
     * foursquare
     * lastfm
     * myspace
     * quora
     * vimeo
     * yelp
     * youtube
     */
    public McSocialNetworkMemberValueEnum getValue() {
        return value;
    }

    public void setValue(McSocialNetworkMemberValueEnum value) {
        this.value = value;
    }
}


text:
using namespace boost::python;
using namespace IECorePython;
using namespace Gaffer;
using namespace GafferScene;
using namespace GafferSceneUI;
using namespace GafferBindings;

namespace
{

void setScene( SceneGadget &g, ScenePlug &scene )
{
	ScopedGILRelease gilRelease;
	g.setScene( &scene );
}

GafferScene::ScenePlugPtr getScene( SceneGadget &g )
{
	return const_cast<GafferScene::ScenePlug *>( g.getScene() );
}

void setContext( SceneGadget &g, Context &context )
{
	ScopedGILRelease gilRelease;
	g.setContext( &context );
}

void setVisibleSet( SceneGadget &g, const GafferScene::VisibleSet &visibleSet )
{
	ScopedGILRelease gilRelease;
	g.setVisibleSet( visibleSet );
}

void setMinimumExpansionDepth( SceneGadget &g, size_t depth )
{
	ScopedGILRelease gilRelease;
	g.setMinimumExpansionDepth( depth );
}

void setPaused( SceneGadget &g, bool paused )
{
	ScopedGILRelease gilRelease;
	g.setPaused( paused );
}

void waitForCompletion( SceneGadget &g )
{
	ScopedGILRelease gilRelease;
	g.waitForCompletion();
}

struct SceneGadgetSlotCaller
{
	void operator()( boost::python::object slot, SceneGadgetPtr g )
	{
		try
		{
			slot( g );
		}
		catch( const error_already_set &e )
		{
			ExceptionAlgo::translatePythonException();
		}
	}
};

void setRenderer( SceneGadget &g, IECore::InternedString name )
{
	ScopedGILRelease gilRelease;
	g.setRenderer( name );
}

std::string getRenderer( SceneGadget &g )
{
	return g.getRenderer().string();
}

IECore::CompoundObjectPtr getOpenGLOptions( const SceneGadget &g )
{
	return g.getOpenGLOptions()->copy();
}

IECore::StringVectorDataPtr getSelectionMask( const SceneGadget &g )
{
	const IECore::StringVectorData *d = g.getSelectionMask();
	return d ? d->copy() : nullptr;
}

IECore::InternedStringVectorDataPtr objectAt( SceneGadget &g, IECore::LineSegment3f &l )
{
	ScopedGILRelease gilRelease;
	IECore::InternedStringVectorDataPtr result = new IECore::InternedStringVectorData;
	if( g.objectAt( l, result->writable() ) )
	{
		return result;
	}
	return nullptr;
}

tuple objectAndIntersectionAt( SceneGadget &g, IECore::LineSegment3f &l )
{
	IECore::InternedStringVectorDataPtr result = new IECore::InternedStringVectorData;
	Imath::V3f hitPos( 0.0f );

	{
		ScopedGILRelease gilRelease;
		if( !g.objectAt( l, result->writable(), hitPos ) )
		{
			result = nullptr;
		}
	}

	return boost::python::make_tuple( result, hitPos );
}

size_t objectsAt( SceneGadget &g, const Imath::V3f &corner0InGadgetSpace, const Imath::V3f &corner1InGadgetSpace, IECore::PathMatcher &paths )
{
	ScopedGILRelease gilRelease;
	return g.objectsAt( corner0InGadgetSpace, corner1InGadgetSpace, paths );
}

Imath::Box3f selectionBound( SceneGadget &g )
{
	ScopedGILRelease gilRelease;
	return g.selectionBound();
}

Imath::Box3f bound( SceneGadget &g, bool selected, const IECore::PathMatcher *omitted )
{
	ScopedGILRelease gilRelease;
	return g.bound( selected, omitted );
}

} // namespace

void GafferSceneUIModule::bindSceneGadget()
{

	scope s = GafferUIBindings::GadgetClass<SceneGadget>()
		.def( init<>() )
		.def( "setScene", &setScene )
		.def( "getScene", &getScene )
		.def( "setContext", &setContext )
		.def( "getContext", (Gaffer::Context *(SceneGadget::*)())&SceneGadget::getContext, return_value_policy<CastToIntrusivePtr>() )
		.def( "setVisibleSet", &setVisibleSet )
		.def( "getVisibleSet", &SceneGadget::getVisibleSet, return_value_policy<copy_const_reference>() )
		.def( "setMinimumExpansionDepth", &setMinimumExpansionDepth )
		.def( "getMinimumExpansionDepth", &SceneGadget::getMinimumExpansionDepth )
		.def( "getPaused", &SceneGadget::getPaused )
		.def( "setPaused", &setPaused )
		.def( "state", &SceneGadget::state )
		.def( "stateChangedSignal", &SceneGadget::stateChangedSignal, return_internal_reference<1>() )
		.def( "waitForCompletion", &waitForCompletion )
		.def( "setRenderer", &setRenderer )
		.def( "getRenderer", &getRenderer )
		.def( "setOpenGLOptions", &SceneGadget::setOpenGLOptions )
		.def( "getOpenGLOptions", &getOpenGLOptions )
		.def( "setSelectionMask", &SceneGadget::setSelectionMask )
		.def( "getSelectionMask", &getSelectionMask )
		.def( "objectAt", &objectAt )
		.def( "objectAndIntersectionAt", &objectAndIntersectionAt )
		.def( "objectsAt", &objectsAt )
		.def( "setSelection", &SceneGadget::setSelection )
		.def( "getSelection", &SceneGadget::getSelection, return_value_policy<copy_const_reference>() )
		.def( "selectionBound", &selectionBound )
		.def( "bound", &bound, ( arg( "selected" ), arg( "omitted" ) = object() ) )
	;

	enum_<SceneGadget::State>( "State" )
		.value( "Paused", SceneGadget::Paused )
		.value( "Running", SceneGadget::Running )
		.value( "Complete", SceneGadget::Complete )
	;

	SignalClass<SceneGadget::SceneGadgetSignal, DefaultSignalCaller<SceneGadget::SceneGadgetSignal>, SceneGadgetSlotCaller>( "ImageGadgetSignal" );

}


text:
CBrowserHead::
CBrowserHead(CBrowserWindow *window) :
 CBrowserObject(window, CHtmlTagId::HEAD)
{
  setDisplay(Display::NONE);
}

void
CBrowserHead::
init()
{
  CBrowserObject::init();
}

void
CBrowserHead::
setNameValue(const std::string &name, const std::string &value)
{
  CBrowserObject::setNameValue(name, value);
}


text:
#ifndef CONSTOVERLOAD_H
#define CONSTOVERLOAD_H
#include <iostream>
class Point3 {                                  /* 3-dimension point (of double). */
 public:
    friend std::ostream& operator<<(std::ostream& out, const Point3& v);
    Point3(double x = 0, double y = 0, double z = 0);
    double& operator[](int index);
    const double& operator[](int index) const;  /* Overloaded
       on const-ness. */
    Point3 operator+(const Point3& v) const;
    Point3 operator-(const Point3& v) const;
    Point3 operator*(double s) const;           /* Scalar multiplication. */
 private:
    static const int cm_Dim = 3;
    double m_Coord[cm_Dim];
};
#endif


text:
Location management and geocoding / reverse geocoding library.

## Documentation

- http://www.rubymotion.com/developers/motion-flow/Location.html


text:
#include "limb_manipulation/region_growing_rgb_segmentation.h"
#include <ros/console.h>

#include "perception/box_fitter.h"
#include "perception/object.h"
#include "visualization_msgs/Marker.h"
#include "pcl/segmentation/extract_clusters.h"
#include <pcl/filters/extract_indices.h>
#include "geometry_msgs/Pose.h"
#include "simple_grasping/shape_extraction.h"
#include "shape_msgs/SolidPrimitive.h"

#include <boost/lexical_cast.hpp>

namespace manipulation {

Segmenter::Segmenter(const ros::Publisher& filtered_cloud_pub, const ros::Publisher& colored_cloud_pub, const ros::Publisher& marker_pub)
  : filtered_cloud_pub_(filtered_cloud_pub), colored_cloud_pub_(colored_cloud_pub), marker_pub_(marker_pub) {}

void Segmenter::JointStateCallback(const sensor_msgs::JointState& msg) {
  head_tilt_joint_value_ = msg.position[5];
  torso_lift_joint_value_ = msg.position[2];
}

void Segmenter::Callback(const sensor_msgs::PointCloud2& msg) {
  SegmentPointCloud(msg);
}

void Segmenter::SegmentPointCloud(const sensor_msgs::PointCloud2& msg) {
  // parameters
  int reg_distance, reg_point_color, reg_region_color, min_cluster_size, max_cluster_size;
  ros::param::param("reg_distance", reg_distance, 10);
  ros::param::param("reg_point_color", reg_point_color, 6);
  ros::param::param("reg_region_color", reg_region_color, 5);
  ros::param::param("min_cluster_size", min_cluster_size, 60);
  ros::param::param("max_cluster_size", max_cluster_size, 10000);

  // pass through filter
  pcl::search::Search <pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB>);

  pcl::PointCloud <pcl::PointXYZRGB>::Ptr cloud_unfiltered (new pcl::PointCloud <pcl::PointXYZRGB>);
  pcl::fromROSMsg (msg, *cloud_unfiltered);

  pcl::IndicesPtr indices (new std::vector <int>);
  pcl::PointCloud <pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud <pcl::PointXYZRGB>);
  pcl::removeNaNFromPointCloud(*cloud_unfiltered, *cloud, *indices);

  pcl::PassThrough<pcl::PointXYZRGB> pass;
  pass.setInputCloud (cloud);
  pass.setFilterFieldName("z");
  pass.setFilterLimits(0.0, 1.0);
  pcl::PointCloud <pcl::PointXYZRGB>::Ptr filtered_cloud (new pcl::PointCloud <pcl::PointXYZRGB>);
  pass.filter (*filtered_cloud);

  // publish the filtered point cloud
  // sensor_msgs::PointCloud2 filtered_cloud_msg;
  // pcl::toROSMsg (*filtered_cloud, filtered_cloud_msg);
  // filtered_cloud_pub_.publish(filtered_cloud_msg);

  // color segmentation
  pcl::RegionGrowingRGB<pcl::PointXYZRGB> reg;
  reg.setInputCloud (filtered_cloud);
  // reg.setIndices (indices);
  reg.setSearchMethod (tree);
  reg.setDistanceThreshold (reg_distance);  // determine whether the point is in the neighboring or not
  reg.setPointColorThreshold (reg_point_color);
  reg.setRegionColorThreshold (reg_region_color);
  reg.setMinClusterSize (min_cluster_size);
  reg.setMaxClusterSize (max_cluster_size);

  std::vector <pcl::PointIndices> object_indices;
  reg.extract (object_indices);
  pcl::PointCloud <pcl::PointXYZRGB>::Ptr colored_cloud = reg.getColoredCloud ();

  // convert to sensor message
  sensor_msgs::PointCloud2 cloud_out;
  pcl::toROSMsg (*colored_cloud, cloud_out);

  // **********************************
  // // transform point cloud
  // cloud_out.header.frame_id = "head_camera_rgb_frame";

  // tf::TransformListener tf_listener;
  // tf::StampedTransform transform;
  // try {
  //   tf_listener.waitForTransform("base_link", cloud_out.header.frame_id,
  //                                ros::Time(0), ros::Duration(5.0));
  //   tf_listener.lookupTransform("base_link", cloud_out.header.frame_id,
  //                               ros::Time(0), transform);
  // } catch (tf::LookupException& e) {
  //   ROS_ERROR("%s", e.what());
  // } catch (tf::ExtrapolationException& e) {
  //   ROS_ERROR("%s", e.what());
  // }

  // sensor_msgs::PointCloud2 colored_cloud_transformed;
  // pcl_ros::transformPointCloud("base_link", cloud_out, colored_cloud_transformed, tf_listener);

  // colored_cloud_pub_.publish(colored_cloud_transformed);
  // **********************************
  // transform point cloud
  tf::Transform rotation_transform;
  rotation_transform.setOrigin( tf::Vector3(0.17, 0.02, 1.03 + torso_lift_joint_value_) );
  tf::Quaternion q;
  q.setRPY(-1.5707 - head_tilt_joint_value_, 0, -1.5707);
  rotation_transform.setRotation(q);

  // // Eigen::Affine3f rotation_transform = Eigen::Affine3f::Identity();
  // // Define a translation of 2.5 meters on the x axis.
  // rotation_transform.translation() << 2.5, 0.0, 0.0;
  // // The same rotation matrix as before; theta radians around Z axis
  // rotation_transform.rotate (Eigen::AngleAxisf (1.5707, Eigen::Vector3f::UnitZ()));

  sensor_msgs::PointCloud2 colored_cloud_transformed;
  pcl_ros::transformPointCloud("base_link", rotation_transform, cloud_out, colored_cloud_transformed);
  // **********************************

  // publish the color-segmented cloud
  colored_cloud_pub_.publish(colored_cloud_transformed);

  // convert ROS message to pcl PointCloud type for labelling
  pcl::PointCloud <pcl::PointXYZRGB>::Ptr colored_cloud_with_transformation (new pcl::PointCloud <pcl::PointXYZRGB>);
  pcl::fromROSMsg (colored_cloud_transformed, *colored_cloud_with_transformation);
  // label the markers
  SegmentMarker(&object_indices, colored_cloud_with_transformation);

}

void Segmenter::SegmentMarker(std::vector <pcl::PointIndices>* object_indices, pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud) {
  // parameters
  int size_min, size_max;
  ros::param::param("size_min", size_min, 3);
  ros::param::param("size_max", size_max, 10);

  pcl::ExtractIndices<pcl::PointXYZRGB> extract;
  extract.setInputCloud(cloud);

  int num = 0;  // for the id# of visualization markers

  for (size_t i = 0; i < object_indices->size(); ++i) {
    // reify indices into a point cloud of the object
    pcl::PointIndices::Ptr indices(new pcl::PointIndices);
    *indices = object_indices->at(i);

    if (indices->indices.size() > size_min && indices->indices.size() < size_max) {
      pcl::PointCloud<pcl::PointXYZRGB>::Ptr object_cloud(new pcl::PointCloud<pcl::PointXYZRGB>());
      // fill in object_cloud using indices
      extract.setIndices(indices);
      extract.setNegative(false);
      extract.filter(*object_cloud);

      // find the center of the object
      Eigen::Vector4f centroid;
      pcl::compute3DCentroid (*object_cloud, centroid);

      // publish a marker
      visualization_msgs::Marker object_marker;
      object_marker.ns = "objects";
      object_marker.id = num;
      object_marker.header.frame_id = "base_link";
      object_marker.type = visualization_msgs::Marker::SPHERE;

      object_marker.pose.position.x = centroid[0];
      object_marker.pose.position.y = centroid[1];
      object_marker.pose.position.z = centroid[2];
      object_marker.scale.x = 0.05;
      object_marker.scale.y = 0.05;
      object_marker.scale.z = 0.05;
      object_marker.color.g = 1;
      object_marker.color.a = 1;
      marker_pub_.publish(object_marker);

      num++;

    }

    /*
    // Fit every region into a bounding box, and only label markers with specific sizes
    pcl::PointCloud<pcl::PointXYZRGB>::Ptr object_cloud(new pcl::PointCloud<pcl::PointXYZRGB>());

    // fill in object_cloud using indices
    extract.setIndices(indices);
    extract.setNegative(false);
    extract.filter(*object_cloud);

    // bounding box
    pcl::PointCloud<pcl::PointXYZRGB>::Ptr object_cloud_out(new pcl::PointCloud<pcl::PointXYZRGB>());
    shape_msgs::SolidPrimitive shape;
    geometry_msgs::Pose pose;
    simple_grasping::extractShape(*object_cloud, *object_cloud_out, shape, pose);

    if (shape.type == shape_msgs::SolidPrimitive::BOX) {
      double x = shape.dimensions[0], y = shape.dimensions[1], z = shape.dimensions[2];

      if (z > 0.5) {
        std::cout << num << std::endl;
        std::cout << "x: " << x << std::endl;
        std::cout << "y: " << y << std::endl;
        std::cout << "z: " << z << std::endl;
        std::cout << std::endl;

        // sensor_msgs::PointCloud2 object_cloud_transformed;
        // pcl::toROSMsg(*object_cloud, object_cloud_transformed);
        // colored_cloud_pub_.publish(object_cloud_transformed);

        // find the center of the object
        Eigen::Vector4f centroid;
        pcl::compute3DCentroid (*object_cloud, centroid);

        // publish a marker
        visualization_msgs::Marker object_marker;
        object_marker.ns = "objects";
        object_marker.id = num;
        object_marker.header.frame_id = "base_link";
        object_marker.type = visualization_msgs::Marker::TEXT_VIEW_FACING;

        object_marker.text = boost::lexical_cast<std::string>(num);
        object_marker.pose.position.x = centroid[0];
        object_marker.pose.position.y = centroid[1];
        object_marker.pose.position.z = centroid[2];
        object_marker.scale.x = 0.05;
        object_marker.scale.y = 0.05;
        object_marker.scale.z = 0.05;
        object_marker.color.g = 1;
        object_marker.color.a = 1;
        marker_pub_.publish(object_marker);

        num++;
      }
    }
    */
  }
}
}  // namespace manipulation


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9"/>
<title>Snowflake: Snowflake.Utility.BiDictionary< TFirst, TSecond > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Snowflake
    api-pre-alpha

Snowflake C# API Documentation

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Classes |
Public Member Functions |
Properties |
List of all members

Snowflake.Utility.BiDictionary< TFirst, TSecond > Class Template Reference

Inheritance diagram for Snowflake.Utility.BiDictionary< TFirst, TSecond >:

  <map id="Snowflake.Utility.BiDictionary< TFirst, TSecond >_map" name="Snowflake.Utility.BiDictionary< TFirst, TSecond >_map">
</map>

Public Member Functions

IEnumerator< KeyValuePair< TFirst, TSecond > > 	GetEnumerator ()

void 	Add (TFirst key, TSecond value)

bool 	ContainsKey (TFirst key)

bool 	TryGetValue (TFirst key, out TSecond value)

bool 	Remove (TFirst key)

void 	Clear ()

Properties

IDictionary< TSecond, TFirst > 	Reverse [get]

int 	Count [get]

bool 	IsReadOnly [get]

TSecond 	this[TFirst key] [get, set]

ICollection< TFirst > 	Keys [get]

ICollection< TSecond > 	Values [get]

The documentation for this class was generated from the following file:

Utility/BiDictionary.cs

Snowflake

Utility

BiDictionary

Generated on Fri Jan 2 2015 15:30:43 for Snowflake by

     1.8.9


text:
package org.apache.pulsar.common.configuration;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Stores field context to validate based on requirement or value constraints.
 *
 *
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FieldContext {

    /**
     * checks field value is required. By default field is mandatory false.
     *
     * @return true if attribute is required else returns false
     */
    public boolean required() default false;

    /**
     * binds numeric value's lower bound
     *
     * @return minimum value of the field
     */
    public long minValue() default Long.MIN_VALUE;

    /**
     * binds numeric value's upper bound
     *
     * @return maximum value of the field
     */
    public long maxValue() default Long.MAX_VALUE;

    /**
     * binds character length of text
     *
     * @return character length of field
     */
    public int maxCharLength() default Integer.MAX_VALUE;

    /**
     * allow field to be updated dynamically
     *
     * @return
     */
    public boolean dynamic() default false;
}


text:
namespace TitaniumAS.Opc.Client.Common.Wrappers
{
    public interface IComWrapper
    {
    }
}


text:
package gl

import (
	"github.com/blevesearch/bleve/v2/analysis"
	"github.com/blevesearch/bleve/v2/registry"
)

const StopName = "stop_gl"

// this content was obtained from:
// lucene-4.7.2/analysis/common/src/resources/org/apache/lucene/analysis/
// ` was changed to ' to allow for literal string

var GalicianStopWords = []byte(`# galican stopwords
a
aínda
alí
aquel
aquela
aquelas
aqueles
aquilo
aquí
ao
aos
as
así
á
ben
cando
che
co
coa
comigo
con
connosco
contigo
convosco
coas
cos
cun
cuns
cunha
cunhas
da
dalgunha
dalgunhas
dalgún
dalgúns
das
de
del
dela
delas
deles
desde
deste
do
dos
dun
duns
dunha
dunhas
e
el
ela
elas
eles
en
era
eran
esa
esas
ese
eses
esta
estar
estaba
está
están
este
estes
estiven
estou
eu
é
facer
foi
foron
fun
había
hai
iso
isto
la
las
lle
lles
lo
los
mais
me
meu
meus
min
miña
miñas
moi
na
nas
neste
nin
no
non
nos
nosa
nosas
noso
nosos
nós
nun
nunha
nuns
nunhas
o
os
ou
ó
ós
para
pero
pode
pois
pola
polas
polo
polos
por
que
se
senón
ser
seu
seus
sexa
sido
sobre
súa
súas
tamén
tan
te
ten
teñen
teño
ter
teu
teus
ti
tido
tiña
tiven
túa
túas
un
unha
unhas
uns
vos
vosa
vosas
voso
vosos
vós
`)

func TokenMapConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenMap, error) {
	rv := analysis.NewTokenMap()
	err := rv.LoadBytes(GalicianStopWords)
	return rv, err
}

func init() {
	registry.RegisterTokenMap(StopName, TokenMapConstructor)
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@drawable/sms_item"
              android:orientation="vertical"
              android:padding="16dp">

    <TextView
        android:id="@+id/id_tv_msg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="8dp"/>

    <com.angluswang.festival_sms.view.FlowLayout
        android:id="@+id/id_fl_contacts"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </com.angluswang.festival_sms.view.FlowLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/id_tv_festival"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="8dp"
            android:background="@drawable/tag_bg"/>

        <TextView
            android:id="@+id/id_tv_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</LinearLayout>


text:
package elogeel.utilities;

/*
 * Spring 2013 TCSS 558 - Applied Distributed Computing
 * Institute of Technology, UW Tacoma
 * Written by Daniel M. Zimmerman
 */

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * WordList encapsulates a word list for the spelling server. It includes a
 * method to return the subset of the word list that is "close" to a
 * specified word, as defined in the assignment, plus other utility methods.
 *
 * @author Daniel M. Zimmerman
 * @version Spring 2013
 */
public class WordList
{
  // Instance Fields

  /**
   * The TreeSet containing the word list. We chose a TreeSet because it
   * sorts the entries and allows for relatively quick searching.
   */
  private final Set<String> my_words = new TreeSet<String>();

  // Constructor

  /**
   * Creates a WordList from the file with the specified name.
   *
   * @param the_file The name of the file.
   * @exception IOException if there is a problem reading the list from the
   *  file.
   */
  public WordList(final String the_file) throws IOException
  {
    // create a reader for the file

    final FileReader file_reader = new FileReader(the_file);
    final BufferedReader buffered_reader = new BufferedReader(file_reader);

    // read the lines

    String line;

    do
    {
      line = buffered_reader.readLine();

      if (line != null && line.length() != 0)
      {
        // it's a word (not a blank line)

        my_words.add(line);
      }
    }
    while (line != null);

    buffered_reader.close();
  }

  /**
   * Constructs a WordList from the specified collection of Strings.
   *
   * @param the_words The words.
   */
  protected WordList(final Collection<String> the_words)
  {
    if (the_words != null)
    {
      my_words.addAll(the_words);
    }
  }

  // Instance Methods

  /**
   * Checks for a word in the list.
   *
   * @param the_word The word to search for.
   * @return true if the specified word is in the word list, false
   *  otherwise.
   */
  public boolean isInList(final String the_word)
  {
    return my_words.contains(the_word);
  }

  /**
   * Checks for words "close to" the specified word in the list.
   *
   * @param the_word The word to check for closeness.
   * @return a sorted set containing all words in the word list that
   *  are "close" to the specified word, as described in the assignment.
   */
  public SortedSet<String> getCloseWords(final String the_word)
  {
    final SortedSet<String> close_set = new TreeSet<>();

    for (String s : my_words)
    {
      if (WordDistance.getDistance(the_word, s) <=
          WordDistance.DISTANCE_THRESHOLD)
      {
        // the word is close enough
        close_set.add(s);
      }
    }

    return close_set;
  }

  /*
   * @param the_word The name of the word to be added.
   */
  public synchronized void add(String the_word) {
      my_words.add(the_word);
  }

  /*
   * @param the_word The name of the word to be removed.
   */
  public synchronized void remove(String the_word) {
      if (my_words.contains(the_word)) {
          my_words.remove(the_word);
      }
  }
}


text:
var gulp = require('gulp');
var gutil = require('gulp-util');
var browserify = require('browserify');
var watchify = require('watchify');
var source = require('vinyl-source-stream');

// bundler used to run watchify and browserify
var bundler = watchify(browserify(watchify.args, {standalone: 'NUTELLA'}));
// add the lib file to bundle
bundler.add('./src/nutella_lib.js');

gulp.task('bundle', bundle); // so you can run `gulp js` to build the file
bundler.on('update', bundle); // on any dep update, runs the bundler
bundler.on('log', gutil.log); // output build logs to terminal

function bundle() {
    return bundler.bundle()
        // log errors if they happen
        .on('error', gutil.log.bind(gutil, 'Browserify Error'))
        .pipe(source('nutella_lib.js'))
        .pipe(gulp.dest('./dist'));
}

gulp.task('default', function() {
    // place code for your default task here
});


text:
title: "Delete Nodes and Return Forest"
description: "Some description ..."
authors: ["lek-tin"]
tags: ["leetcode", "binary-tree", "dfs"]
categories: ["algorithm"]
date: 2020-03-22T01:46:03-07:00
lastmod: 2020-03-22T01:46:03-07:00
draft: false
archive: false
---

Given the `root` of a binary tree, each node in the tree has a distinct value.

After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).

Return the roots of the trees in the remaining forest.  You may return the result in any order.

### Example 1

![delete nodes and return forest example 1](/img/post/delete-nodes-and-return-forest-example-1.png)
```
Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
Output: [[1,2,null,4],[6],[7]]
```

#### Constraints

1 The number of nodes in the given tree is at most `1000`.
2. Each node has a distinct value between `1` and `1000`.
3. `to_delete.length <= 1000`
4. `to_delete` contains distinct values between `1` and `1000`.

### Solution

```python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
        self.res = []
        to_delete = set(to_delete)
        self.dfs(root, to_delete, True)
        return self.res

    def dfs(self, root, to_delete, is_root):
        if not root:
            return None

        is_deleted = root.val in to_delete

        if is_root and not is_deleted:
            self.res.append(root)

        root.left = self.dfs(root.left, to_delete, is_deleted)
        root.right = self.dfs(root.right, to_delete, is_deleted)

        return None if is_deleted else root
```


text:
using System;
using System.ComponentModel.DataAnnotations;

namespace MigrationDicas.Models
{
    public class Aluno
    {
        [Key]
        public int AlunoID { get; set; }
        public int ProfessorID { get; set; }
        [Required]
        public string NomeAluno { get; set; }
        public string Email { get; set; }
        public int Ano { get; set; }
        public DateTime? Inscricao { get; set; }

        public virtual Professor Professor { get; set; }
    }
}


text:
namespace df
{

class Message;

class MessageAcceptor
{
public:
  virtual ~MessageAcceptor() {}

protected:
  virtual void AcceptMessage(dp::RefPointer<Message> message) = 0;

  /// Must be called by subclass on message target thread
  void ProcessSingleMessage(unsigned maxTimeWait = -1);
  void CloseQueue();

private:
  friend class ThreadsCommutator;

  void PostMessage(dp::TransferPointer<Message> message);

private:
  MessageQueue m_messageQueue;
};

} // namespace df


text:
package com.podio.app;

import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonValue;

public enum ApplicationViewType {

	BADGE,
	TABLE,
	LIST,
	NODE,
	CALENDAR,
	GALLERY,
	CARD,
	STREAM;

	@Override
	@JsonValue
	public String toString() {
		return name().toLowerCase();
	}

	@JsonCreator
	public static ApplicationViewType getByName(String value) {
		return valueOf(value.toUpperCase());
	}
}


text:
package com.ettrema.console;

public interface ConsoleCommand {

    public Result execute();

}


text:
package com.facebook.imagepipeline.producers;

import com.facebook.common.internal.Preconditions;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.Executor;

public class ThreadHandoffProducerQueue {
  private boolean mQueueing = false;
  private final Deque<Runnable> mRunnableList;
  private final Executor mExecutor;

  public ThreadHandoffProducerQueue(Executor executor) {
    mExecutor = Preconditions.checkNotNull(executor);
    mRunnableList = new ArrayDeque<>();
  }

  public synchronized void addToQueueOrExecute(Runnable runnable) {
    if (mQueueing) {
      mRunnableList.add(runnable);
    } else {
      mExecutor.execute(runnable);
    }
  }

  public synchronized void startQueueing() {
    mQueueing = true;
  }

  public synchronized void stopQueuing() {
    mQueueing = false;
    execInQueue();
  }

  private void execInQueue() {
    while (!mRunnableList.isEmpty()) {
      mExecutor.execute(mRunnableList.pop());
    }
    mRunnableList.clear();
  }

  public synchronized void remove(Runnable runnable) {
    mRunnableList.remove(runnable);
  }

  public synchronized boolean isQueueing() {
    return mQueueing;
  }
}


text:
#include <stdio.h>

#include <contiki.h>
#include <contiki-net.h>

#include "letmecreate/core/i2c.h"
#include "letmecreate/core/network.h"
#include "letmecreate/click/thermo3.h"

#include "letmecreate/core/debug.h"

#define SERVER_IP_ADDR "fe80::e01a:69ff:fe6c:4a97"

#define SERVER_PORT 3000
#define CLIENT_PORT 3001

#define BUFFER_SIZE 64

PROCESS(main_process, "Main process");
AUTOSTART_PROCESSES(&main_process);
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(main_process, ev, data)
{
    PROCESS_BEGIN();
    INIT_NETWORK_DEBUG();
    {
        // Due to the way Contiki protothreads work this needs to be static,
        // otherwise the data will be lost when switching to a different thread
        static struct etimer et;
        static struct uip_udp_conn * conn;
        static float temperature;
        static uint8_t network_data[2];

        PRINTF("===START===\n");

        i2c_init();
        conn = udp_new_connection(CLIENT_PORT, SERVER_PORT, SERVER_IP_ADDR);

        thermo3_click_enable(0);
        while(1)
        {
            etimer_set(&et, CLOCK_SECOND);
            PROCESS_WAIT_EVENT();

            thermo3_click_get_temperature(&temperature);

            // We don't want to send floats over, so the simples solution is to send
            // the integer part plus the first two decimal point digits as integers,
            // then we decode them on the server
            network_data[0] = (uint8_t)temperature;
            network_data[1] = (uint8_t)((temperature - (float)network_data[0]) * 100.0);

            PRINTF("Sending temperature %i.%i\n", network_data[0], network_data[1]);

            udp_packet_send(conn, network_data, 2);
            PROCESS_WAIT_UDP_SENT();
        }

        thermo3_click_disable();
        i2c_release();
    }

    PROCESS_END();
}

/*---------------------------------------------------------------------------*/


text:
<?php

App::uses('PusherComponent', 'CakePusher.Controller/Component');
App::uses('Controller', 'Controller');
App::uses('ComponentCollection', 'Controller');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');

/**
 * A test variant of the PusherComponent class.
 *
 * @author James Tancock <tanuck@gmail.com>
 */
class TestPusherComponent extends PusherComponent {

/**
 * The Pusher api instance.
 *
 * @var Pusher
 * @codingStandardsIgnoreStart
 */
	public $_pusherApps = array();

	public $_current = null;
// @codingStandardsIgnoreEnd
}

class PusherComponentTest extends CakeTestCase {

	public function setUp() {
		parent::setUp();

		$ComponentCollection = new ComponentCollection();
		$this->Pusher = new TestPusherComponent($ComponentCollection, array(
			'main' => array(
				'auth_key' => 'a',
				'secret' => 'b',
				'app_id' => '1234',
			),
			'backup' => array(
				'auth_key' => '1',
				'secret' => '2',
				'app_id' => '5678',
			),
		));
		$this->Pusher->initialize(new Controller(new CakeRequest(), new CakeResponse()));
	}

	public function testConstructor() {
		$collection = new ComponentCollection();
		$Pusher = new TestPusherComponent($collection, array(
			'auth_key' => 'b',
			'secret' => 'c',
			'app_id' => '4321',
			'bad_key' => 'bad_value',
		));

		$expected = array(
			'main' => array(
				'auth_key' => 'b',
				'secret' => 'c',
				'app_id' => '4321',
				'options' => array(),
				'host' => null,
				'port' => null,
				'timeout' => null,
				'bad_key' => 'bad_value',
			),
		);
		$this->assertEquals($expected, $Pusher->settings);
	}

	public function testInitialize() {
		$this->assertInstanceOf('Pusher', $this->Pusher->_pusherApps['main']);
	}

/**
 * @expectedException InternalErrorException
 * @expectedExceptionMessage Invalid pusher method.
 */
	public function testForErrorWhenCallingUnMappedMethod() {
		$this->Pusher->badMethodCall();
	}

	public function testTrigger() {
		$this->Pusher->_pusherApps['main'] = $this->getMockBuilder('Pusher')
									->disableOriginalConstructor()
									->getMock();
		$this->Pusher->_pusherApps['main']
					->expects($this->exactly(1))
					->method('trigger')
					->with($this->equalTo('my-channel'),
						$this->equalTo('new-message'),
						$this->equalTo('Hello Bill'),
						$this->equalTo(null))
					->will($this->returnValue(true));

		$this->assertTrue($this->Pusher->trigger('my-channel', 'new-message', 'Hello Bill'));
	}

	public function testSocketAuth() {
		$result = $this->Pusher->socketAuth('my-channel', '1234.1234');
		$this->assertInternalType('string', $result);
		$this->assertEquals(
			'{"auth":"a:0126071f211855bc9a126cc8a702a877b1b349e98189ddcb2a88e4be810297d1"}',
			$result
		);
	}

	public function testPresenceAuth() {
		$result = $this->Pusher->presenceAuth('my-channel', '1234.1234', 'user-12', true);
		$this->assertInternalType('string', $result);
		$this->assertEquals(
			'{"auth":"a:47279d0aa95b2c5cf73bbe8190bf3973db703f5742cf4b5e248c828138238dd0","channel_data":"{\"user_id\":\"user-12\",\"user_info\":true}"}',
			$result
		);

		$this->Pusher->_pusherApps['main'] = $this->getMockBuilder('Pusher')
									->disableOriginalConstructor()
									->getMock();
		$this->Pusher->_pusherApps['main']
					->expects($this->exactly(1))
					->method('presence_auth')
					->with($this->equalTo('my-channel'),
						$this->equalTo('1234.1234'),
						$this->equalTo('user-12'),
						$this->equalTo(true));
		$this->Pusher->presenceAuth('my-channel', '1234.1234', 'user-12', true);
	}

	public function testGet() {
		$this->Pusher->_pusherApps['main'] = $this->getMockBuilder('Pusher')
									->disableOriginalConstructor()
									->getMock();
		$this->Pusher->_pusherApps['main']
					->expects($this->exactly(1))
					->method('get')
					->with($this->equalTo('/channels'),
						$this->equalTo(array()))
					->will($this->returnValue(array('status' => 200)));

		$result = $this->Pusher->get('/channels');
		$this->assertInternalType('array', $result);
		$this->assertEquals(200, $result['status']);
	}

	public function testGetDefault() {
		$default = $this->Pusher->getDefault();
		$this->assertInternalType('string', $default);
		$this->assertEquals('main', $default);
	}

	public function testSetDefault() {
		$this->assertFalse($this->Pusher->setDefault(new stdClass()));

		$this->assertFalse($this->Pusher->setDefault('badappname'));

		$this->assertTrue($this->Pusher->setDefault('backup'));
		$this->assertEquals('backup', $this->Pusher->getDefault());
	}

	public function testAddAppConfig() {
		$result = $this->Pusher->addAppConfig('newapp', array(
			'auth_key' => 'key',
			'secret' => 'secret',
			'app_id' => '234',
		));
		$this->assertTrue($result);
	}

	public function testWith() {
		$result = $this->Pusher->with('backup');
		$this->assertInstanceOf('PusherComponent', $result);
		$this->assertEquals('backup', $this->Pusher->_current);

		$result = $this->Pusher->with();
		$this->assertEquals('main', $this->Pusher->_current);
	}

/**
 * @expectedException CakeException
 * @expectedExceptionMessage Missing Pusher app instance.
 */
	public function testWithErrorForMissingApp() {
		$this->Pusher->with('badappname');
	}

}


text:
<?php

namespace PhpEws\DataType;

use PhpEws\DataType;

/**
 * Definition of the SyncFolderHierarchyCreateOrUpdateType type
 */
class SyncFolderHierarchyCreateOrUpdateType extends DataType
{
    /**
     * Folder property
     *
     * @var FolderType
     */
    public $Folder;

    /**
     * CalendarFolder property
     *
     * @var CalendarFolderType
     */
    public $CalendarFolder;

    /**
     * ContactsFolder property
     *
     * @var ContactsFolderType
     */
    public $ContactsFolder;

    /**
     * SearchFolder property
     *
     * @var SearchFolderType
     */
    public $SearchFolder;

    /**
     * TasksFolder property
     *
     * @var TasksFolderType
     */
    public $TasksFolder;
}


text:
package io.druid.query.search.search;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import io.druid.granularity.QueryGranularity;
import io.druid.query.BaseQuery;
import io.druid.query.DataSource;
import io.druid.query.Query;
import io.druid.query.Result;
import io.druid.query.dimension.DimensionSpec;
import io.druid.query.filter.DimFilter;
import io.druid.query.search.SearchResultValue;
import io.druid.query.spec.QuerySegmentSpec;

import java.util.List;
import java.util.Map;

/**
 */
public class SearchQuery extends BaseQuery<Result<SearchResultValue>>
{
  private final DimFilter dimFilter;
  private final SearchSortSpec sortSpec;
  private final QueryGranularity granularity;
  private final List<DimensionSpec> dimensions;
  private final SearchQuerySpec querySpec;
  private final int limit;

  @JsonCreator
  public SearchQuery(
      @JsonProperty("dataSource") DataSource dataSource,
      @JsonProperty("filter") DimFilter dimFilter,
      @JsonProperty("granularity") QueryGranularity granularity,
      @JsonProperty("limit") int limit,
      @JsonProperty("intervals") QuerySegmentSpec querySegmentSpec,
      @JsonProperty("searchDimensions") List<DimensionSpec> dimensions,
      @JsonProperty("query") SearchQuerySpec querySpec,
      @JsonProperty("sort") SearchSortSpec sortSpec,
      @JsonProperty("context") Map<String, Object> context
  )
  {
    super(dataSource, querySegmentSpec, context);
    this.dimFilter = dimFilter;
    this.sortSpec = sortSpec == null ? new LexicographicSearchSortSpec() : sortSpec;
    this.granularity = granularity == null ? QueryGranularity.ALL : granularity;
    this.limit = (limit == 0) ? 1000 : limit;
    this.dimensions = dimensions;
    this.querySpec = querySpec;

    Preconditions.checkNotNull(querySegmentSpec, "Must specify an interval");
    Preconditions.checkNotNull(querySpec, "Must specify a query");
  }

  @Override
  public boolean hasFilters()
  {
    return dimFilter != null;
  }

  @Override
  public String getType()
  {
    return Query.SEARCH;
  }

  @Override
  public SearchQuery withQuerySegmentSpec(QuerySegmentSpec spec)
  {
    return new SearchQuery(
        getDataSource(),
        dimFilter,
        granularity,
        limit,
        spec,
        dimensions,
        querySpec,
        sortSpec,
        getContext()
    );
  }

  @Override
  public Query<Result<SearchResultValue>> withDataSource(DataSource dataSource)
  {
    return new SearchQuery(
        dataSource,
        dimFilter,
        granularity,
        limit,
        getQuerySegmentSpec(),
        dimensions,
        querySpec,
        sortSpec,
        getContext()
    );
  }

  @Override
  public SearchQuery withOverriddenContext(Map<String, Object> contextOverrides)
  {
    return new SearchQuery(
        getDataSource(),
        dimFilter,
        granularity,
        limit,
        getQuerySegmentSpec(),
        dimensions,
        querySpec,
        sortSpec,
        computeOverridenContext(contextOverrides)
    );
  }

  @JsonProperty("filter")
  public DimFilter getDimensionsFilter()
  {
    return dimFilter;
  }

  @JsonProperty
  public QueryGranularity getGranularity()
  {
    return granularity;
  }

  @JsonProperty
  public int getLimit()
  {
    return limit;
  }

  @JsonProperty("searchDimensions")
  public List<DimensionSpec> getDimensions()
  {
    return dimensions;
  }

  @JsonProperty("query")
  public SearchQuerySpec getQuery()
  {
    return querySpec;
  }

  @JsonProperty("sort")
  public SearchSortSpec getSort()
  {
    return sortSpec;
  }

  public SearchQuery withLimit(int newLimit)
  {
    return new SearchQuery(
        getDataSource(),
        dimFilter,
        granularity,
        newLimit,
        getQuerySegmentSpec(),
        dimensions,
        querySpec,
        sortSpec,
        getContext()
    );
  }

  @Override
  public String toString()
  {
    return "SearchQuery{" +
        "dataSource='" + getDataSource() + '\'' +
        ", dimFilter=" + dimFilter +
        ", granularity='" + granularity + '\'' +
        ", dimensions=" + dimensions +
        ", querySpec=" + querySpec +
        ", querySegmentSpec=" + getQuerySegmentSpec() +
        ", limit=" + limit +
        '}';
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    if (!super.equals(o)) return false;

    SearchQuery that = (SearchQuery) o;

    if (limit != that.limit) return false;
    if (dimFilter != null ? !dimFilter.equals(that.dimFilter) : that.dimFilter != null) return false;
    if (dimensions != null ? !dimensions.equals(that.dimensions) : that.dimensions != null) return false;
    if (granularity != null ? !granularity.equals(that.granularity) : that.granularity != null) return false;
    if (querySpec != null ? !querySpec.equals(that.querySpec) : that.querySpec != null) return false;
    if (sortSpec != null ? !sortSpec.equals(that.sortSpec) : that.sortSpec != null) return false;

    return true;
  }

  @Override
  public int hashCode()
  {
    int result = super.hashCode();
    result = 31 * result + (dimFilter != null ? dimFilter.hashCode() : 0);
    result = 31 * result + (sortSpec != null ? sortSpec.hashCode() : 0);
    result = 31 * result + (granularity != null ? granularity.hashCode() : 0);
    result = 31 * result + (dimensions != null ? dimensions.hashCode() : 0);
    result = 31 * result + (querySpec != null ? querySpec.hashCode() : 0);
    result = 31 * result + limit;
    return result;
  }
}