text:
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics.OpenGL4;
using Voxalia.Shared;
using Voxalia.ClientGame.OtherSystems;
using FreneticScript;

namespace Voxalia.ClientGame.GraphicsSystems
{
    public class VBO
    {
        uint _VertexVBO;
        uint _IndexVBO;
        uint _NormalVBO;
        uint _TexCoordVBO;
        uint _ColorVBO;
        uint _BoneIDVBO;
        uint _BoneWeightVBO;
        uint _BoneID2VBO;
        uint _BoneWeight2VBO;
        uint _TCOLVBO;
        uint _THVVBO;
        uint _THWVBO;
        uint _TangentVBO;
        public int _VAO = -1;

        public Texture Tex;
        public Texture Tex_Specular;
        public Texture Tex_Reflectivity;
        public Texture Tex_Normal;

        public List<Vector3> Vertices;
        public List<uint> Indices;
        public List<Vector3> Normals;
        public List<Vector3> Tangents;
        public List<Vector3> TexCoords;
        public List<Vector4> Colors;
        public List<Vector4> BoneIDs;
        public List<Vector4> BoneWeights;
        public List<Vector4> BoneIDs2;
        public List<Vector4> BoneWeights2;
        public List<Vector4> TCOLs;
        public List<Vector4> THVs;
        public List<Vector4> THWs;

        public long LastVRAM = 0;

        public long GetVRAMUsage()
        {
            return LastVRAM;
        }

        public void CleanLists()
        {
            Vertices = null;
            Indices = null;
            Normals = null;
            Tangents = null;
            TexCoords = null;
            Colors = null;
            BoneIDs = null;
            BoneWeights = null;
            BoneIDs2 = null;
            BoneWeights2 = null;
            verts = null;
            indices = null;
            normals = null;
            texts = null;
            TCOLs = null;
            THVs = null;
            THWs = null;
        }

        int vC;

        public void AddSide(Location normal, TextureCoordinates tc, bool offs = false, float texf = 0)
        {
            // TODO: IMPROVE!
            for (int i = 0; i < 6; i++)
            {
                Normals.Add(ClientUtilities.Convert(normal));
                Colors.Add(new Vector4(1f, 1f, 1f, 1f));
                Indices.Add((uint)Indices.Count);
                BoneIDs.Add(new Vector4(0, 0, 0, 0));
                BoneWeights.Add(new Vector4(0f, 0f, 0f, 0f));
                BoneIDs2.Add(new Vector4(0, 0, 0, 0));
                BoneWeights2.Add(new Vector4(0f, 0f, 0f, 0f));
            }
            float aX = (tc.xflip ? 1 : 0) + tc.xshift;
            float aY = (tc.yflip ? 1 : 0) + tc.yshift;
            float bX = (tc.xflip ? 0 : 1) * tc.xscale + tc.xshift;
            float bY = (tc.yflip ? 1 : 0) + tc.yshift;
            float cX = (tc.xflip ? 0 : 1) * tc.xscale + tc.xshift;
            float cY = (tc.yflip ? 0 : 1) * tc.yscale + tc.yshift;
            float dX = (tc.xflip ? 1 : 0) + tc.xshift;
            float dY = (tc.yflip ? 0 : 1) * tc.yscale + tc.yshift;
            float zero = offs ? -0.5f: -1; // Sssh
            float one = offs ? 0.5f : 1;
            if (normal.Z == 1)
            {
                // T1
                TexCoords.Add(new Vector3(bX, bY, texf));
                Vertices.Add(new Vector3(zero, zero, one));
                TexCoords.Add(new Vector3(cX, cY, texf));
                Vertices.Add(new Vector3(zero, one, one));
                TexCoords.Add(new Vector3(dX, dY, texf));
                Vertices.Add(new Vector3(one, one, one));
                // T2
                TexCoords.Add(new Vector3(bX, bY, texf));
                Vertices.Add(new Vector3(zero, zero, one));
                TexCoords.Add(new Vector3(dX, dY, texf));
                Vertices.Add(new Vector3(one, one, one));
                TexCoords.Add(new Vector3(aX, aY, texf));
                Vertices.Add(new Vector3(one, zero, one));
            }
            else if (normal.Z == -1)
            {
                // T1
                TexCoords.Add(new Vector3(cX, cY, texf));
                Vertices.Add(new Vector3(one, one, zero));
                TexCoords.Add(new Vector3(dX, dY, texf));
                Vertices.Add(new Vector3(zero, one, zero));
                TexCoords.Add(new Vector3(aX, aY, texf));
                Vertices.Add(new Vector3(zero, zero, zero));
                // T2
                TexCoords.Add(new Vector3(bX, bY, texf));
                Vertices.Add(new Vector3(one, zero, zero));
                TexCoords.Add(new Vector3(cX, cY, texf));
                Vertices.Add(new Vector3(one, one, zero));
                TexCoords.Add(new Vector3(aX, aY, texf));
                Vertices.Add(new Vector3(zero, zero, zero));
            }
            else if (normal.X == 1)
            {
                // T1
                TexCoords.Add(new Vector3(bX, bY, texf));
                Vertices.Add(new Vector3(one, one, one));
                TexCoords.Add(new Vector3(cX, cY, texf));
                Vertices.Add(new Vector3(one, one, zero));
                TexCoords.Add(new Vector3(dX, dY, texf));
                Vertices.Add(new Vector3(one, zero, zero));
                // T2
                TexCoords.Add(new Vector3(aX, aY, texf));
                Vertices.Add(new Vector3(one, zero, one));
                TexCoords.Add(new Vector3(bX, bY, texf));
                Vertices.Add(new Vector3(one, one, one));
                TexCoords.Add(new Vector3(dX, dY, texf));
                Vertices.Add(new Vector3(one, zero, zero));
            }
            else if (normal.X == -1)
            {
                // T1
                TexCoords.Add(new Vector3(cX, cY, texf));
                Vertices.Add(new Vector3(zero, zero, zero));
                TexCoords.Add(new Vector3(dX, dY, texf));
                Vertices.Add(new Vector3(zero, one, zero));
                TexCoords.Add(new Vector3(aX, aY, texf));
                Vertices.Add(new Vector3(zero, one, one));
                // T2
                TexCoords.Add(new Vector3(cX, cY, texf));
                Vertices.Add(new Vector3(zero, zero, zero));
                TexCoords.Add(new Vector3(aX, aY, texf));
                Vertices.Add(new Vector3(zero, one, one));
                TexCoords.Add(new Vector3(bX, bY, texf));
                Vertices.Add(new Vector3(zero, zero, one));
            }
            else if (normal.Y == 1)
            {
                // T1
                TexCoords.Add(new Vector3(aX, aY, texf));
                Vertices.Add(new Vector3(one, one, one));
                TexCoords.Add(new Vector3(bX, bY, texf));
                Vertices.Add(new Vector3(zero, one, one));
                TexCoords.Add(new Vector3(cX, cY, texf));
                Vertices.Add(new Vector3(zero, one, zero));
                // T2
                TexCoords.Add(new Vector3(dX, dY, texf));
                Vertices.Add(new Vector3(one, one, zero));
                TexCoords.Add(new Vector3(aX, aY, texf));
                Vertices.Add(new Vector3(one, one, one));
                TexCoords.Add(new Vector3(cX, cY, texf));
                Vertices.Add(new Vector3(zero, one, zero));
            }
            else if (normal.Y == -1)
            {
                // T1
                TexCoords.Add(new Vector3(dX, dY, texf));
                Vertices.Add(new Vector3(zero, zero, zero));
                TexCoords.Add(new Vector3(aX, aY, texf));
                Vertices.Add(new Vector3(zero, zero, one));
                TexCoords.Add(new Vector3(bX, bY, texf));
                Vertices.Add(new Vector3(one, zero, one));
                // T2
                TexCoords.Add(new Vector3(dX, dY, texf));
                Vertices.Add(new Vector3(zero, zero, zero));
                TexCoords.Add(new Vector3(bX, bY, texf));
                Vertices.Add(new Vector3(one, zero, one));
                TexCoords.Add(new Vector3(cX, cY, texf));
                Vertices.Add(new Vector3(one, zero, zero));
            }
            else
            {
                throw new Exception("Lazy code can't handle unique normals! Only axis-aligned, normalized normals!");
            }
        }

        public void Prepare()
        {
            Vertices = new List<Vector3>();
            Indices = new List<uint>();
            Normals = new List<Vector3>();
            TexCoords = new List<Vector3>();
            Colors = new List<Vector4>();
            BoneIDs = new List<Vector4>();
            BoneWeights = new List<Vector4>();
            BoneIDs2 = new List<Vector4>();
            BoneWeights2 = new List<Vector4>();
        }

        public bool generated = false;

        public void Destroy()
        {
            if (generated)
            {
                GL.DeleteVertexArray(_VAO);
                GL.DeleteBuffer(_VertexVBO);
                GL.DeleteBuffer(_IndexVBO);
                GL.DeleteBuffer(_NormalVBO);
                GL.DeleteBuffer(_TexCoordVBO);
                GL.DeleteBuffer(_TangentVBO);
                if (colors)
                {
                    GL.DeleteBuffer(_ColorVBO);
                    colors = false;
                }
                if (tcols)
                {
                    GL.DeleteBuffer(_TCOLVBO);
                    GL.DeleteBuffer(_THVVBO);
                    GL.DeleteBuffer(_THWVBO);
                    tcols = false;
                }
                if (bones)
                {
                    GL.DeleteBuffer(_BoneIDVBO);
                    GL.DeleteBuffer(_BoneWeightVBO);
                    GL.DeleteBuffer(_BoneID2VBO);
                    GL.DeleteBuffer(_BoneWeight2VBO);
                    bones = false;
                }
                generated = false;
            }
        }

        public void oldvert()
        {
            verts = Vertices.ToArray();
            normals = Normals.ToArray();
            texts = TexCoords.ToArray();
            Vertices = null;
            Normals = null;
            TexCoords = null;
            // TODO: Other arrays?
        }

        bool colors;
        bool tcols;
        bool bones;

        public Vector3[] verts = null;
        public uint[] indices = null;
        Vector3[] normals = null;
        Vector3[] texts = null;

        public void UpdateBuffer()
        {
            if (Vertices == null && verts == null)
            {
                SysConsole.Output(OutputType.ERROR, "Failed to update VBO, null vertices!");
                return;
            }
            LastVRAM = 0;
            Vector3[] vecs = verts == null ? Vertices.ToArray() : verts;
            uint[] inds = indices == null ? Indices.ToArray() : indices;
            Vector3[] norms = normals == null ? Normals.ToArray() : normals;
            Vector3[] texs = texts == null ? TexCoords.ToArray() : texts;
            Vector3[] tangs = Tangents != null ? Tangents.ToArray() : TangentsFor(vecs, norms, texs);
            Vector4[] cols = Colors != null ? Colors.ToArray() : null;
            Vector4[] tcols = TCOLs != null ? TCOLs.ToArray() : null;
            Vector4[] thvs = THVs != null ? THVs.ToArray() : null;
            Vector4[] thws = THWs != null ? THWs.ToArray() : null;
            vC = vecs.Length;
            // Vertex buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, _VertexVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vecs.Length * Vector3.SizeInBytes), vecs, BufferMode);
            LastVRAM += vecs.Length * Vector3.SizeInBytes;
            // Normal buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, _NormalVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(norms.Length * Vector3.SizeInBytes), norms, BufferMode);
            LastVRAM += norms.Length * Vector3.SizeInBytes;
            // TexCoord buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, _TexCoordVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(texs.Length * Vector3.SizeInBytes), texs, BufferMode);
            LastVRAM += texs.Length * Vector3.SizeInBytes;
            // Tangent buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, _TangentVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(tangs.Length * Vector3.SizeInBytes), tangs, BufferMode);
            LastVRAM += tangs.Length * Vector3.SizeInBytes;
            // Color buffer
            if (cols != null)
            {
                GL.BindBuffer(BufferTarget.ArrayBuffer, _ColorVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(cols.Length * Vector4.SizeInBytes), cols, BufferMode);
                LastVRAM += cols.Length * Vector4.SizeInBytes;
            }
            // TCOL buffer
            if (tcols != null)
            {
                GL.BindBuffer(BufferTarget.ArrayBuffer, _TCOLVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(tcols.Length * Vector4.SizeInBytes), tcols, BufferMode);
                LastVRAM += tcols.Length * Vector4.SizeInBytes;
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THVVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(thvs.Length * Vector4.SizeInBytes), thvs, BufferMode);
                LastVRAM += thvs.Length * Vector4.SizeInBytes;
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THWVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(thws.Length * Vector4.SizeInBytes), thws, BufferMode);
                LastVRAM += thws.Length * Vector4.SizeInBytes;
            }
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            // Index buffer
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, _IndexVBO);
            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(inds.Length * sizeof(uint)), inds, BufferMode);
            LastVRAM += inds.Length * sizeof(uint);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
        }

        public void GenerateOrUpdate()
        {
            if (generated)
            {
                UpdateBuffer();
            }
            else
            {
                GenerateVBO();
            }
        }

        public BufferUsageHint BufferMode = BufferUsageHint.StaticDraw;

        public static Vector3[] TangentsFor(Vector3[] vecs, Vector3[] norms, Vector3[] texs)
        {
            Vector3[] tangs = new Vector3[vecs.Length];
            if (vecs.Length != norms.Length || texs.Length != vecs.Length || (vecs.Length % 3) != 0)
            {
                for (int i = 0; i < tangs.Length; i++)
                {
                    tangs[i] = new Vector3(0, 0, 0);
                }
                return tangs;
            }
            for (int i = 0; i < vecs.Length; i += 3)
            {
                Vector3 v1 = vecs[i];
                Vector3 dv1 = vecs[i + 1] - v1;
                Vector3 dv2 = vecs[i + 2] - v1;
                Vector3 t1 = texs[i];
                Vector3 dt1 = texs[i + 1] - t1;
                Vector3 dt2 = texs[i + 2] - t1;
                Vector3 tangent = (dv1 * dt2.Y - dv2 * dt1.Y) / (dt1.X * dt2.Y - dt1.Y * dt2.X);
                Vector3 normal = norms[i];
                tangent = (tangent - normal * Vector3.Dot(normal, tangent)).Normalized(); // TODO: Necessity of this correction?
                tangs[i] = tangent;
                tangs[i + 1] = tangent;
                tangs[i + 2] = tangent;
            }
            return tangs;
        }

        public static Vector3[] TangentsFor(Vector3[] vecs, Vector3[] norms, Vector2[] texs)
        {
            Vector3[] tangs = new Vector3[vecs.Length];
            if (vecs.Length != norms.Length || texs.Length != vecs.Length || (vecs.Length % 3) != 0)
            {
                for (int i = 0; i < tangs.Length; i++)
                {
                    tangs[i] = new Vector3(0, 0, 0);
                }
                return tangs;
            }
            for (int i = 0; i < vecs.Length; i += 3)
            {
                Vector3 v1 = vecs[i];
                Vector3 dv1 = vecs[i + 1] - v1;
                Vector3 dv2 = vecs[i + 2] - v1;
                Vector2 t1 = texs[i];
                Vector2 dt1 = texs[i + 1] - t1;
                Vector2 dt2 = texs[i + 2] - t1;
                Vector3 tangent = (dv1 * dt2.Y - dv2 * dt1.Y) / (dt1.X * dt2.Y - dt1.Y * dt2.X);
                Vector3 normal = norms[i];
                tangent = (tangent - normal * Vector3.Dot(normal, tangent)).Normalized(); // TODO: Necessity of this correction?
                tangs[i] = tangent;
                tangs[i + 1] = tangent;
                tangs[i + 2] = tangent;
            }
            return tangs;
        }

        public void GenerateVBO()
        {
            if (generated)
            {
                Destroy();
            }
            GL.BindVertexArray(0);
            if (Vertices == null && verts == null)
            {
                SysConsole.Output(OutputType.ERROR, "Failed to render VBO, null vertices!");
                return;
            }
            Vector3[] vecs = verts == null ? Vertices.ToArray() : verts;
            if (vecs.Length == 0)
            {
                return;
            }
            LastVRAM = 0;
            uint[] inds = indices == null ? Indices.ToArray() : indices;
            Vector3[] norms = normals == null ? Normals.ToArray() : normals;
            Vector3[] texs = texts == null ? TexCoords.ToArray() : texts;
            Vector3[] tangs = Tangents != null ? Tangents.ToArray() : TangentsFor(vecs, norms, texs);
            Vector4[] cols = Colors != null ? Colors.ToArray() : null;
            Vector4[] tcols = TCOLs != null ? TCOLs.ToArray() : null;
            Vector4[] thvs = THVs != null ? THVs.ToArray() : null;
            Vector4[] thws = THWs != null ? THWs.ToArray() : null;
            vC = inds.Length;
            Vector4[] ids = null;
            if (BoneIDs != null)
            {
                ids = BoneIDs.ToArray();
                bones = true;
            }
            Vector4[] weights = null;
            if (BoneWeights != null)
            {
                weights = BoneWeights.ToArray();
            }
            Vector4[] ids2 = null;
            if (BoneIDs2 != null)
            {
                ids2 = BoneIDs2.ToArray();
            }
            Vector4[] weights2 = null;
            if (BoneWeights2 != null)
            {
                weights2 = BoneWeights2.ToArray();
            }
            // Vertex buffer
            GL.GenBuffers(1, out _VertexVBO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _VertexVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vecs.Length * Vector3.SizeInBytes), vecs, BufferMode);
            LastVRAM += vecs.Length * Vector3.SizeInBytes;
            // Normal buffer
            GL.GenBuffers(1, out _NormalVBO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _NormalVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(norms.Length * Vector3.SizeInBytes), norms, BufferMode);
            LastVRAM += norms.Length * Vector3.SizeInBytes;
            // TexCoord buffer
            GL.GenBuffers(1, out _TexCoordVBO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _TexCoordVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(texs.Length * Vector3.SizeInBytes), texs, BufferMode);
            LastVRAM += texs.Length * Vector3.SizeInBytes;
            GL.GenBuffers(1, out _TangentVBO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _TangentVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(tangs.Length * Vector3.SizeInBytes), tangs, BufferMode);
            LastVRAM += tangs.Length * Vector3.SizeInBytes;
            // Color buffer
            if (cols != null)
            {
                colors = true;
                GL.GenBuffers(1, out _ColorVBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _ColorVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(cols.Length * Vector4.SizeInBytes), cols, BufferMode);
                LastVRAM += cols.Length * Vector4.SizeInBytes;
            }
            // TCOL buffer
            if (tcols != null)
            {
                this.tcols = true;
                GL.GenBuffers(1, out _TCOLVBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _TCOLVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(tcols.Length * Vector4.SizeInBytes), tcols, BufferMode);
                LastVRAM += tcols.Length * Vector4.SizeInBytes;
                GL.GenBuffers(1, out _THVVBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THVVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(thvs.Length * Vector4.SizeInBytes), thvs, BufferMode);
                LastVRAM += thvs.Length * Vector4.SizeInBytes;
                GL.GenBuffers(1, out _THWVBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THWVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(thws.Length * Vector4.SizeInBytes), thws, BufferMode);
                LastVRAM += thws.Length * Vector4.SizeInBytes;
            }
            // Weight buffer
            if (weights != null)
            {
                GL.GenBuffers(1, out _BoneWeightVBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _BoneWeightVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(weights.Length * Vector4.SizeInBytes), weights, BufferMode);
                LastVRAM += weights.Length * Vector4.SizeInBytes;
            }
            // ID buffer
            if (ids != null)
            {
                GL.GenBuffers(1, out _BoneIDVBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _BoneIDVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(ids.Length * Vector4.SizeInBytes), ids, BufferMode);
                LastVRAM += ids.Length * Vector4.SizeInBytes;
            }
            // Weight2 buffer
            if (weights2 != null)
            {
                GL.GenBuffers(1, out _BoneWeight2VBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _BoneWeight2VBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(weights2.Length * Vector4.SizeInBytes), weights2, BufferMode);
                LastVRAM += weights2.Length * Vector4.SizeInBytes;
            }
            // ID2 buffer
            if (ids2 != null)
            {
                GL.GenBuffers(1, out _BoneID2VBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _BoneID2VBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(ids2.Length * Vector4.SizeInBytes), ids2, BufferMode);
                LastVRAM += ids2.Length * Vector4.SizeInBytes;
            }
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            // Index buffer
            GL.GenBuffers(1, out _IndexVBO);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, _IndexVBO);
            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(inds.Length * sizeof(uint)), inds, BufferMode);
            LastVRAM += inds.Length * sizeof(uint);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
            // VAO
            GL.GenVertexArrays(1, out _VAO);
            GL.BindVertexArray(_VAO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _VertexVBO);
            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 0, 0);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _NormalVBO);
            GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, 0, 0);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _TexCoordVBO);
            GL.VertexAttribPointer(2, 3, VertexAttribPointerType.Float, false, 0, 0);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _TangentVBO);
            GL.VertexAttribPointer(3, 3, VertexAttribPointerType.Float, false, 0, 0);
            if (cols != null)
            {
                GL.BindBuffer(BufferTarget.ArrayBuffer, _ColorVBO);
                GL.VertexAttribPointer(4, 4, VertexAttribPointerType.Float, false, 0, 0);
            }
            if (tcols != null)
            {
                GL.BindBuffer(BufferTarget.ArrayBuffer, _TCOLVBO);
                GL.VertexAttribPointer(5, 4, VertexAttribPointerType.Float, false, 0, 0);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THVVBO);
                GL.VertexAttribPointer(6, 4, VertexAttribPointerType.Float, false, 0, 0);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THWVBO);
                GL.VertexAttribPointer(7, 4, VertexAttribPointerType.Float, false, 0, 0);
            }
            if (weights != null)
            {
                GL.BindBuffer(BufferTarget.ArrayBuffer, _BoneWeightVBO);
                GL.VertexAttribPointer(5, 4, VertexAttribPointerType.Float, false, 0, 0);
            }
            if (ids != null)
            {
                GL.BindBuffer(BufferTarget.ArrayBuffer, _BoneIDVBO);
                GL.VertexAttribPointer(6, 4, VertexAttribPointerType.Float, false, 0, 0);
            }
            if (weights2 != null)
            {
                GL.BindBuffer(BufferTarget.ArrayBuffer, _BoneWeight2VBO);
                GL.VertexAttribPointer(7, 4, VertexAttribPointerType.Float, false, 0, 0);
            }
            if (ids2 != null)
            {
                GL.BindBuffer(BufferTarget.ArrayBuffer, _BoneID2VBO);
                GL.VertexAttribPointer(8, 4, VertexAttribPointerType.Float, false, 0, 0);
            }
            GL.EnableVertexAttribArray(0);
            GL.EnableVertexAttribArray(1);
            GL.EnableVertexAttribArray(2);
            GL.EnableVertexAttribArray(3);
            if (cols != null)
            {
                GL.EnableVertexAttribArray(4);
            }
            if (tcols != null)
            {
                GL.EnableVertexAttribArray(5);
                GL.EnableVertexAttribArray(6);
                GL.EnableVertexAttribArray(7);
            }
            if (weights != null)
            {
                GL.EnableVertexAttribArray(5);
            }
            if (ids != null)
            {
                GL.EnableVertexAttribArray(6);
            }
            if (weights2 != null)
            {
                GL.EnableVertexAttribArray(7);
            }
            if (ids2 != null)
            {
                GL.EnableVertexAttribArray(8);
            }
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, _IndexVBO);
            // Clean up
            GL.BindVertexArray(0);
            generated = true;

        }

        public void Render(bool texture, bool fixafter = true)
        {
            if (!generated)
            {
                return;
            }
            if (texture && Tex != null)
            {
                GL.ActiveTexture(TextureUnit.Texture3);
                if (Tex_Reflectivity != null)
                {
                    Tex_Reflectivity.Bind();
                }
                else
                {
                    Tex.Engine.Black.Bind();
                }
                GL.ActiveTexture(TextureUnit.Texture2);
                if (Tex_Specular != null)
                {
                    Tex_Specular.Bind();
                }
                else
                {
                    Tex.Engine.Black.Bind();
                }
                GL.ActiveTexture(TextureUnit.Texture1);
                if (Tex_Normal != null)
                {
                    Tex_Normal.Bind();
                }
                else
                {
                    Tex.Engine.NormalDef.Bind();
                }
                GL.ActiveTexture(TextureUnit.Texture0);
                Tex.Bind();
            }
            GL.BindVertexArray(_VAO);
            GL.DrawElements(PrimitiveType.Triangles, vC, DrawElementsType.UnsignedInt, IntPtr.Zero);
            GL.BindVertexArray(0);
            if (fixafter && texture && Tex != null)
            {
                GL.ActiveTexture(TextureUnit.Texture3);
                Tex.Engine.Black.Bind();
                GL.ActiveTexture(TextureUnit.Texture2);
                Tex.Engine.Black.Bind();
                GL.ActiveTexture(TextureUnit.Texture1);
                Tex.Engine.NormalDef.Bind();
                GL.ActiveTexture(TextureUnit.Texture0);
                Tex.Engine.White.Bind();
            }
        }
    }

    public class TextureCoordinates
    {
        public TextureCoordinates()
        {
            xscale = 1;
            yscale = 1;
            xshift = 0;
            yshift = 0;
            xflip = false;
            yflip = false;
        }

        public float xscale;
        public float yscale;
        public float xshift;
        public float yshift;
        public bool xflip;
        public bool yflip;

        public override string ToString()
        {
            return xscale + "/" + yscale + "/" + xshift + "/" + yshift + "/" + (xflip ? "t" : "f") + "/" + (yflip ? "t" : "f");
        }

        public static TextureCoordinates FromString(string str)
        {
            TextureCoordinates tc = new TextureCoordinates();
            string[] data = str.SplitFast('/');
            tc.xscale = (float)Utilities.StringToFloat(data[0]);
            tc.yscale = (float)Utilities.StringToFloat(data[1]);
            tc.xshift = (float)Utilities.StringToFloat(data[2]);
            tc.yshift = (float)Utilities.StringToFloat(data[3]);
            tc.xflip = data[4] == "t";
            tc.yflip = data[5] == "t";
            return tc;
        }
    }
}


text:
function CategoryService($http){
  this.getCategories = function(){
    return $http.get('http://localhost:3000/api/v1/categories');
  }
}

angular
.module('app')
.service("CategoryService", CategoryService)

redpajama_set_name: RedPajamaGithub


text:
package org.apache.carbondata.spark.testsuite.joinquery

import org.apache.spark.sql.Row
import org.apache.spark.sql.common.util.QueryTest
import org.scalatest.BeforeAndAfterAll

/**
 * Test Class for join query with orderby and limit
 */

class OrderByLimitTestCase extends QueryTest with BeforeAndAfterAll {

  override def beforeAll {
    sql(
      "CREATE TABLE carbon1 (empno int, empname String, designation String, doj Timestamp, " +
      "workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, " +
      "projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int," +
      "utilization int,salary int) STORED BY 'org.apache.carbondata.format'")
    sql(
      s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE carbon1 OPTIONS
          |('DELIMITER'= ',', 'QUOTECHAR'= '\"')""".stripMargin);

    sql(
      "CREATE TABLE carbon2 (empno int, empname String, designation String, doj Timestamp, " +
      "workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, " +
      "projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int," +
      "utilization int,salary int) STORED BY 'org.apache.carbondata.format'")
    sql(
      s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE carbon2 OPTIONS
          |('DELIMITER'= ',', 'QUOTECHAR'= '\"')""".stripMargin);

    sql(
      "CREATE TABLE carbon1_hive (empno int, empname String, designation String, doj Timestamp, " +
      "workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, " +
      "projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int," +
      "utilization int,salary int) row format delimited fields terminated by ','")
    sql(
      s"LOAD DATA local inpath '$resourcesPath/datawithoutheader.csv' INTO TABLE carbon1_hive ")

    sql(
      "CREATE TABLE carbon2_hive (empno int, empname String, designation String, doj Timestamp, " +
      "workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, " +
      "projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int," +
      "utilization int,salary int) row format delimited fields terminated by ','")
    sql(
      s"LOAD DATA local inpath '$resourcesPath/datawithoutheader.csv' INTO TABLE carbon2_hive ");

  }

  test("test join with orderby limit") {
    checkAnswer(
      sql(
        "select a.empno,a.empname,a.workgroupcategoryname from carbon1 a full outer join carbon2 " +
        "b on substr(a.workgroupcategoryname," +
        "1,3)" +
        "=substr(b.workgroupcategoryname,1,3) order by a.empname limit 5"),
      sql(
        "select a.empno,a.empname,a.workgroupcategoryname from carbon1_hive a full outer join " +
        "carbon2_hive b on " +
        "substr(a" +
        ".workgroupcategoryname,1,3)=substr(b.workgroupcategoryname,1,3) order by a.empname limit" +
        " 5")
    )
  }

  override def afterAll {
    sql("drop table carbon1")
    sql("drop table carbon2")
    sql("drop table carbon1_hive")
    sql("drop table carbon2_hive")
  }
}


text:
<?php
Class Login extends CI_Controller {

	 function __construct() {
		parent::__construct();
		$this->data[]='';
		$this->load->helper('url');
		$this->data['url']=base_url();
		$this->load->library('parser');
		$this->load->library('session');
		$this->load->model('login_model');
		$this->load->library('email');
	 }

	 /* Function for Dashboard view.....................................................................*/
	function index()
	{
		$this->parser->parse('include/header',$this->data);
		$this->load->view('dashboard',$this->data);
		$this->parser->parse('include/footer_dashboard',$this->data);
	}

	/* Function for login Application view.....................................................................*/
	function application_login()
	{
		//$app_list=$this->data['app_list']=$this->login_model->app_list();
		//if(isset($_GET['id'])&&!$_GET['id']=='login'&&!$_GET['id']=='reg')
		//{
		//	$list_dbname=$this->data['list_dbname']=$this->login_model->list_dbname($_GET['id']);
		//}
	//	$this->parser->parse('include/header',$this->data);
		$this->load->view('application_login',$this->data);
		//$this->parser->parse('include/footer_dashboard',$this->data);
	}

	/* Function for rest api demo .....................................................................*/
	function restapiDemo()
	{
		$this->load->view('restapiDemo',$this->data);
	}

	/* Function for login Application List.....................................................................*/
	function application_list()
	{
		$app_list=$this->data['app_list']=$this->login_model->app_list();
		if(isset($_GET['id'])&&!$_GET['id']=='login'&&!$_GET['id']=='reg')
		{
			$list_dbname=$this->data['list_dbname']=$this->login_model->list_dbname($_GET['id']);
		}
		$this->parser->parse('include/header',$this->data);
		$this->load->view('application_list',$this->data);
		$this->parser->parse('include/footer_dashboard',$this->data);
	}

	/* Function For registration Application view for new organization.......................................................*/
	function registration_application()
	{
	$app_list=$this->data['app_list']=$this->login_model->app_list($_GET['id']);

		$this->parser->parse('include/header',$this->data);
		$this->load->view('registration_application',$this->data);
		$this->parser->parse('include/footer',$this->data);

	}

	/* function for activate account with help of mail  */
	function activate_org($id=false,$codeid=false,$name=false)
	{
		$activate_org=$this->data['activate_org']=$this->login_model->activate_org('registered_application',array('registration_id'=>$id));
		$application_id=$this->data['application_id']=$this->login_model->app_id($id);

		if($activate_org='true' && $application_id='School')
		{
			?><?php
			redirect('http://junctiondev.cloudapp.net/appmanager/login/school'.$name,'refresh');
		}
		else
		{
			?><?php
			redirect('http://junctiondev.cloudapp.net/appmanager','refresh');

		}
	}

		function validation($db_name)
		{
			echo $db_name;
			//$db_name=$_GET['db'];
			//$db_name=str_replace(' ','_',$this->input->post('db_name'));
			$result=$this->data['result']=$this->login_model->validation($db_name);
			if($result)
			{
				echo 'database name already exist';
			}
			else
			{
				echo 'database name not exist';
			}
		}

		/* Function For insert organization and application information diffrent table and server application user table.........................................................*/
	function set_registration_application($parm=false)
	{
		$org_id='';
		$org_name=$this->input->post('organization_name');
		$email=$this->input->post('email');
		$username=$this->input->post('username');
		$db_name=str_replace(' ','_',$this->input->post('db_name'));
		//$url=$this->input->post('app_url').$this->input->post('app_reg_fun');
		$url='http://junctiondev.cloudapp.net/sms/user_management/clone_db';
		if($db_name)
		{
			if(isset($org_id) && $org_id=='')
			{
				$data=array(
							'organization_name'=>$this->input->post('organization_name'),
							'name'=>$this->input->post('name'),
							'email'=>$this->input->post('email'),
							'mobile'=>$this->input->post('mobile'),
							'address'=>$this->input->post('address'),
							'Username'=>$this->input->post('username'),
							'password'=>md5($this->input->post('password')),
							'Terms'=>$this->input->post('terms'),
							'status'=>'active',
							'created_by'=>$this->input->post('name'),
							'created_on'=>date("Y-m-d")
						   );
				// variable name take org_id because org_id also avilabe and put same variable name so its easy otherwise condition put into $data_registered_app array in org_id variable with condition
				//print_r($data);return;die;
				$org_id=$this->data['set_new_user']=$this->login_model->set_registration_application('organizations',$data); // insert data into organization table

				if($org_id)
				{
					$data=array(
							'organization_id'=>$org_id,
							'organization_name'=>$this->input->post('organization_name'),
							'organization_admin_UserName'=>$this->input->post('username'),
							'organization_admin_password'=>$this->input->post('password'),
							'organization_admin_mobile'=>$this->input->post('mobile'),
							'organization_admin_email'=>$this->input->post('email'),
							'application_id'=>$this->input->post('application_name'),
							'application_admin_name'=>$this->input->post('application_admin_name'),
							'application_admin_username'=>$this->input->post('application_username'),
							'application_admin_password'=>$this->input->post('application_password'),
							'application_admin_email'=>$this->input->post('application_email'),
							'application_admin_mobile'=>$this->input->post('application_mobile'),
							'db_name'=>trim($db_name),
							'url'=>$url
					);
					$json=json_encode($data);///echo $json; return;
					$this->org_admin_registration_application($json);
					//redirect('http://junctiondev.cloudapp.net/appmanager/login/org_admin_registration_application?data='.$json);
				}

			}

		}

	}

	/* function for registration application............................................................................*/
	function org_admin_registration_application($json)
	{
		if(isset($json) && $json!=='')
		{
			$data=json_decode($json);//echo 'junction';print_r($data);return;die;
		}
		else
		{ 	//return;
			//$url=$this->input->post('app_url').$this->input->post('app_reg_fun');
			$url='http://junctiondev.cloudapp.net/sms/user_management/clone_db';
			$array=array(
							'organization_id'=>$this->input->post('organization_id'),
							'organization_name'=>$this->input->post('organization_name'),
							'organization_admin_email'=>$this->input->post('organization_admin_email'),
							'application_id'=>$this->input->post('application_id'),
							'application_admin_name'=>$this->input->post('application_admin_name'),
							'application_admin_email'=>$this->input->post('application_admin_email'),
							'application_admin_mobile'=>$this->input->post('application_mobile'),
							'application_admin_username'=>$this->input->post('application_username'),
							'application_admin_password'=>$this->input->post('application_password'),
							'db_name'=>trim(str_replace(' ','_',$this->input->post('db_name'))),
							'url'=>$url,
						);
			$json=json_encode($array);
			$data=json_decode($json);
		}
		$data_registered_app=array(
				'organization_id'=>$data->organization_id,
				'application_id'=>$data->application_id,
				'name'=>$data->application_admin_name,
				'Username'=>$data->application_admin_username,
				'password'=>md5($data->application_admin_password),
				'email'=>$data->application_admin_email,
				'mobile'=>$data->application_admin_mobile,
				'db_name'=>$data->db_name,
				'status'=>'suspend',
				'created_by'=>$data->application_admin_name,
				'created_on'=>date("Y-m-d")
		);
		$set_new_user=$this->data['set_new_user']=$this->login_model->set_registration_application('registered_application',$data_registered_app);
		/* Create Array For convert into json and send data for application servar */
		$data_user=array(
				'registration_id'=>$set_new_user,
				'organization_id'=>$data->organization_id,
				'organization_name'=>$data->organization_name,
				'organization_admin_UserName'=>$data->organization_admin_UserName,
				'organization_admin_password'=>$data->organization_admin_password,
				'organization_admin_mobile'=>$data->organization_admin_mobile,
				'organization_admin_email'=>$data->organization_admin_email,
				'application_id'=>$data->application_id,
				'application_admin_email'=>$data->application_admin_email,
				'application_admin_mobile'=>$data->application_admin_mobile,
				'application_admin_username'=>$data->application_admin_username,
				'application_admin_password'=>$data->application_admin_password,
				'db_name'=>$data->db_name,
				'UserType'=>'masteruser'
		);
		$json= json_encode($data_user);// create json for sending purpose
		echo $json;die;
		//redirect($data->url.'?data='.$json);
		//$this->clone_db($json);
	}

	function clone_db($json_data)
	{
	 	$var=json_decode($json_data);
		$database_name=$var->db_name;
		$this->session->set_userdata('db_name',$database_name);
	//	$this->session->userdata('db_name');
	$set_users=$this->data['set_users']=$this->login_model->clone_db($database_name);

				$ch2=curl_init();
				$url2 = "http://junctiondev.cloudapp.net/appmanager/login/set_user";
		  /**
		   * For https, there are more options that you must define, these you can get from php.net
		   */
		  curl_setopt($ch2,CURLOPT_URL,$url2);
		  curl_setopt($ch2,CURLOPT_POST, true);
		  curl_setopt($ch2,CURLOPT_POSTFIELDS, http_build_query(array(
													'json_data'=>$json_data,
												)));
		  curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, true);
		  curl_setopt($ch2,CURLOPT_RETURNTRANSFER, true);
		  curl_setopt($ch2, CURLOPT_FRESH_CONNECT, true);
		  curl_setopt($ch2, CURLOPT_CUSTOMREQUEST, "POST");
		  curl_setopt($ch2,CURLOPT_CONNECTTIMEOUT ,30); //timeout in seconds
		  curl_setopt($ch2,CURLOPT_TIMEOUT, 30); // same for here. Timeout in seconds.
		  $response2 = curl_exec($ch2);

		  curl_close ($ch2); //close curl handle
			echo  $response2;

	//

		//$this->set_user($json_data);
		//redirect('http://junctiondev.cloudapp.net/sms/user_management/set_user?data='.$json_data);
	}

	/* function for clone db with in registration time */
	function set_user()
	{	//echo $this->input->post('json_data');//die;
		//$json_data=$_GET['data'];
		//echo $json_data;
		$json_data=$this->input->post('json_data');
		$var=json_decode($json_data);
		$data=array(
					'Username'=>$var->application_admin_username,
					'Password'=>md5($var->application_admin_password),
					'UserType'=>$var->UserType,
				   );
		$status=$this->login_model->set_user($data);//return;
		if($status)
		{
			$data=array(
							'organization_id'=>$var->organization_id,
							'registration_id'=>$var->registration_id,
							'organization_name'=>$var->organization_name,
							'organization_admin_email'=>$var->organization_admin_email,
							'organization_admin_UserName'=>$var->organization_admin_UserName,
							'organization_admin_password'=>$var->organization_admin_password,
							'organization_admin_mobile'=>$var->organization_admin_mobile,
							'application_admin_email'=>$var->application_admin_email,
							'application_admin_username'=>$var->application_admin_username,
							'application_admin_password'=>$var->application_admin_password,
							'application_admin_mobile'=>$var->application_admin_mobile,
							'database_name'=>$var->db_name,
							'code'=>'200',
						);
			//$database_name=$this->session->userdata('db_name');
			//$this->session->unset_userdata($database_name);
			//$this->session->sess_destroy();
			$datas=json_encode($data);
			$this->result_application($datas);
			//redirect('http://junctiondev.cloudapp.net/appmanager/login/result_application?json='.$datas);
			//redirect('http://junctiondev.cloudapp.net/appmanager/login/result_application');
		}
		else
		{
			$this->result_application();
			//redirect('http://junctiondev.cloudapp.net/appmanager/login/application_login?id=login');
		}
	}

	/* function for check organization information is already exist in database .......................................................*/
	function verification_new_user()
	{
		$val= $this->input->post('val');
		$field_name= $this->input->post('field_name');
		$check_org=$this->data['check_org']=$this->login_model->verification_new_user($val,$field_name);
		if($check_org)
		{
			if($check_org && $field_name!=='Database name'){
			?>
				 Your <?=$field_name; ?> Already Exist If you want to used same organization for new Application Please Login then registered for Application <?=$field_name; ?>
			<?php
			}
			if($check_org && $field_name=='Database name')
			{
				?>
					 Your <?=$field_name; ?> Already Exist Please Try With Another Unique organisation key
				<?php
			}
		}
	}

/* Function for user login for his application to verify all detail central server and application server.....................................................................................*/
	function login_function()
	{	//print_r($_POST['json']);die;
		if(isset($_POST) && isset($_POST['json'])==''){
			$json=$_POST;
			$data=json_encode($json);
			$value=json_decode($data);
		}
		else
		{
			$json=$_POST['json'];
			$value=json_decode($json);
			$url_name=$value->device;

		}
		if(isset($_SERVER['HTTP_REFERER']) && isset($value->device)!=='')
		{
			$url_name=$_SERVER['HTTP_REFERER'];// take and save in which url user login for application
		}
			if(!$value->db_name)                    //Super Admin Case if login into Application
			{
				if('admin'==$this->input->POST('username') && 'admin'==$this->input->post('password'))
				{
					$this->session->set_userdata(array('username'=>'admin'));
					$this->session->userdata('username');
				}
			}
			elseif($value->db_name)
			{
				$app_info=$this->login_model->login('registered_application',array('db_name'=>$value->db_name));
				if($app_info)
				{
					$status_org_info=$this->login_model->login('organizations',array('organization_id'=>$app_info[0]->organization_id));   // hear check organization status is active or not
					$app_url_info=$this->login_model->login('applications',array('application_id'=>$app_info[0]->application_id));		  // get application url and redirect into server
					if($status_org_info[0]->status=='active')
					{
						if($app_info[0]->status=='active')  // check status application active or not
						{
							$explode=explode("@",$value->username);
							if(count($explode)>= 2)
							{
								$data=array(
												'url'=>$url_name,
												'database_name'=>$value->db_name,
												'username'=>$value->username,
												'password'=>$value->password,
												'organization_id'=>$status_org_info[0]->organization_id,
												'organization_name'=>str_replace(' ','_',$status_org_info[0]->organization_name),
										    );
							}
							else
							{
								$data=array(
										'url'=>$url_name,
										'database_name'=>$value->db_name,
										'username'=>$value->username,
										'password'=>md5($value->password),
										'organization_id'=>$status_org_info[0]->organization_id,
										'organization_name'=>str_replace(' ','_',$status_org_info[0]->organization_name),
								);
							}
							$value=json_encode($data);
							$url=$app_url_info[0]->application_url.$app_url_info[0]->login_function;
							redirect($url.'?json='.$value);
						}
						else
						{
							if(isset($value->device) && $value->device=='androide')
							{
								$data=array(
										'code'=>'400',
										'status'=>'error',
										'result'=>'Your Application Not Active',
								);

								echo json_encode($data);die;
							}
							?><?php
								//echo 'not active organization';
							redirect($url_name,'refresh');
						}
					}
					else
					{
						if(isset($value->device) && $value->device=='androide')
						{
							$data=array(
									'code'=>'400',
									'status'=>'error',
									'result'=>'Your Application Not Active',
							);

							echo json_encode($data);die;
						}
						// todo hear msg show if Organization suspend by super admin then redirect
						?><?php
						//echo 'not active organization';
						redirect($url_name,'refresh');

					}
				}
				else
				{
					?><?php
					redirect($url_name,'refresh');
				}
			}
			else
			{

			}

	}

	/* Function For Application Result Show Message If Success Or Not */
	function result_application()
	{	echo "appmanager final response"; return; die;
		echo $_GET['json'];
		return;die;
		$json=json_decode($_GET['json']);
		if(isset($json->code) && $json->code=='500')
		{
			$result=$this->login_model->result_application($json->organization_id);
			if($result)
			{
				?><?php
				redirect('http://junctiondev.cloudapp.net/appmanager','refresh');
			}
		}
		if(isset($json->code)&& $json->code=='200')
		{	$application_id=$this->data['application_id']=$this->login_model->app_id($json->registration_id);

			$json=json_decode($_GET['json']);
			$code_application_id=md5($json->registration_id);
			$subject="Zero ERP:-  Please Activate Your Account ";
			$message= "
Hello:  Organization Administrator

 Your Organization is Successfully Registered Some Important Details Are
 Organization Name:- $json->organization_name
 Database Name-: $json->database_name
  User Name-: $json->organization_admin_UserName
 Password:- $json->organization_admin_password
 Mobile:-  $json->organization_admin_mobile

Please Click In This Link And Activate Your Account  :)

 http://junctiondev.cloudapp.net/appmanager/login/activate_org/$json->registration_id/$code_application_id/$json->organization_name
";
			$name='Junction Software Pvt Ltd';
			/*
			 This example shows settings to use when sending via Google's Gmail servers.
			 */

			//SMTP needs accurate times, and the PHP time zone MUST be set
			//This should be done in your php.ini, but this is how to do it if you don't have access to that
			date_default_timezone_set('Etc/UTC');

			require 'PHPMailer/PHPMailerAutoload.php';

			//Create a new PHPMailer instance
			$mail = new PHPMailer;

			//Tell PHPMailer to use SMTP
			$mail->isSMTP();

			//Enable SMTP debugging
			// 0 = off (for production use)
			// 1 = client messages
			// 2 = client and server messages
			$mail->SMTPDebug = 0;

			//Ask for HTML-friendly debug output
			$mail->Debugoutput = 'html';

			//Set the hostname of the mail server
			$mail->Host = 'smtp.gmail.com';

			//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
			$mail->Port = 587;

			//Set the encryption system to use - ssl (deprecated) or tls
			$mail->SMTPSecure = 'tls';

			//Whether to use SMTP authentication
			$mail->SMTPAuth = true;

			//Username to use for SMTP authentication - use full email address for gmail
			$mail->Username = "dev4junction@gmail.com";

			//Password to use for SMTP authentication
			$mail->Password = 'initial1$';

			//Set who the message is to be sent from
			$mail->setFrom($json->organization_admin_email,$name);

			//Set an alternative reply-to address
			$mail->addReplyTo('dev4junction@gmail.com', $name);

			//Set who the message is to be sent to
			$mail->addAddress($json->organization_admin_email);

			//Set the subject line
			$mail->Subject = $subject;

			//Read an HTML message body from an external file, convert referenced images to embedded,
			//convert HTML into a basic plain-text alternative body
			$mail->msgHTML($message);

			//Replace the plain text body with one created manually
			$mail->AltBody = 'This is a plain-text message body';

			//Attach an image file
			//$mail->addAttachment($uploadfile,$filename);

			//send the message, check for errors

			if (!$mail->send())
			{
				print "We encountered an error sending your mail";

			}
			elseif($application_id='School')
			{
			$subjects=" Zero ERP :- Your Application Registered Successfully ";
				$messages= "
Hello: Application Administrator

Your Application is Successfully Registered Some Important Details Are
 Organization Name:- $json->organization_name
 User Name:- $json->application_admin_username
 Password:- $json->application_admin_password
  Database Name:- $json->database_name
 Mobile Number:- $json->application_admin_mobile

Please Click In This Link And Login With Use Of Those Userid, Password And Database :)
'http://junctiondev.cloudapp.net/appmanager/login/school/$json->organization_name'
";
				$names='Junction Software Pvt Ltd';

				/*
				 This example shows settings to use when sending via Google's Gmail servers.
				 */

				//SMTP needs accurate times, and the PHP time zone MUST be set
				//This should be done in your php.ini, but this is how to do it if you don't have access to that
				//	date_default_timezone_set('Etc/UTC');

				//require 'PHPMailer/PHPMailerAutoload.php';

				//Create a new PHPMailer instance
				//$mail = new PHPMailer;

				//Tell PHPMailer to use SMTP
				//$mail->isSMTP();

				//Enable SMTP debugging
				// 0 = off (for production use)
				// 1 = client messages
				// 2 = client and server messages
				//$mail->SMTPDebug = 0;

				//Ask for HTML-friendly debug output
				//	$mail->Debugoutput = 'html';

				//Set the hostname of the mail server
				//$mail->Host = 'smtp.gmail.com';

				//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
				//	$mail->Port = 587;

				//Set the encryption system to use - ssl (deprecated) or tls
				//$mail->SMTPSecure = 'tls';

				//Whether to use SMTP authentication
				//$mail->SMTPAuth = true;

				//Username to use for SMTP authentication - use full email address for gmail
				//$mail->Username = "dev4junction@gmail.com";

				//Password to use for SMTP authentication
				//	$mail->Password = 'initial1$';

				//Set who the message is to be sent from
				$mail->setFrom($json->application_admin_email,$names);

				//Set an alternative reply-to address
				$mail->addReplyTo('dev4junction@gmail.com', $names);

				//Set who the message is to be sent to
				$mail->addAddress($json->application_admin_email);

				//Set the subject line
				$mail->Subject = $subjects;

				//Read an HTML message body from an external file, convert referenced images to embedded,
				//convert HTML into a basic plain-text alternative body
				$mail->msgHTML($messages);

				//Replace the plain text body with one created manually
				$mail->AltBody = 'This is a plain-text message body';

				//Attach an image file
				//$mail->addAttachment($uploadfile,$filename);

				//send the message, check for errors

				if (!$mail->send())
				{
					print "We encountered an error sending your mail";

				}
				elseif($application_id='School')
				{
					?><?php
					redirect('http://junctiondev.cloudapp.net/appmanager/login/school/'.$json->organization_name,'refresh');
				}
				else{
					?><?php
					redirect('http://junctiondev.cloudapp.net/appmanager/','refresh');
				}
			}

			else
			{
				$subjects=" Zero ERP :- Your Application Registered Successfully ";
				$messages= "
Hello: Application Administrator

Your Application is Successfully Registered Some Important Details Are
 Organization Name:- $json->organization_name
 User Name:- $json->application_admin_username
 Password:- $json->application_admin_password
  Database Name:- $json->database_name
 Mobile Number:- $json->application_admin_mobile

Please Click In This Link And Login With Use Of Those Userid, Password And Database :)

				'http://junctiondev.cloudapp.net/appmanager/login/school/$json->organization_name'
";
				$names='Junction Software Pvt Ltd';

				/*
				 This example shows settings to use when sending via Google's Gmail servers.
				 */

				//SMTP needs accurate times, and the PHP time zone MUST be set
				//This should be done in your php.ini, but this is how to do it if you don't have access to that
				//	date_default_timezone_set('Etc/UTC');

				//require 'PHPMailer/PHPMailerAutoload.php';

				//Create a new PHPMailer instance
				//$mail = new PHPMailer;

				//Tell PHPMailer to use SMTP
				//$mail->isSMTP();

				//Enable SMTP debugging
				// 0 = off (for production use)
				// 1 = client messages
				// 2 = client and server messages
				//$mail->SMTPDebug = 0;

				//Ask for HTML-friendly debug output
				//	$mail->Debugoutput = 'html';

				//Set the hostname of the mail server
				//$mail->Host = 'smtp.gmail.com';

				//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
				//	$mail->Port = 587;

				//Set the encryption system to use - ssl (deprecated) or tls
				//$mail->SMTPSecure = 'tls';

				//Whether to use SMTP authentication
				//$mail->SMTPAuth = true;

				//Username to use for SMTP authentication - use full email address for gmail
				//$mail->Username = "dev4junction@gmail.com";

				//Password to use for SMTP authentication
				//	$mail->Password = 'initial1$';

				//Set who the message is to be sent from
				$mail->setFrom($json->application_admin_email,$names);

				//Set an alternative reply-to address
				$mail->addReplyTo('dev4junction@gmail.com', $names);

				//Set who the message is to be sent to
				$mail->addAddress($json->application_admin_email);

				//Set the subject line
				$mail->Subject = $subjects;

				//Read an HTML message body from an external file, convert referenced images to embedded,
				//convert HTML into a basic plain-text alternative body
				$mail->msgHTML($messages);

				//Replace the plain text body with one created manually
				$mail->AltBody = 'This is a plain-text message body';

				//Attach an image file
				//$mail->addAttachment($uploadfile,$filename);

				//send the message, check for errors

				if (!$mail->send())
				{
					print "We encountered an error sending your mail";

				}
				elseif($application_id='School')
				{
					?><?php
					redirect('http://junctiondev.cloudapp.net/appmanager/login/school/$json->organization_name','refresh');
				}
				else{
					?><?php
					redirect('http://junctiondev.cloudapp.net/appmanager/','refresh');
				}
			}
		}
	}

	/* function for logout for admin dashboard...........................................................................*/
	function logout()
	{
		$url=$this->session->userdata('url');
		$this->data['user_data']=$this->session->userdata('user_data');
		$userdata=$this->session->userdata('user_data');
		$unset_userdata=$this->session->unset_userdata($userdata);
		$this->session->sess_destroy();
		redirect('login');
	}

	function reset_password_view()
	{
		$this->parser->parse('include/header',$this->data);
		$this->load->view('reset_password',$this->data);
	}
	function school($schoolname=false)
	{

		//if(!empty($schoolname)){

		//$this->session->set_userdata('schoolname',$schoolname);

		//$school_info=$this->data['schoolinfo']=$this->login_model->schoolinfo();

		//}
		$school_detail=$this->data['schooldetail']=$this->login_model->schooldetail($schoolname);

		$this->parser->parse('include/header',$this->data);
		$this->load->view('school',$this->data);
		$this->parser->parse('include/footer',$this->data);
	}
	function reset_password()
	{
		$UserEmail=$this->input->post('usermailid');
		$choose_application=$this->input->post('panel');
		$code=substr(md5(microtime()),rand(0,26),5);
		if($choose_application=='org_admin')
		{
			$EmailOrg=$this->login_model->get_reset_password('organizations',array('email'=>$UserEmail));
			if($EmailOrg)
			{
				$id='Organization';
				$updatePassword=$this->login_model->set_reset_password('organizations',array('email'=>$UserEmail),array('password'=>$code));
			}
			else
			{
				?><?php
				 redirect('http://junctiondev.cloudapp.net/appmanager','refresh');
			}
		}
		else
		{
			$EmailRegApp=$this->login_model->set_reset_password('registered_application',array('email'=>$UserEmail));
			if($EmailRegApp)
			{
				$id='Application';
				$updatePassword=$this->login_model->set_reset_password('registered_application',array('email'=>$UserEmail),array('password'=>$code));
			}
			else
			{
				  ?><?php
				  redirect('http://junctiondev.cloudapp.net/appmanager','refresh');
			}
		}
		if($updatePassword)
		{
			$subject=" Zero Erp:- Reset Your Password ";
			$message= "
Hello: $id Administrator

 Please Use This Temporary Password And Reset Your Password
 Temporary Password:- $code

Please Click In This Link And Update Your Password   :)

 http://junctiondev.cloudapp.net/appmanager/login/reset_confirm_password/$id
";
			$name='Junction Software Pvt Ltd';
			/*
			 This example shows settings to use when sending via Google's Gmail servers.
			 */
			//SMTP needs accurate times, and the PHP time zone MUST be set
			//This should be done in your php.ini, but this is how to do it if you don't have access to that
			date_default_timezone_set('Etc/UTC');

			require 'PHPMailer/PHPMailerAutoload.php';

			//Create a new PHPMailer instance
			$mail = new PHPMailer;

			//Tell PHPMailer to use SMTP
			$mail->isSMTP();

			//Enable SMTP debugging
			// 0 = off (for production use)
			// 1 = client messages
			// 2 = client and server messages
			$mail->SMTPDebug = 0;

			//Ask for HTML-friendly debug output
			$mail->Debugoutput = 'html';

			//Set the hostname of the mail server
			$mail->Host = 'smtp.gmail.com';

			//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
			$mail->Port = 587;

			//Set the encryption system to use - ssl (deprecated) or tls
			$mail->SMTPSecure = 'tls';

			//Whether to use SMTP authentication
			$mail->SMTPAuth = true;

			//Username to use for SMTP authentication - use full email address for gmail
			$mail->Username = "dev4junction@gmail.com";

			//Password to use for SMTP authentication
			$mail->Password = 'initial1$';

			//Set who the message is to be sent from
			$mail->setFrom($UserEmail,$name);

			//Set an alternative reply-to address
			$mail->addReplyTo('dev4junction@gmail.com', $name);

			//Set who the message is to be sent to
			$mail->addAddress($UserEmail);

			//Set the subject line
			$mail->Subject = $subject;

			//Read an HTML message body from an external file, convert referenced images to embedded,
			//convert HTML into a basic plain-text alternative body
			$mail->msgHTML($message);

			//Replace the plain text body with one created manually
			$mail->AltBody = 'This is a plain-text message body';

			//Attach an image file
			//$mail->addAttachment($uploadfile,$filename);

			//send the message, check for errors
			if (!$mail->send())
			{
				print "We encountered an error sending your mail";

			}
				?><?php
				redirect('http://junctiondev.cloudapp.net/appmanager','refresh');
		}
		else
		{
			?><?php
			 redirect('http://junctiondev.cloudapp.net/appmanager','refresh');
		}

	}

	function reset_confirm_password($id=false)
	{
		$this->data['id']=$id;// check id mens application or organization is print or not
		$this->parser->parse('include/header',$this->data);
		$this->load->view('reset_confirm_password',$this->data);
	}

	function UpdatePassword()
	{
		$id=$this->input->post('id');
		if($id=='Application')
		{
			$Emailapp=$this->login_model->get_reset_password('registered_application',array('email'=>$this->input->post('useremailid'),'password'=>$this->input->post('temp_password')));
			if($Emailapp)
			{
				$updatePassword=$this->login_model->set_reset_password('registered_application',array('email'=>$this->input->post('useremailid')),array('password'=>md5($this->input->post('new_password'))));
				if($updatePassword)
				{
					?>  <?php
					redirect('http://junctiondev.cloudapp.net/appmanager','refresh');
				}
			}
		}
		else
		{
			$EmailOrg=$this->login_model->get_reset_password('organizations',array('email'=>$this->input->post('useremailid'),'password'=>$this->input->post('temp_password')));
			if($EmailOrg)
			{
				$updatePassword=$this->login_model->set_reset_password('organizations',array('email'=>$this->input->post('useremailid')),array('password'=>md5($this->input->post('new_password'))));
				if($updatePassword)
				{
					?>  <?php
						redirect('http://junctiondev.cloudapp.net/appmanager','refresh');
				}
			}
		}
	}
}


text:
package com.thoughtworks.studios.shine.cruise;

import java.io.File;
import java.util.Date;

import com.thoughtworks.go.config.GoConfigFileDao;
import com.thoughtworks.go.config.materials.ScmMaterial;
import com.thoughtworks.go.domain.Pipeline;
import com.thoughtworks.go.domain.Stage;
import com.thoughtworks.go.domain.StageFinder;
import com.thoughtworks.go.domain.StageResult;
import com.thoughtworks.go.domain.feed.stage.StageFeedEntry;
import com.thoughtworks.go.domain.materials.Modification;
import com.thoughtworks.go.server.dao.DatabaseAccessHelper;
import com.thoughtworks.go.server.dao.sparql.TestFailureSetup;
import com.thoughtworks.go.server.domain.PipelineTimeline;
import com.thoughtworks.go.server.domain.xml.JobXmlViewModel;
import com.thoughtworks.go.server.domain.xml.PipelineXmlViewModel;
import com.thoughtworks.go.server.domain.xml.StageXmlViewModel;
import com.thoughtworks.go.server.persistence.MaterialRepository;
import com.thoughtworks.go.server.service.ArtifactsService;
import com.thoughtworks.go.server.service.JobInstanceService;
import com.thoughtworks.go.server.service.PipelineHistoryService;
import com.thoughtworks.go.server.service.PipelineInstanceLoader;
import com.thoughtworks.go.server.service.PropertiesService;
import com.thoughtworks.go.server.service.StageService;
import com.thoughtworks.go.server.service.XmlApiService;
import com.thoughtworks.go.server.transaction.TransactionTemplate;
import com.thoughtworks.go.util.GoConfigFileHelper;
import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.util.TempFiles;
import com.thoughtworks.studios.shine.cruise.stage.details.StageResourceImporter;
import com.thoughtworks.studios.shine.cruise.stage.details.StageStorage;
import com.thoughtworks.studios.shine.semweb.Graph;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
        "classpath:WEB-INF/applicationContext-global.xml",
        "classpath:WEB-INF/applicationContext-dataLocalAccess.xml",
        "classpath:WEB-INF/applicationContext-acegi-security.xml"
})
public class BackgroundStageLoaderIntegrationTest {

    private StageStorage stageStorage;
    private TempFiles tempFiles;
    private BackgroundStageLoader loader;
    private StageFinder stageFinder;
    private PipelineInstanceLoader pipelineInstanceLoader;

    private GoConfigFileHelper configHelper = new GoConfigFileHelper();

    @Autowired private StageService stageService;
    @Autowired private PipelineHistoryService pipelineHistoryService;
    @Autowired private MaterialRepository materialRepository;
    @Autowired private GoConfigFileDao goConfigFileDao;
    @Autowired private PropertiesService propertiesService;
    @Autowired private ArtifactsService artifactsService;
    @Autowired private JobInstanceService jobInstanceService;
    @Autowired private XmlApiService xmlApiService;
    @Autowired private TransactionTemplate transactionTemplate;
    @Autowired private SystemEnvironment systemEnvironment;

    @Autowired private DatabaseAccessHelper dbHelper;

    @Autowired private PipelineTimeline pipelineTimeline;
    private TestFailureSetup failureSetup;

    @Before
    public void setUp() throws Exception {
        dbHelper.onSetUp();
        tempFiles = new TempFiles();
        File tempFolder = tempFiles.createUniqueFolder("shine");
        stageStorage = new StageStorage(tempFolder.getAbsolutePath());
        stageStorage.clear();
        stageFinder = stageService;
        pipelineInstanceLoader = pipelineHistoryService;
        StageResourceImporter importer = new StageResourceImporter("/artifacts", xmlApiService, stageFinder, pipelineInstanceLoader,systemEnvironment);
        loader = new BackgroundStageLoader(null, importer, stageStorage, pipelineHistoryService, stageService, systemEnvironment );
        configHelper.usingCruiseConfigDao(goConfigFileDao);
        configHelper.onSetUp();

        failureSetup = new TestFailureSetup(materialRepository, dbHelper, pipelineTimeline, configHelper, transactionTemplate);
    }

    @After
    public void tearDown() throws Exception {
        tempFiles.cleanUp();
        configHelper.onTearDown();
        dbHelper.onTearDown();
    }

    @Test
    public void willNotHandleWhenStageAlreadyImported() {
        TestFailureSetup.SavedStage savedStage = failureSetup.setupPipelineInstanceWithoutTestXmlStubbing(true, null, new Date());

        assertFalse(loader.shouldStopHandling(feedEntry(savedStage)));
        loader.handle(feedEntry(savedStage), pipelineInstanceLoader);
        assertTrue(loader.shouldStopHandling(feedEntry(savedStage)));
    }

    private StageFeedEntry feedEntry(TestFailureSetup.SavedStage stage) {
        return new StageFeedEntry(stage.stage.getId(), stage.pipeline.getId(), stage.stageId, stage.stage.getId(), stage.stage.latestTransitionDate(), StageResult.Failed);
    }

    @Test
    public void willNotHandleWhenStageCompletedBeforeOneWeek() {
        TestFailureSetup.SavedStage savedStage = failureSetup.setupPipelineInstanceWithoutTestXmlStubbing(true, null, new DateTime().minusDays(8).toDate());

        assertTrue(loader.shouldStopHandling(feedEntry(savedStage)));
        assertFalse(stageStorage.isStageStored(savedStage.stageId));
    }

    @Test
    public void handleAStageURLNotYetSeenShouldStoreStageResourceIntoStageStorage() {
        TestFailureSetup.SavedStage savedStage = failureSetup.setupPipelineInstanceWithoutTestXmlStubbing(true, null, new Date());

        loader.handle(feedEntry(savedStage), pipelineInstanceLoader);
        assertTrue(stageStorage.isStageStored(savedStage.stageId));

        Graph storedGraph = stageStorage.load(savedStage.stageId);
        Stage stage = savedStage.stage;
        String baseUrl = "https://localhost:8154/go";
        String jobUrl = new JobXmlViewModel(stage.getJobInstances().first()).httpUrl(baseUrl);

        assertTrue(storedGraph.containsResourceWithURI(jobUrl));
        assertTrue(storedGraph.containsResourceWithURI(new StageXmlViewModel(stage).httpUrl(baseUrl)));
        Pipeline pipeline = savedStage.pipeline;
        assertTrue(storedGraph.containsResourceWithURI(PipelineXmlViewModel.httpUrlForPipeline(baseUrl, pipeline.getId(), pipeline.getName())));
        Modification latestModification = pipeline.getMaterialRevisions().getRevisions().get(0).getLatestModification();
        assertTrue(storedGraph.containsResourceWithURI(ScmMaterial.changesetUrl(latestModification, baseUrl, latestModification.getMaterialInstance().getId())));
    }

    @Test
    public void stageWithInvalidPipelineFeedShouldNotSaveStageToStageStorage() {
        TestFailureSetup.SavedStage stage = failureSetup.setupPipelineInstanceWithoutTestXmlStubbing(true, null, new Date());
        pipelineInstanceLoader = mock(PipelineInstanceLoader.class);
        when(pipelineInstanceLoader.loadPipelineForShine(anyLong())).thenThrow(new RuntimeException("ouch, that hurt!"));

        StageResourceImporter importer = new StageResourceImporter("/artifacts", xmlApiService, stageFinder, pipelineInstanceLoader,systemEnvironment);

        loader = new BackgroundStageLoader(null, importer, stageStorage, pipelineHistoryService, stageService, systemEnvironment);

        try {
            loader.handle(feedEntry(stage), pipelineInstanceLoader);
            fail("should have failed as pipeline load bombed");
        } catch (Exception e) {
            //expected
        }
        assertFalse(stageStorage.isStageStored(stage.stageId));
    }

    @Test
    public void stageWithInvalidJobPropertiesShouldNotSaveStageToStageStorage() {
        PropertiesService propertiesService = mock(PropertiesService.class);
        when(propertiesService.getPropertiesForJob(anyLong())).thenThrow(new RuntimeException("something bad happened"));

        xmlApiService = new XmlApiService(propertiesService, artifactsService, jobInstanceService, stageService);
        StageResourceImporter importer = new StageResourceImporter("/artifacts", xmlApiService, stageFinder, pipelineInstanceLoader,systemEnvironment);
        loader = new BackgroundStageLoader(null, importer, stageStorage, pipelineHistoryService, stageService, systemEnvironment);
        TestFailureSetup.SavedStage stage = failureSetup.setupPipelineInstanceWithoutTestXmlStubbing(true, null, new Date());

        try {
            loader.handle(feedEntry(stage), pipelineInstanceLoader);
            fail("should have failed as properties api bombed");
        } catch(Exception e) {
            //expected
        }
        assertFalse(stageStorage.isStageStored(stage.stageId));
    }

}


text:
[![Latest Version on Packagist][ico-version]][link-packagist]
[![Software License][ico-license]](LICENSE.md)
[![Build Status][ico-travis]][link-travis]
[![Coverage Status][ico-scrutinizer]][link-scrutinizer]
[![Quality Score][ico-code-quality]][link-code-quality]
[![Total Downloads][ico-downloads]][link-downloads]

Fancy internal Domain Specific Languages (DSL) to write SQL Selects by a
[Fluent interface][link-fluent-interface] implementation. It builds great SQL tasks dynamically. Return
a Select statement from chain of responsibilities pattern based source and
"with" methods to cover all paths of the select. Main responsibility of that
package is have all common select keywords well positioned. Besides select
keywords, there are: List of columns that are represented by arrays of data.
And logical operations that are represented by strings of information.

## Install

Via Composer

```json
"repositories": [
    {
        "type": "git",
        "url": "https://github.com/martiadrogue/sqlbuilder.git"
    }
],
"require": {
    "martiadrogue/sqlbuilder": "dev-devel"
},
```

Old school, grab files from [dist directory][link-download]

## Usage

```php
$selectBuilder = new MartiAdrogue\SelectBuilder();
echo $selectBuilder->select(['col1', 'col2', 'col3'])
         ->from('table')
         ->where('col1 = \'lorem ipsum dolor sit amen\'')
         ->limit(20);
```

To a deep usage explanation run

```bash
phpunit --testdox
```

## Change log

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed
recently.

## Testing

```bash
composer test
```

## Contributing

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CONDUCT](CONDUCT.md) for
details.

## Security

If you discover any security related issues, please email
marti.adrogue@gmail.com instead of using the issue tracker.

## Credits

-   [Martí Adrogué][link-author]
-   [All Contributors][link-contributors]

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more
information.

**Build with steel and thunder!**

[ico-version]: https://img.shields.io/packagist/v/martiadrogue/sqlbuilder.svg?style=flat-square
[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
[ico-travis]: https://img.shields.io/travis/martiadrogue/sqlbuilder/master.svg?style=flat-square
[ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/martiadrogue/sqlbuilder.svg?style=flat-square
[ico-code-quality]: https://img.shields.io/scrutinizer/g/martiadrogue/sqlbuilder.svg?style=flat-square
[ico-downloads]: https://img.shields.io/packagist/dt/martiadrogue/sqlbuilder.svg?style=flat-square

[link-packagist]: https://packagist.org/packages/martiadrogue/sqlbuilder
[link-travis]: https://travis-ci.org/martiadrogue/sqlbuilder
[link-scrutinizer]: https://scrutinizer-ci.com/g/martiadrogue/sqlbuilder/code-structure
[link-code-quality]: https://scrutinizer-ci.com/g/martiadrogue/sqlbuilder
[link-downloads]: https://packagist.org/packages/martiadrogue/sqlbuilder
[link-author]: https://github.com/martiadrogue
[link-fluent-interface]: https://en.wikipedia.org/wiki/Fluent_interface
[link-contributors]: ../../contributors
[link-download]: https://github.com/martiadrogue/sqlbuilder/archive/master.zip


text:
package com.redinput.datetimepickercompat;

import android.content.Context;
import android.support.v4.view.AccessibilityDelegateCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Button;
import android.widget.LinearLayout;

/**
 * Fake Button class, used so TextViews can announce themselves as Buttons, for accessibility.
 */
public class AccessibleLinearLayout extends LinearLayout {

	public AccessibleLinearLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		installAccessibilityDelegate();
	}

	private void installAccessibilityDelegate() {
		// The accessibility delegate enables customizing accessibility behavior
		// via composition as opposed as inheritance. The main benefit is that
		// one can write a backwards compatible application by setting the delegate
		// only if the API level is high enough i.e. the delegate is part of the APIs.
		// The easiest way to achieve that is by using the support library which
		// takes the burden of checking API version and knowing which API version
		// introduced the delegate off the developer.
		ViewCompat.setAccessibilityDelegate(this, new AccessibilityDelegateCompat() {

			@Override
			public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
				super.onInitializeAccessibilityEvent(host, event);
				// Note that View.onInitializeAccessibilityNodeInfo was introduced in
				// ICS and we would like to tweak a bit the text that is reported to
				// accessibility services via the AccessibilityNodeInfo.
				event.getText().add(Button.class.getName());
			}

			@Override
			public void onInitializeAccessibilityNodeInfo(View host,
					AccessibilityNodeInfoCompat info) {
				super.onInitializeAccessibilityNodeInfo(host, info);
				// Note that View.onInitializeAccessibilityNodeInfo was introduced in
				// ICS and we would like to tweak a bit the text that is reported to
				// accessibility services via the AccessibilityNodeInfo.
				info.setText(Button.class.getName());
			}
		});
	}
}


text:
"""Write a function char_freq() that takes a string and builds
a frequency listing of the characters contained in it. Represent
the frequency listing as a Python dictionary. Try it with something
like char_freq("abbabcbdbabdbdbabababcbcbab")."""

def char_freq(str):
  pass

#test
print(char_freq("abbabcbdbabdbdbabababcbcbab"))
print(char_freq("hello"))


text:
<!doctype html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
  <title>iron-label basic</title>

  <link rel="x-dart-test" href="iron_label_basic_test.dart">

  <template id="TrivialWrapper">
    <iron-label>
      Label
      <input type="text">
    </iron-label>
  </template>

  <template id="MultiElementWrapper">
    <iron-label>
      Label
      <input iron-label-target type="text">
    </iron-label>
  </template>

  <template id="ExplicitId">
    <iron-label id="explicit">Label<input type="text"></iron-label>
  </template>

  <template id="TrivialSelector">

      <iron-label for="input">Label</iron-label>
      <input id="input" type="text">

  </template>

  <template id="DynamicLabel">

      <iron-label id="label"><input id="nested">Label</iron-label>
      <input id="one" type="text">

  </template>

  <template id="UniqueIds">
    <iron-label></iron-label>
    <iron-label></iron-label>
  </template>


text:
#include "FormObject.hpp"

class FormLayout : public XMLConfig, public Moveable<FormLayout>
{
	typedef FormLayout CLASSNAME;

	PARAMETER(Rect, PageRect);
	PARAMETER(Vector<FormObject>, Objects);

public:
	FormLayout();

	FormLayout(const FormLayout& other)
	{
		*this <<= other;
	}

	FormLayout& operator<<=(const FormLayout& other)
	{
		WhenProgressBar = other.WhenProgressBar;
		_PageRect  = other.GetPageRect();
		_Objects <<= other.GetObjects();
		Name  = other.Name;
		Path  = other.Path;
		Map <<= other.Map;
		return *this;
	}

	void Clear();
	Size GetFormSize();
	virtual void Xmlize(XmlIO xml);
};

#endif // .. FORM_LAYOUT_HPP


text:
<?xml version="1.0"?>
<entry name="selectable" type="widget" widget-element="selectable element">
	<title>Selectable Widget</title>
	<desc>Use the mouse to select elements, individually or in a group.</desc>
	<longdesc>

The jQuery UI Selectable plugin allows for elements to be selected by dragging a box (sometimes called a lasso) with the mouse over the elements. Elements can also be selected via click or drag while holding the ctrl/meta key, allowing for multiple (non-contiguous) selections.

		<xi:include href="../includes/widget-theming.xml" xmlns:xi="http://www.w3.org/2003/XInclude"/>

				ui-selectable: The selectable element.

ui-selectee: One of the selectable elements, as specified through the filter option. This element can also receive one of the following classes: ui-selecting (when the lasso includes this element), ui-selected (after a successful selection), ui-unselecting (when the lasso lost this element).

ui-selectable-helper: The "lasso" element used to visualize the ongoing selection.

Dependencies

UI Core

Widget Factory

Mouse Interaction

	</longdesc>
	<note id="functional-css"/>
	<added>1.0</added>
	<options>
		<option name="appendTo" type="Selector" default='"body"' example-value='"#someElem"'>
			<desc>Which element the selection helper (the lasso) should be appended to.</desc>
		</option>
		<option name="autoRefresh" type="Boolean" default="true" example-value='false'>
			<desc>This determines whether to refresh (recalculate) the position and size of each selectee at the beginning of each select operation. If you have many items, you may want to set this to false and call the refresh() method manually.</desc>
		</option>
		<option name="cancel" type="Selector" default='"input,textarea,button,select,option"' example-value='"a,.cancel"'>
			<desc>Prevents selecting if you start on elements matching the selector.</desc>
		</option>
		<option name="classes" type="Object" default="{}">
			<xi:include href="../includes/classes-option-desc.xml" xmlns:xi="http://www.w3.org/2003/XInclude"/>
			<xi:include href="../includes/classes-option-example.xml" xmlns:xi="http://www.w3.org/2003/XInclude"/>
		</option>
		<option name="delay" type="Integer" default="0" example-value='150'>
			<deprecated>1.12</deprecated>
			<desc>Time in milliseconds to define when the selecting should start. This helps prevent unwanted selections when clicking on an element.</desc>
		</option>
		<xi:include href="../includes/widget-option-disabled.xml" xmlns:xi="http://www.w3.org/2003/XInclude"/>
		<option name="distance" type="Number" default="0" example-value='30'>
			<deprecated>1.12</deprecated>
			<desc>Tolerance, in pixels, for when selecting should start. If specified, selecting will not start until the mouse has been dragged beyond the specified distance.</desc>
		</option>
		<option name="filter" type="Selector" default='"*"' example-value='"li"'>
			<desc>The matching child elements will be made selectees (able to be selected).</desc>
		</option>
		<option name="tolerance" type="String" default='"touch"' example-value='"fit"'>
			<desc>
				Specifies which mode to use for testing whether the lasso should select an item. Possible values:

"fit": Lasso overlaps the item entirely.

"touch": Lasso overlaps the item by any amount.

			</desc>
		</option>
	</options>
	<events>
		<xi:include href="../includes/widget-event-create.xml" xmlns:xi="http://www.w3.org/2003/XInclude"/>
		<event name="selected">
			<desc>Triggered at the end of the select operation, on each element added to the selection.</desc>
			<argument name="event" type="Event"/>
			<argument name="ui" type="Object">
				<property name="selected" type="Element">
					<desc>The selectable item that has been selected.</desc>
				</property>
			</argument>
		</event>
		<event name="selecting">
			<desc>Triggered during the select operation, on each element added to the selection.</desc>
			<argument name="event" type="Event"/>
			<argument name="ui" type="Object">
				<property name="selecting" type="Element">
					<desc>The current selectable item being selected.</desc>
				</property>
			</argument>
		</event>
		<event name="start">
			<desc>Triggered at the beginning of the select operation.</desc>
			<argument name="event" type="Event"/>
			<argument name="ui" type="Object"/>
		</event>
		<event name="stop">
			<desc>Triggered at the end of the select operation.</desc>
			<argument name="event" type="Event"/>
			<argument name="ui" type="Object"/>
		</event>
		<event name="unselected">
			<desc>Triggered at the end of the select operation, on each element removed from the selection.</desc>
			<argument name="event" type="Event"/>
			<argument name="ui" type="Object">
				<property name="unselected" type="Element">
					<desc>The selectable item that has been unselected.</desc>
				</property>
			</argument>
		</event>
		<event name="unselecting">
			<desc>Triggered during the select operation, on each element removed from the selection.</desc>
			<argument name="event" type="Event"/>
			<argument name="ui" type="Object">
				<property name="unselecting" type="Element">
					<desc>The current selectable item being unselected.</desc>
				</property>
			</argument>
		</event>
	</events>
	<methods>
		<xi:include href="../includes/widget-method-destroy.xml" xmlns:xi="http://www.w3.org/2003/XInclude"/>
		<xi:include href="../includes/widget-method-disable.xml" xmlns:xi="http://www.w3.org/2003/XInclude"/>
		<xi:include href="../includes/widget-method-enable.xml" xmlns:xi="http://www.w3.org/2003/XInclude"/>
		<xi:include href="../includes/widget-method-instance.xml" xmlns:xi="http://www.w3.org/2003/XInclude"/>
		<method name="refresh">
			<desc>Refresh the position and size of each selectee element. This method can be used to manually recalculate the position and size of each selectee when the autoRefresh option is set to false.</desc>
		</method>
		<xi:include href="../includes/widget-method-option.xml" xmlns:xi="http://www.w3.org/2003/XInclude"/>
		<xi:include href="../includes/widget-method-widget.xml" xmlns:xi="http://www.w3.org/2003/XInclude"/>
	</methods>
	<example>
		<height>150</height>
		<desc>A simple jQuery UI Selectable.</desc>
		<css><![CDATA[
	#selectable .ui-selecting {
		background: #ccc;
	}
	#selectable .ui-selected {
		background: #999;
	}
]]></css>
		<![CDATA[
$( "#selectable" ).selectable();
]]>
		<![CDATA[

Item 1

Item 2

Item 3

Item 4

Item 5

]]>
	</example>
	<category slug="interactions"/>
</entry>


text:
import pytest

from pagseguro import PagSeguro, PagSeguroTransactionSearchResult
from pagseguro.configs import Config
from pagseguro.exceptions import PagSeguroValidationError
from pagseguro.utils import is_valid_email, is_valid_cpf

TOKEN = '123456'
EMAIL = 'seu@email.com'

@pytest.fixture
def pagseguro():
    return PagSeguro(token=TOKEN, email=EMAIL)

@pytest.fixture
def xml():
    return """
<transactionSearchResult>
    <date>2011-02-16T20:14:35.000-02:00</date>
    <currentPage>1</currentPage>
    <resultsInThisPage>2</resultsInThisPage>
    <totalPages>1</totalPages>
    <transactions>
        <transaction>
            <date>2011-02-05T15:46:12.000-02:00</date>
            <lastEventDate>2011-02-15T17:39:14.000-03:00</lastEventDate>
            9E884542-81B3-4419-9A75-BCC6FB495EF1
            <reference>REF1234</reference>
            <type>1</type>
            <status>3</status>
            <paymentMethod>
                <type>1</type>
            </paymentMethod>
            <grossAmount>49900.00</grossAmount>
            <discountAmount>0.00</discountAmount>
            <feeAmount>0.00</feeAmount>
            <netAmount>49900.00</netAmount>
            <extraAmount>0.00</extraAmount>
        </transaction>
        <transaction>
            <date>2011-02-07T18:57:52.000-02:00</date>
            <lastEventDate>2011-02-14T21:37:24.000-03:00</lastEventDate>
            2FB07A22-68FF-4F83-A356-24153A0C05E1
            <reference>REF5678</reference>
            <type>3</type>
            <status>4</status>
            <paymentMethod>
                <type>3</type>
            </paymentMethod>
            <grossAmount>26900.00</grossAmount>
            <discountAmount>0.00</discountAmount>
            <feeAmount>0.00</feeAmount>
            <netAmount>26900.00</netAmount>
            <extraAmount>0.00</extraAmount>
        </transaction>
    </transactions>
</transactionSearchResult>"""

def test_pagseguro_class(pagseguro):
    assert isinstance(pagseguro, PagSeguro)

def test_pagseguro_initial_attrs(pagseguro):
    assert isinstance(pagseguro.config, Config)
    assert isinstance(pagseguro.data, dict)
    assert 'email' in pagseguro.data
    assert 'token' in pagseguro.data
    assert pagseguro.data['email'] == EMAIL
    assert pagseguro.data['token'] == TOKEN
    assert isinstance(pagseguro.items, list)
    assert isinstance(pagseguro.sender, dict)
    assert isinstance(pagseguro.shipping, dict)
    assert pagseguro._reference == ''
    assert pagseguro.extra_amount is None
    assert pagseguro.redirect_url is None
    assert pagseguro.notification_url is None
    assert pagseguro.abandon_url is None

def test_build_checkout_params_with_all_params(pagseguro, sender, shipping,
                                               items):
    pagseguro.sender = sender
    pagseguro.shipping = shipping
    pagseguro.extra_amount = 12.50
    pagseguro.redirect_url = '/redirecionando/'
    pagseguro.abandon_url = '/abandonando/'
    pagseguro.items = items
    pagseguro.build_checkout_params()

    # check all data fields
    assert isinstance(pagseguro.data, dict)
    keys = ['email', 'token', 'senderName', 'senderAreaCode',
            'senderPhone', 'senderEmail', 'senderCPF', 'senderBornDate',
            'shippingType', 'shippingAddressStreet',
            'shippingAddressNumber', 'shippingAddressComplement',
            'shippingAddressDistrict', 'shippingAddressPostalCode',
            'shippingAddressCity', 'shippingAddressState',
            'shippingAddressCountry', 'shippingCost', 'extraAmount',
            'redirectURL', 'abandonURL']
    # items
    item_keys = ['itemId{}', 'itemDescription{}', 'itemAmount{}',
                 'itemQuantity{}', 'itemWeight{}']

    for key in keys:
        assert key in pagseguro.data

    for i, key in enumerate(pagseguro.items, 1):
        keys_to_compare = map(lambda x: x.format(i), item_keys)
        for item_key in keys_to_compare:
            assert item_key in pagseguro.data

def test_add_items_util(items):
    pagseguro = PagSeguro(token=TOKEN, email=EMAIL)
    pagseguro.add_item(**items[0])
    pagseguro.add_item(**items[1])
    assert len(pagseguro.items) == 2

def test_reference(pagseguro):
    pagseguro.reference = '12345'
    assert unicode(pagseguro.reference) == u'REF12345'

def test_clean_none_params(sender):
    pagseguro = PagSeguro(email=EMAIL, token=TOKEN)
    sender_copy = sender.copy()
    sender_copy['cpf'] = None
    sender_copy['born_date'] = None
    pagseguro.sender = sender_copy
    pagseguro.build_checkout_params()

    assert 'senderCPF' not in pagseguro.data
    assert 'senderBornData' not in pagseguro.data

def test_is_valid_email(sender):
    bad_email = 'john.com'
    pagseguro = PagSeguro(email=bad_email, token=TOKEN)
    pagseguro.sender = {'email': bad_email}
    with pytest.raises(PagSeguroValidationError):
        pagseguro.build_checkout_params()

    # Now testing with a valid email
    pagseguro.sender['email'] = sender['email']
    assert is_valid_email(pagseguro.sender['email']) == sender['email']

def test_is_valid_cpf():
    bad_cpf = '123.456.267-45'
    pagseguro = PagSeguro(email=EMAIL, token=TOKEN)
    pagseguro.sender = {'cpf': bad_cpf}

    with pytest.raises(PagSeguroValidationError):
        pagseguro.build_checkout_params()

    # Now testing with a valid email
    pagseguro.sender['cpf'] = '482.268.465-28'
    assert is_valid_cpf(pagseguro.sender['cpf']) == pagseguro.sender['cpf']

    pagseguro.sender['cpf'] = '48226846528'
    assert is_valid_cpf(pagseguro.sender['cpf']) == pagseguro.sender['cpf']

def test_parse_xml(xml):
    pg = PagSeguro(email=EMAIL, token=TOKEN)
    result = PagSeguroTransactionSearchResult(xml, pg.config)
    assert result.current_page == 1
    assert result.results_in_page == 2
    assert result.total_pages == 1
    assert len(result.transactions) == 2


text:
package com.amazonaws.services.elasticache.model.transform;

import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map.Entry;

import javax.xml.stream.events.XMLEvent;

import com.amazonaws.services.elasticache.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.MapEntry;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * ReservedCacheNodesOffering StAX Unmarshaller
 */
public class ReservedCacheNodesOfferingStaxUnmarshaller implements
        Unmarshaller<ReservedCacheNodesOffering, StaxUnmarshallerContext> {

    public ReservedCacheNodesOffering unmarshall(StaxUnmarshallerContext context)
            throws Exception {
        ReservedCacheNodesOffering reservedCacheNodesOffering = new ReservedCacheNodesOffering();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 3;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return reservedCacheNodesOffering;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("ReservedCacheNodesOfferingId",
                        targetDepth)) {
                    reservedCacheNodesOffering
                            .setReservedCacheNodesOfferingId(StringStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("CacheNodeType", targetDepth)) {
                    reservedCacheNodesOffering
                            .setCacheNodeType(StringStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("Duration", targetDepth)) {
                    reservedCacheNodesOffering
                            .setDuration(IntegerStaxUnmarshaller.getInstance()
                                    .unmarshall(context));
                    continue;
                }

                if (context.testExpression("FixedPrice", targetDepth)) {
                    reservedCacheNodesOffering
                            .setFixedPrice(DoubleStaxUnmarshaller.getInstance()
                                    .unmarshall(context));
                    continue;
                }

                if (context.testExpression("UsagePrice", targetDepth)) {
                    reservedCacheNodesOffering
                            .setUsagePrice(DoubleStaxUnmarshaller.getInstance()
                                    .unmarshall(context));
                    continue;
                }

                if (context.testExpression("ProductDescription", targetDepth)) {
                    reservedCacheNodesOffering
                            .setProductDescription(StringStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("OfferingType", targetDepth)) {
                    reservedCacheNodesOffering
                            .setOfferingType(StringStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("RecurringCharges/RecurringCharge",
                        targetDepth)) {
                    reservedCacheNodesOffering
                            .withRecurringCharges(RecurringChargeStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return reservedCacheNodesOffering;
                }
            }
        }
    }

    private static ReservedCacheNodesOfferingStaxUnmarshaller instance;

    public static ReservedCacheNodesOfferingStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new ReservedCacheNodesOfferingStaxUnmarshaller();
        return instance;
    }
}


text:
package io.virtdata.ast;

import java.util.ArrayList;
import java.util.List;

public class VirtDataFlow {
    private List<Expression> expressions = new ArrayList<>();

    public List<Expression> getExpressions() {
        return expressions;
    }

    public void addExpression(Expression expr) {
        expressions.add(expr);
    }

    public Expression getLastExpression() {
        if (expressions.size()==0) {
            throw new RuntimeException("expressions not initialized, last expression undefined");
        }
        return expressions.get(expressions.size()-1);
    }

    public Expression getFirstExpression() {
        if (expressions.size()==0) {
            throw new RuntimeException("expressions not initialized, first expression undefined.");
        }
        return expressions.get(0);
    }
}