text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

#if IGNORE_SSL_ERRORS
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
#endif

using System.Text;
using MindTouch.Tasking;
using MindTouch.Web;
using MindTouch.Xml;

namespace MindTouch.Dream.Http {
    using Yield = IEnumerator<IYield>;

    internal class HttpPlugEndpoint : IPlugEndpoint {

        //--- Types ---
        internal class ActivityState {

            //--- Fields ---
            private readonly IDreamActivityDescription _activity;
            private Queue<string> _messages = new Queue<string>();
            private readonly IDreamEnvironment _env;
            private readonly string _verb;
            private readonly string _uri;

            //--- Constructors ---
            internal ActivityState(IDreamEnvironment env, string verb, string uri) {
                _env = env;
                _activity = env.CreateActivityDescription();
                _verb = verb;
                _uri = uri;
            }

            //--- Messages ---
            internal void Message(string message) {
                lock(this) {
                    if(message != null) {
                        if(_messages != null) {
                            _messages.Enqueue(message);
                            if(_messages.Count > 10) {
                                _messages.Dequeue();
                            }
                            _activity.Description = string.Format("Outgoing: {0} {1} [{2}]", _verb, _uri, string.Join(" -> ", _messages.ToArray()));
                        }
                    } else {
                        _messages = null;
                        _activity.Dispose();
                    }
                }
            }
        }

        //--- Class Fields ---
        private static readonly log4net.ILog _log = LogUtils.CreateLog();

        //--- Class Constructor ---
        static HttpPlugEndpoint() {
#if IGNORE_SSL_ERRORS
            try {
                ServicePointManager.ServerCertificateValidationCallback = delegate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) {
                    return true;
                };
            } catch(Exception e) {
                _log.Error("class ctor", e);
            }
#endif
        }

        //--- Methods ---
        public int GetScoreWithNormalizedUri(XUri uri, out XUri normalized) {
            normalized = uri;
            switch(uri.Scheme.ToLowerInvariant()) {
            case "http":
            case "https":
                return 1;
            case "ext-http":
                normalized = normalized.WithScheme("http");
                return int.MaxValue;
            case "ext-https":
                normalized = normalized.WithScheme("https");
                return int.MaxValue;
            default:
                return 0;
            }
        }

        public Yield Invoke(Plug plug, string verb, XUri uri, DreamMessage request, Result<DreamMessage> response) {
            Result<DreamMessage> res;

            // register activity
            DreamContext context = DreamContext.CurrentOrNull;
            Action<string> activity;
            if(context != null) {
                activity = new ActivityState(context.Env, verb, uri.ToString()).Message;
            } else {
                activity = delegate { };
            }
            activity("pre Invoke");
            yield return res = Coroutine.Invoke(HandleInvoke, activity, plug, verb, uri, request, new Result<DreamMessage>(response.Timeout)).Catch();
            activity("post Invoke");

            // unregister activity
            activity(null);

            // return response
            response.Return(res);
        }

        private Yield HandleInvoke(Action<string> activity, Plug plug, string verb, XUri uri, DreamMessage request, Result<DreamMessage> response) {
            Result<IAsyncResult> async;

            // remove internal headers
            request.Headers.DreamTransport = null;

            // set request headers
            request.Headers.Host = uri.Host;
            if(request.Headers.UserAgent == null) {
                request.Headers.UserAgent = "Dream/" + DreamUtil.DreamVersion;
            }

            // add cookies to request
            if(request.HasCookies) {
                request.Headers[DreamHeaders.COOKIE] = DreamCookie.RenderCookieHeader(request.Cookies);
            }

            // initialize request
            activity("pre WebRequest.Create");
            var httpRequest = (HttpWebRequest)WebRequest.Create(uri.ToUri());
            activity("post WebRequest.Create");
            httpRequest.Method = verb;
            httpRequest.Timeout = System.Threading.Timeout.Infinite;
            httpRequest.ReadWriteTimeout = System.Threading.Timeout.Infinite;

            // Note (arnec): httpRequest AutoRedirect is disabled because Plug is responsible for it (this allows redirects to follow
            // the appropriate handler instead staying stuck in http end point land
            httpRequest.AllowAutoRedirect = false;

            // Note from http://support.microsoft.com/kb/904262
            // The HTTP request is made up of the following parts:
            // 1.   Sending the request is covered by using the HttpWebRequest.Timeout method.
            // 2.   Getting the response header is covered by using the HttpWebRequest.Timeout method.
            // 3.   Reading the body of the response is not covered by using the HttpWebResponse.Timeout method. In ASP.NET 1.1 and in later versions, reading the body of the response
            //      is covered by using the HttpWebRequest.ReadWriteTimeout method. The HttpWebRequest.ReadWriteTimeout method is used to handle cases where the response headers are
            //      retrieved in a timely manner but where the reading of the response body times out.

            httpRequest.KeepAlive = false;
            httpRequest.ProtocolVersion = HttpVersion.Version10;

            // TODO (steveb): set default proxy
            //httpRequest.Proxy = WebProxy.GetDefaultProxy();
            //httpRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;

            // set credentials
            if(plug.Credentials != null) {
                httpRequest.Credentials = plug.Credentials;
                httpRequest.PreAuthenticate = true;
            } else if(!string.IsNullOrEmpty(uri.User) || !string.IsNullOrEmpty(uri.Password)) {
                httpRequest.Credentials = new NetworkCredential(uri.User ?? string.Empty, uri.Password ?? string.Empty);
                httpRequest.PreAuthenticate = true;

                // Note (arnec): this manually adds the basic auth header, so it can authorize
                // in a single request without requiring challenge
                var authbytes = Encoding.ASCII.GetBytes(string.Concat(uri.User ?? string.Empty, ":", uri.Password ?? string.Empty));
                var base64 = Convert.ToBase64String(authbytes);
                httpRequest.Headers.Add(DreamHeaders.AUTHORIZATION, "Basic " + base64);
            }

            // add request headres
            foreach(KeyValuePair<string, string> header in request.Headers) {
                httpRequest.AddHeader(header.Key, header.Value);
            }

            // send message stream
            if((request.ContentLength != 0) || (verb == Verb.POST)) {
                async = new Result<IAsyncResult>();
                try {
                    activity("pre BeginGetRequestStream");
                    httpRequest.BeginGetRequestStream(async.Return, null);
                    activity("post BeginGetRequestStream");
                } catch(Exception e) {
                    activity("pre HandleResponse 1");
                    if(!HandleResponse(activity, e, null, response)) {
                        _log.ErrorExceptionMethodCall(e, "HandleInvoke@BeginGetRequestStream", verb, uri.ToString(false));
                        try {
                            httpRequest.Abort();
                        } catch { }
                    }
                    yield break;
                }
                activity("pre yield BeginGetRequestStream");
                yield return async.Catch();
                activity("post yield BeginGetRequestStream");

                // send request
                Stream outStream;
                try {
                    activity("pre EndGetRequestStream");
                    outStream = httpRequest.EndGetRequestStream(async.Value);
                    activity("pre EndGetRequestStream");
                } catch(Exception e) {
                    activity("pre HandleResponse 2");
                    if(!HandleResponse(activity, e, null, response)) {
                        _log.ErrorExceptionMethodCall(e, "HandleInvoke@EndGetRequestStream", verb, uri.ToString(false));
                        try {
                            httpRequest.Abort();
                        } catch { }
                    }
                    yield break;
                }

                // copy data
                //(yurig): HttpWebRequest does some internal memory buffering, therefore copying the data syncronously is acceptable.
                activity("pre CopyStream");
                try {
                    request.ToStream().CopyTo(outStream);
                    activity("post CopyStream");
                } catch (Exception e) {
                    activity("post CopyStream");
                    activity("pre HandleResponse 3");
                    if(!HandleResponse(activity, e, null, response)) {
                        _log.ErrorExceptionMethodCall(e, "HandleInvoke@AsyncUtil.CopyStream", verb, uri.ToString(false));
                        try {
                            httpRequest.Abort();
                        } catch { }
                    }
                    yield break;
                } finally {
                    outStream.Close();
                }
            }
            request = null;

            // wait for response
            async = new Result<IAsyncResult>(response.Timeout);
            try {
                activity("pre BeginGetResponse");
                httpRequest.BeginGetResponse(async.Return, null);
                activity("post BeginGetResponse");
            } catch(Exception e) {
                activity("pre HandleResponse 4");
                if(!HandleResponse(activity, e, null, response)) {
                    _log.ErrorExceptionMethodCall(e, "HandleInvoke@BeginGetResponse", verb, uri.ToString(false));
                    try {
                        httpRequest.Abort();
                    } catch { }
                }
                yield break;
            }
            activity("pre yield BeginGetResponse");
            yield return async.Catch();
            activity("post yield BeginGetResponse");

            // check if an error occurred
            if(async.HasException) {
                activity("pre HandleResponse 5");
                if(!HandleResponse(activity, async.Exception, null, response)) {
                    _log.ErrorExceptionMethodCall(async.Exception, "HandleInvoke@BeginGetResponse", verb, uri.ToString(false));
                    try {
                        httpRequest.Abort();
                    } catch { }
                }
                yield break;
            } else {

                // handle response
                try {
                    HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(async.Value);
                    activity("pre HandleResponse 6");
                    if(!HandleResponse(activity, null, httpResponse, response)) {
                        try {
                            httpRequest.Abort();
                        } catch { }
                    }
                } catch(Exception e) {
                    activity("pre HandleResponse 7");
                    if(!HandleResponse(activity, e, null, response)) {
                        _log.ErrorExceptionMethodCall(e, "HandleInvoke@EndGetResponse", verb, uri.ToString(false));
                        try {
                            httpRequest.Abort();
                        } catch { }
                    }
                    yield break;
                }
            }
        }

        private bool HandleResponse(Action<string> activity, Exception exception, HttpWebResponse httpResponse, Result<DreamMessage> response) {
            if(exception != null) {
                if(exception is WebException) {
                    activity("pre WebException");
                    httpResponse = (HttpWebResponse)((WebException)exception).Response;
                    activity("post WebException");
                } else {
                    activity("pre HttpWebResponse close");
                    try {
                        httpResponse.Close();
                    } catch { }
                    activity("HandleResponse exit 1");
                    response.Return(new DreamMessage(DreamStatus.UnableToConnect, null, new XException(exception)));
                    return false;
                }
            }

            // check if a response was obtained, otherwise fail
            if(httpResponse == null) {
                activity("HandleResponse exit 2");
                response.Return(new DreamMessage(DreamStatus.UnableToConnect, null, new XException(exception)));
                return false;
            }

            // determine response type
            MimeType contentType = string.IsNullOrEmpty(httpResponse.ContentType) ? null : new MimeType(httpResponse.ContentType);
            Stream stream;
            HttpStatusCode statusCode = httpResponse.StatusCode;
            WebHeaderCollection headers = httpResponse.Headers;
            long contentLength = httpResponse.ContentLength;

            if(contentType != null || contentLength == -1) {
                activity("pre new BufferedStream");
                stream = new BufferedStream(httpResponse.GetResponseStream());
                activity("post new BufferedStream");
            } else {

                // TODO (arnec): If we get a response with a stream, but no content-type, we're currently dropping the stream. Might want to revisit that.
                _log.DebugFormat("response ({0}) has not content-type and content length of {1}", statusCode, contentLength);
                contentType = null;
                stream = Stream.Null;
                httpResponse.Close();
            }

            // encapsulate the response in a dream message
            activity("HandleResponse exit 3");
            response.Return(new DreamMessage((DreamStatus)(int)statusCode, new DreamHeaders(headers), contentType, contentLength, stream));
            return true;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

public class ThreeSlicesSprite : MonoBehaviour
{
    SpriteRenderer spriteRenderer;
    Material material;

    [Range(0, 1)]
    public float donePercentage;

    void Start()
    {
        spriteRenderer = GetComponentInChildren<SpriteRenderer>();
        material = spriteRenderer.material;
    }

    void Update()
    {
        material.SetFloat("_ScreenLeftOffset", Camera.main.WorldToScreenPoint(spriteRenderer.bounds.min).x);
        material.SetFloat("_ScreenRightOffset", Camera.main.WorldToScreenPoint(spriteRenderer.bounds.max).x);
        material.SetFloat("_Done", donePercentage);
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <stdint.h>
#include <iostream>

#include "ignite/ignite.h"
#include "ignite/ignition.h"

#include "ignite/examples/organization.h"
#include "ignite/examples/person.h"

using namespace ignite;
using namespace cache;
using namespace query;

using namespace examples;

/** Organizations cache name. */
const char* ORG_CACHE = "Organization";

/** Organizations type name. */
const char* ORG_TYPE = "Organization";

/** Persons cache name. */
const char* PERSON_CACHE = "Person";

/** Persons type name. */
const char* PERSON_TYPE = "Person";

/**
 * Example for SQL fields queries based on all employees working for a specific
 * organization (query uses distributed join).
 *
 * Note that SQL Fields Query can only be performed using fields that have been
 * listed in "QueryEntity" been of the config.
 */
void DoSqlQueryWithDistributedJoin()
{
    Cache<PersonKey, Person> cache = Ignition::Get().GetCache<PersonKey, Person>(PERSON_CACHE);

    // SQL clause query which joins on 2 types to select people for a specific organization.
    SqlFieldsQuery qry(
        "select firstName, lastName from Person "
        "inner join \"Organization\".Organization as org "
        "where Person.orgId = org._key "
        "and lower(org.name) = lower(?)");

    qry.AddArgument<std::string>("ApacheIgnite");

    // Enable distributed joins for query.
    qry.SetDistributedJoins(true);

    QueryFieldsCursor cursor = cache.Query(qry);

    // Printing first result set.
    std::cout << "Following people are 'ApacheIgnite' employees (distributed join): " << std::endl;

    while (cursor.HasNext())
    {
        QueryFieldsRow row = cursor.GetNext();

        std::cout << row.GetNext<std::string>() << " " << row.GetNext<std::string>() << std::endl;
    }

    std::cout << std::endl;

    qry.ClearArguments();

    qry.AddArgument<std::string>("Other");

    cursor = cache.Query(qry);

    // Printing second result set.
    std::cout << "Following people are 'Other' employees (distributed join): " << std::endl;

    while (cursor.HasNext())
    {
        QueryFieldsRow row = cursor.GetNext();

        std::cout << row.GetNext<std::string>() << " " << row.GetNext<std::string>() << std::endl;
    }

    std::cout << std::endl;
}

/**
 * Example for SQL-based fields queries that return only person name and company it works in.
 *
 * Note that SQL Fields Query can only be performed using fields that have been
 * listed in "QueryEntity" been of the config.
 */
void DoSqlQueryWithJoin()
{
    Cache<PersonKey, Person> cache = Ignition::Get().GetCache<PersonKey, Person>(PERSON_CACHE);

    // Execute query to get names of all employees.
    std::string sql(
        "select concat(firstName, ' ', lastName), org.name "
        "from Person, \"Organization\".Organization as org "
        "where Person.orgId = org._key");

    QueryFieldsCursor cursor = cache.Query(SqlFieldsQuery(sql));

    // Print persons' names and organizations' names.
    std::cout << "Names of all employees and organizations they belong to: " << std::endl;

    // In this particular case each row will have two elements with full name
    // of an employees and their organization.
    while (cursor.HasNext())
    {
        QueryFieldsRow row = cursor.GetNext();

        std::cout << row.GetNext<std::string>() << " is working in ";
        std::cout << row.GetNext<std::string>() << std::endl;
    }

    std::cout << std::endl;
}

/**
 * Example for SQL-based fields queries that uses SQL functions.
 *
 * Note that SQL Fields Query can only be performed using fields that have been
 * listed in "QueryEntity" been of the config.
 */
void DoSqlQueryWithFunction()
{
    Cache<PersonKey, Person> cache = Ignition::Get().GetCache<PersonKey, Person>(PERSON_CACHE);

    // Execute query to get names of all employees.
    QueryFieldsCursor cursor = cache.Query(SqlFieldsQuery(
        "select concat(firstName, ' ', lastName) from Person"));

    // Print names.
    std::cout << "Names of all employees: " << std::endl;

    // In this particular case each row will have one element with full name of an employees.
    while (cursor.HasNext())
        std::cout << cursor.GetNext().GetNext<std::string>() << std::endl;

    std::cout << std::endl;
}

/**
 * Example for SQL queries to calculate average salary for a specific organization.
 *
 * Note that SQL Fields Query can only be performed using fields that have been
 * listed in "QueryEntity" been of the config.
 */
void DoSqlQueryWithAggregation()
{
    Cache<PersonKey, Person> cache = Ignition::Get().GetCache<PersonKey, Person>(PERSON_CACHE);

    // Calculate average of salary of all persons in ApacheIgnite.
    // Note that we also join on Organization cache as well.
    SqlFieldsQuery qry(
        "select avg(salary) "
        "from Person, \"Organization\".Organization as org "
        "where Person.orgId = org._key "
        "and lower(org.name) = lower(?)");

    qry.AddArgument<std::string>("ApacheIgnite");

    QueryFieldsCursor cursor = cache.Query(qry);

    // Calculate average salary for a specific organization.
    std::cout << "Average salary for 'ApacheIgnite' employees: " << std::endl;

    while (cursor.HasNext())
        std::cout << cursor.GetNext().GetNext<double>() << std::endl;

    std::cout << std::endl;
}

/**
 * Example for SQL queries based on salary ranges.
 *
 * Note that SQL Query can only be performed using fields that have been
 * listed in "QueryEntity" been of the config.
 */
void DoSqlQuery()
{
    Cache<PersonKey, Person> cache = Ignition::Get().GetCache<PersonKey, Person>(PERSON_CACHE);

    // SQL clause which selects salaries based on range.
    SqlFieldsQuery qry(
        "select firstName, lastName, salary "
        "from Person "
        "where salary > ? and salary <= ?");

    // Execute queries for salary range 0 - 1000.
    std::cout << "People with salaries between 0 and 1000 (queried with SQL query): " << std::endl;

    qry.AddArgument(0);
    qry.AddArgument(1000);

    QueryFieldsCursor cursor = cache.Query(qry);

    while (cursor.HasNext())
    {
        QueryFieldsRow row = cursor.GetNext();

        std::cout
            << row.GetNext<std::string>() << " "
            << row.GetNext<std::string>() << " : "
            << row.GetNext<double>()
            << std::endl;
    }

    std::cout << std::endl;

    qry.ClearArguments();

    // Execute queries for salary range 1000 - 2000.
    std::cout << "People with salaries between 1000 and 2000 (queried with SQL query): " << std::endl;

    qry.AddArgument(1000);
    qry.AddArgument(2000);

    cursor = cache.Query(qry);

    while (cursor.HasNext())
    {
        QueryFieldsRow row = cursor.GetNext();

        std::cout
            << row.GetNext<std::string>() << " "
            << row.GetNext<std::string>() << " : "
            << row.GetNext<double>()
            << std::endl;
    }

    std::cout << std::endl;
}

/**
 * Example for TEXT queries using LUCENE-based indexing of people's resumes.
 *
 * Note that to be able to do so you have to add FULLTEXT index for the 'resume'
 * field of the Person type. See config for details.
 */
void DoTextQuery()
{
    Cache<PersonKey, Person> cache = Ignition::Get().GetCache<PersonKey, Person>(PERSON_CACHE);

    typedef std::vector< CacheEntry<PersonKey, Person> > ResVector;

    //  Query for all people with "Master" in their resumes.
    ResVector masters;
    cache.Query(TextQuery(PERSON_TYPE, "Master")).GetAll(masters);

    // Query for all people with "Bachelor" in their resumes.
    ResVector bachelors;
    cache.Query(TextQuery(PERSON_TYPE, "Bachelor")).GetAll(bachelors);

    std::cout << "Following people have 'Master' in their resumes: " << std::endl;

    // Printing first result set.
    for (ResVector::const_iterator i = masters.begin(); i != masters.end(); ++i)
        std::cout << i->GetKey().ToString() << " : " << i->GetValue().ToString() << std::endl;

    std::cout << std::endl;

    std::cout << "Following people have 'Bachelor' in their resumes: " << std::endl;

    // Printing second result set.
    for (ResVector::const_iterator i = bachelors.begin(); i != bachelors.end(); ++i)
        std::cout << i->GetKey().ToString() << " : " << i->GetValue().ToString() << std::endl;

    std::cout << std::endl;
}

/**
 * Example for scan query based on a predicate.
 */
void DoScanQuery()
{
    Cache<PersonKey, Person> cache = Ignition::Get().GetCache<PersonKey, Person>(PERSON_CACHE);

    ScanQuery scan;

    typedef std::vector< CacheEntry<PersonKey, Person> > ResVector;

    ResVector res;
    cache.Query(scan).GetAll(res);

    // Execute queries for salary ranges.
    std::cout << "People with salaries between 0 and 1000 (queried with SCAN query): " << std::endl;

    for (ResVector::const_iterator i = res.begin(); i != res.end(); ++i)
    {
        Person person(i->GetValue());

        if (person.salary <= 1000)
            std::cout << i->GetKey().ToString() << " : " << person.ToString() << std::endl;
    }

    std::cout << std::endl;
}

/**
 * Populate cache with test data.
 */
void Initialize()
{
    Cache<int64_t, Organization> orgCache =
        Ignition::Get().GetCache<int64_t, Organization>(ORG_CACHE);

    // Clear cache before running the example.
    orgCache.Clear();

    // Organizations.
    Organization org1("ApacheIgnite");
    Organization org2("Other");

    const int64_t org1Id = 1;
    const int64_t org2Id = 2;

    orgCache.Put(org1Id, org1);
    orgCache.Put(org2Id, org2);

    Cache<PersonKey, Person> personCache =
        Ignition::Get().GetCache<PersonKey, Person>(PERSON_CACHE);

    // Clear cache before running the example.
    personCache.Clear();

    // People.

    // Collocated by 1st organisation:
    Person p1(org1Id, "John", "Doe", "John Doe has Master Degree.", 2000);
    Person p2(org1Id, "Jane", "Doe", "Jane Doe has Bachelor Degree.", 1000);

    PersonKey pKey1 (1, org1Id);
    PersonKey pKey2 (2, org1Id);

    // Collocated by second organisation:
    Person p3(org2Id, "John", "Smith", "John Smith has Bachelor Degree.", 1000);
    Person p4(org2Id, "Jane", "Smith", "Jane Smith has Master Degree.", 2000);

    PersonKey pKey3 (3, org2Id);
    PersonKey pKey4 (4, org2Id);

    // Note that in this example we use custom affinity key for Person objects
    // to ensure that all persons are collocated with their organizations.
    personCache.Put(pKey1, p1);
    personCache.Put(pKey2, p2);
    personCache.Put(pKey3, p3);
    personCache.Put(pKey4, p4);
}

int main()
{
    try
    {
        IgniteConfiguration cfg;
        cfg.springCfgPath = "platforms/cpp/examples/query-example/config/query-example.xml";

        // Start a node.
        Ignite ignite = Ignition::Start(cfg);

        std::cout << std::endl;
        std::cout << ">>> Cache query example started." << std::endl;
        std::cout << std::endl;

        // Get organization cache instance.
        Cache<int64_t, Organization> orgCache = ignite.GetCache<int64_t, Organization>(ORG_CACHE);

        // Get person cache instance.
        Cache<PersonKey, Person> personCache = ignite.GetCache<PersonKey, Person>(PERSON_CACHE);

        // Populate cache.
        Initialize();

        // Example for SCAN-based query based on a predicate.
        DoScanQuery();

        // Example for TEXT-based querying for a given string in peoples resumes.
        DoTextQuery();

        // Example for SQL-based querying employees based on salary ranges.
        DoSqlQuery();

        // Example for SQL-based querying employees for a given organization (includes SQL join).
        DoSqlQueryWithJoin();

        // Example for SQL-based querying employees for a given organization (includes distributed SQL join).
        DoSqlQueryWithDistributedJoin();

        // Example for SQL-based fields queries that uses SQL functions.
        DoSqlQueryWithFunction();

        // Example for SQL-based querying to calculate average salary among all employees within a company.
        DoSqlQueryWithAggregation();

        // Stop node.
        Ignition::StopAll(false);

        std::cout << std::endl;
        std::cout << ">>> Example finished, press 'Enter' to exit ..." << std::endl;
        std::cout << std::endl;

        std::cin.get();
    }
    catch (IgniteError& err)
    {
        std::cout << "An error occurred: " << err.GetText() << std::endl;

        return err.GetCode();
    }

    return 0;
}


text:
#ifndef __LSBUTTONSET_H_INCLUDED
#define __LSBUTTONSET_H_INCLUDED

#include <iostream>
#include "LButton.h"

using namespace std;

class LSButtonSet
{
public:
	LSButtonSet();
	~LSButtonSet();

	void setMaxButtons(int max);
	void handleEvents(SDL_Event* e);
	void loadTextures(string buttonTxt, SDL_Renderer* mren);
	void setClips(SDL_Rect clip1, SDL_Rect clip2, SDL_Rect clip3, SDL_Rect clip4);
	void setPos(int _x, int _y);
	void render(SDL_Renderer* mren);
	void free();
	int getCurrent();

	SDL_Rect getDiment1();
	SDL_Rect getDiment2();
	SDL_Rect getDiment3();
private:
	LButton buttons[15];
	int maxButtons;
	int current = 0;
};

#endif //__LSBUTTONSET_H_INCLUDED


text:
class DrawTest : public testing::Test
{
};

// Test that a vertex shader with no gl_Position works.
// This was fixed in swiftshader-cl/51808
TEST_F(DrawTest, VertexShaderNoPositionOutput)
{
	DrawTester tester;
	tester.onCreateVertexBuffers([](DrawTester &tester) {
		struct Vertex
		{
			float position[3];
		};

		Vertex vertexBufferData[] = {
			{ { 1.0f, 1.0f, 0.5f } },
			{ { -1.0f, 1.0f, 0.5f } },
			{ { 0.0f, -1.0f, 0.5f } }
		};

		std::vector<vk::VertexInputAttributeDescription> inputAttributes;
		inputAttributes.push_back(vk::VertexInputAttributeDescription(0, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, position)));

		tester.addVertexBuffer(vertexBufferData, sizeof(vertexBufferData), std::move(inputAttributes));
	});

	tester.onCreateVertexShader([](DrawTester &tester) {
		const char *vertexShader = R"(#version 310 es
			layout(location = 0) in vec3 inPos;

			void main()
			{
				// Remove gl_Position on purpose for the test
				//gl_Position = vec4(inPos.xyz, 1.0);
			})";

		return tester.createShaderModule(vertexShader, EShLanguage::EShLangVertex);
	});

	tester.onCreateFragmentShader([](DrawTester &tester) {
		const char *fragmentShader = R"(#version 310 es
			precision highp float;

			layout(location = 0) out vec4 outColor;

			void main()
			{
				outColor = vec4(1.0, 1.0, 1.0, 1.0);
			})";

		return tester.createShaderModule(fragmentShader, EShLanguage::EShLangFragment);
	});

	tester.initialize();
	tester.renderFrame();
}


text:
var models = require('../models/models.js');

// GET /quizes/question
exports.question = function(req,res) {
  models.Quiz.findAll().then(function(quiz) {
    res.render('quizes/question',{pregunta:quiz[0].pregunta})
  })
};

// GET /quizes/answer
exports.answer = function(req,res) {
  models.Quiz.findAll().then(function(quiz) {
    if (req.query.respuesta === quiz[0].respuesta) {
      res.render('quizes/answer',{respuesta:'Correcto'});
    } else {
      res.render('quizes/answer',{respuesta:'Incorrecto'});
    }
  })
};


text:
package org.flowkeeper.client.ui;

import javax.swing.JOptionPane;

import org.jdesktop.application.Action;
import org.jdesktop.beansbinding.AutoBinding;

/**
 * A simple dialog for inputting the new work item, consisting of the following:
 *
 *

 *
Title / description

 *
Estimated number of Pomodoros (1 to 4)

 *

 *
 * Source code is mostly generated by Netbeans Swing editor and was not
 * formatted or refactored to keep compatibility.
 */
public class AddWorkItemDialog extends javax.swing.JDialog {

	private static final long serialVersionUID = 2644334006118194204L;

	private boolean created = false;

    public boolean isCreated () {
        return created;
    }

    public AddWorkItemDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        getRootPane().setDefaultButton(addWorkItemButton);
        Util.decorate(this, true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jLabel1 = new javax.swing.JLabel();
        descriptionTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        pomodoroCountComboBox = new javax.swing.JComboBox();
        addWorkItemButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        headerPanel = new javax.swing.JPanel();
        headerTextLabel = new javax.swing.JLabel();
        headerLogoLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(org.flowkeeper.client.ui.PomodoroClientApp.class).getContext().getResourceMap(AddWorkItemDialog.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setModal(true);
        setName("Form"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        descriptionTextField.setText(resourceMap.getString("title.text")); // NOI18N
        descriptionTextField.setName("title"); // NOI18N

        AutoBinding<Object, Object, Object, Object> binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, addWorkItemButton, org.jdesktop.beansbinding.ELProperty.create("${action}"), descriptionTextField, org.jdesktop.beansbinding.BeanProperty.create("action"));
        bindingGroup.addBinding(binding);

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        pomodoroCountComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "●", "●●", "●●●", "●●●●" }));
        pomodoroCountComboBox.setName("pomodoros"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(org.flowkeeper.client.ui.PomodoroClientApp.class).getContext().getActionMap(AddWorkItemDialog.class, this);
        addWorkItemButton.setAction(actionMap.get("addWorkItem")); // NOI18N
        addWorkItemButton.setText(resourceMap.getString("addButton.text")); // NOI18N
        addWorkItemButton.setName("addButton"); // NOI18N

        cancelButton.setAction(actionMap.get("cancelPressed")); // NOI18N
        cancelButton.setText(resourceMap.getString("cancelButton.text")); // NOI18N
        cancelButton.setName("cancelButton"); // NOI18N

        headerPanel.setBackground(resourceMap.getColor("headerPanel.background")); // NOI18N
        headerPanel.setBorder(javax.swing.BorderFactory.createLineBorder(resourceMap.getColor("headerPanel.border.lineColor"))); // NOI18N
        headerPanel.setName("headerPanel"); // NOI18N

        headerTextLabel.setFont(headerTextLabel.getFont().deriveFont(headerTextLabel.getFont().getSize()+7f));
        headerTextLabel.setText(resourceMap.getString("headerTextLabel.text")); // NOI18N
        headerTextLabel.setName("headerTextLabel"); // NOI18N

        headerLogoLabel.setIcon(resourceMap.getIcon("headerLogoLabel.icon")); // NOI18N
        headerLogoLabel.setName("headerLogoLabel"); // NOI18N

        javax.swing.GroupLayout headerPanelLayout = new javax.swing.GroupLayout(headerPanel);
        headerPanel.setLayout(headerPanelLayout);
        headerPanelLayout.setHorizontalGroup(
            headerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, headerPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(headerTextLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(headerLogoLabel))
        );
        headerPanelLayout.setVerticalGroup(
            headerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(headerLogoLabel)
            .addComponent(headerTextLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 68, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(headerPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(descriptionTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 327, Short.MAX_VALUE)
                            .addComponent(pomodoroCountComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(addWorkItemButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(headerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(descriptionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(pomodoroCountComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addWorkItemButton)
                    .addComponent(cancelButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    @Action
    public void cancelPressed() {
        created = false;
        setVisible(false);
    }

    @Action
    public void addWorkItem() {
        created = true;
        if (getWorkItemTitle().isEmpty()) {
            JOptionPane.showMessageDialog(this, "You must specify work item title", "Error", JOptionPane.ERROR_MESSAGE);
        } else {
            setVisible(false);
        }
    }

    public String getWorkItemTitle() {
        return descriptionTextField.getText();
    }

    public int getPomodoros() {
        return pomodoroCountComboBox.getSelectedIndex() + 1;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel headerLogoLabel;
    private javax.swing.JPanel headerPanel;
    private javax.swing.JLabel headerTextLabel;
    private javax.swing.JButton addWorkItemButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JComboBox pomodoroCountComboBox;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField descriptionTextField;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

}


text:
namespace PlantIt.Common.Mapping
{
    public interface IMapFrom<TModel>
    {

    }
}


text:
package com.dup.base.util;

import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import com.dup.base.exception.UncheckedException;

/**
 * 硬件相关工具类。
 */
public class HardwareUtils {
	/**
	 * 获取当前机器所有MAC地址列表。
	 *
	 * @return 返回当前机器所有MAC地址列表。
	 */
	public static List<String> getAllMac() {
		List<String> macs = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
					.getNetworkInterfaces();
			while (networkInterfaces.hasMoreElements()) {
				NetworkInterface networkInterface = networkInterfaces
						.nextElement();
				byte[] macBytes = networkInterface.getHardwareAddress();
				if (macBytes != null) {
					String mac = byteToMac(macBytes);
					macs.add(mac);
				}
			}
		} catch (Exception e) {
			throw new UncheckedException("获取MAC地址时发生异常", e);
		}
		return macs;
	}

	/**
	 * 将MAC地址字节数组转成字符串。
	 *
	 * @param macBytes
	 *            MAC地址字节数组
	 * @return 返回MAC地址字符串。
	 */
	private static String byteToMac(byte[] macBytes) {
		StringBuilder builder = new StringBuilder();
		for (byte macByte : macBytes) {
			String macStr = "00" + Integer.toHexString(macByte);
			macStr = macStr.substring(macStr.length() - 2).toUpperCase();
			builder.append("-");
			builder.append(macStr);
		}
		String mac = builder.toString();
		mac = mac.substring(1);
		return mac;
	}
}


text:
require_relative '../spec_helper'

describe name_from_filename do
    include_examples 'path_extractor'

    def results
        [
            'http://test.com',
            'test',
            'test.com'
        ]
    end

    def text
        results.map { |u| "<form action='#{u}'>Stuff</form>" }.join
    end

    easy_test
end


text:
import sys, os

def lll(dirname):
    for name in os.listdir(dirname):
        if name not in (os.curdir, os.pardir):
            full = os.path.join(dirname, name)
            if os.path.islink(full):
                print name, '->', os.readlink(full)

args = sys.argv[1:]
if not args: args = [os.curdir]
first = 1
for arg in args:
    if len(args) > 1:
        if not first: print
        first = 0
        print arg + ':'
    lll(arg)


text:
<meta name="order" content="2" />
<title>Exporting data via website</title>

Export Data

Data can be exported from Ensembl pages in various formats. Because we're open access, all the data and images you export are free to be used and reproduced in papers, posters, presentations and websites.

[[SCRIPT::EnsEMBL::Web::Document::HTML::Export]]


text:
package org.ehcache.impl.internal.store.loaderwriter;

import org.ehcache.config.ResourceType;
import org.ehcache.core.spi.store.AbstractWrapperStoreProvider;
import org.ehcache.core.spi.store.Store;
import org.ehcache.spi.loaderwriter.CacheLoaderWriter;
import org.ehcache.spi.loaderwriter.CacheLoaderWriterConfiguration;
import org.ehcache.spi.loaderwriter.CacheLoaderWriterProvider;
import org.ehcache.spi.loaderwriter.WriteBehindConfiguration;
import org.ehcache.spi.loaderwriter.WriteBehindProvider;
import org.ehcache.spi.service.Service;
import org.ehcache.spi.service.ServiceConfiguration;
import org.ehcache.spi.service.ServiceDependencies;
import org.ehcache.spi.service.ServiceProvider;

import java.util.Collection;
import java.util.Set;

import static org.ehcache.core.spi.service.ServiceUtils.findSingletonAmongst;

@ServiceDependencies({CacheLoaderWriterProvider.class, WriteBehindProvider.class})
public class LoaderWriterStoreProvider extends AbstractWrapperStoreProvider {

  private volatile WriteBehindProvider writeBehindProvider;

  @Override
  protected <K, V> Store<K, V> wrap(Store<K, V> store, Store.Configuration<K, V> storeConfig, ServiceConfiguration<?, ?>... serviceConfigs) {
    WriteBehindConfiguration<?> writeBehindConfiguration = findSingletonAmongst(WriteBehindConfiguration.class, (Object[]) serviceConfigs);
    LocalLoaderWriterStore<K, V> loaderWriterStore;
    if(writeBehindConfiguration == null) {
      loaderWriterStore = new LocalLoaderWriterStore<>(store, storeConfig.getCacheLoaderWriter(), storeConfig.useLoaderInAtomics(), storeConfig.getExpiry());
    } else {
      CacheLoaderWriter<? super K, V> writeBehindLoaderWriter = writeBehindProvider.createWriteBehindLoaderWriter(storeConfig.getCacheLoaderWriter(), writeBehindConfiguration);
      loaderWriterStore = new LocalWriteBehindLoaderWriterStore<>(store, writeBehindLoaderWriter, storeConfig.useLoaderInAtomics(), storeConfig.getExpiry());
    }
    return loaderWriterStore;
  }

  @Override
  public void releaseStore(Store<?, ?> resource) {
    try {
      if (resource instanceof LocalWriteBehindLoaderWriterStore<?, ?>) {
        writeBehindProvider.releaseWriteBehindLoaderWriter(((LocalWriteBehindLoaderWriterStore<?, ?>) resource).getCacheLoaderWriter());
      }
    } finally {
      super.releaseStore(resource);
    }
  }

  @Override
  public void start(ServiceProvider<Service> serviceProvider) {
    super.start(serviceProvider);
    this.writeBehindProvider = serviceProvider.getService(WriteBehindProvider.class);
  }

  @Override
  public void stop() {
    this.writeBehindProvider = null;
    super.stop();
  }

  @Override
  public int rank(Set<ResourceType<?>> resourceTypes, Collection<ServiceConfiguration<?, ?>> serviceConfigs) {
    throw new UnsupportedOperationException("Its a Wrapper store provider, does not support regular ranking");
  }

  @Override
  public int wrapperStoreRank(Collection<ServiceConfiguration<?, ?>> serviceConfigs) {
    CacheLoaderWriterConfiguration<?> loaderWriterConfiguration = findSingletonAmongst(CacheLoaderWriterConfiguration.class, serviceConfigs);
    if (loaderWriterConfiguration == null) {
      return 0;
    }
    return 2;
  }
}


text:
#ifndef _OLSR_HOST_SWITCH
#define _OLSR_HOST_SWITCH

#include "olsr_types.h"

#define OHS_TCP_PORT 10150

#define OHS_VERSION "0.1"

#define OHS_DEFAULT_OLSRD_PATH "./olsrd"

#define OHS_OUT_OF_MEMORY(s) do { printf("ohsd: out of memory \"%s\"!\n", s); ohs_close(0); } while (0)

#ifdef _WIN32
#define close(x) closesocket(x)
int __stdcall ohs_close(unsigned long signal) __attribute__ ((noreturn));
#else /* _WIN32 */
void ohs_close(int) __attribute__ ((noreturn));
#endif /* _WIN32 */

struct ohs_ip_link {
  union olsr_ip_addr dst;
  uint8_t quality;                     /* 0 - 100 */
  struct ohs_ip_link *next;
};

struct ohs_connection {
  union olsr_ip_addr ip_addr;
  int socket;
  uint32_t rx;
  uint32_t tx;
  uint32_t linkcnt;
  struct ohs_ip_link *links;
  struct ohs_connection *next;
};

extern uint32_t logbits;

extern struct ohs_connection *ohs_conns;

#define LOG_DEFAULT 0x0
#define LOG_FORWARD 0x1
#define LOG_CONNECT 0x2
#define LOG_LINK    0x4

#ifdef _WIN32
int __stdcall SignalHandler(unsigned long);
#else /* _WIN32 */
void ohs_close(int);
#endif /* _WIN32 */

struct ohs_connection *get_client_by_addr(const union olsr_ip_addr *);

int ohs_delete_connection(struct ohs_connection *);

#endif /* _OLSR_HOST_SWITCH */

/*
 * Local Variables:
 * c-basic-offset: 2
 * indent-tabs-mode: nil
 * End:
 */


text:
using ServiceStack;

namespace Ponics.Kernel.Queries
{
    public interface IQuery<TResult> : IReturn<TResult>
    {
    }
}


text:
#ifndef DALI_INTERNAL_SCENE_GRAPH_NODE_H
#define DALI_INTERNAL_SCENE_GRAPH_NODE_H

// INTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <dali/internal/common/message.h>
#include <dali/internal/event/common/event-thread-services.h>
#include <dali/internal/render/data-providers/node-data-provider.h>
#include <dali/internal/update/common/animatable-property.h>
#include <dali/internal/update/common/inherited-property.h>
#include <dali/internal/update/common/property-owner.h>
#include <dali/internal/update/common/scene-graph-buffers.h>
#include <dali/internal/update/manager/transform-manager-property.h>
#include <dali/internal/update/manager/transform-manager.h>
#include <dali/internal/update/nodes/node-declarations.h>
#include <dali/internal/update/rendering/scene-graph-renderer.h>
#include <dali/public-api/actors/actor-enumerations.h>
#include <dali/public-api/actors/draw-mode.h>
#include <dali/public-api/math/math-utils.h>
#include <dali/public-api/math/quaternion.h>
#include <dali/public-api/math/vector3.h>

namespace Dali
{
namespace Internal
{
// Value types used by messages.
template<>
struct ParameterType<ColorMode> : public BasicType<ColorMode>
{
};
template<>
struct ParameterType<ClippingMode::Type> : public BasicType<ClippingMode::Type>
{
};

namespace SceneGraph
{
class DiscardQueue;
class Layer;
class RenderTask;
class UpdateManager;

// Flags which require the scene renderable lists to be updated
static NodePropertyFlags RenderableUpdateFlags = NodePropertyFlags::TRANSFORM | NodePropertyFlags::CHILD_DELETED;

/**
 * Node is the base class for all nodes in the Scene Graph.
 *
 * Each node provides a transformation which applies to the node and
 * its children.  Node data is double-buffered. This allows an update
 * thread to modify node data, without interferring with another
 * thread reading the values from the previous update traversal.
 */
class Node : public PropertyOwner, public NodeDataProvider
{
public:
  // Defaults
  static const ColorMode DEFAULT_COLOR_MODE;

  // Creation methods

  /**
   * Construct a new Node.
   */
  static Node* New();

  /**
   * Deletes a Node.
   */
  static void Delete(Node* node);

  /**
   * Called during UpdateManager::DestroyNode shortly before Node is destroyed.
   */
  void OnDestroy();

  /**
   * @return the unique ID of the node
   */
  uint32_t GetId() const;

  // Layer interface

  /**
   * Query whether the node is a layer.
   * @return True if the node is a layer.
   */
  bool IsLayer() const
  {
    return mIsLayer;
  }

  /**
   * Convert a node to a layer.
   * @return A pointer to the layer, or NULL.
   */
  virtual Layer* GetLayer()
  {
    return nullptr;
  }

  // Camera interface

  /**
   * Query whether the node is a camera.
   * @return True if the node is a camera.
   */
  bool IsCamera() const
  {
    return mIsCamera;
  }

  /**
   * Mark an node and its sub tree according to the updated flag.
   * @param[in] updated The updated flag
   * (used for partial rendering to mark an animating sub tree for example).
   */
  void SetUpdatedTree(bool updated)
  {
    mUpdated = updated;

    for(Node* child : mChildren)
    {
      child->SetUpdatedTree(updated);
    }
  }

  /**
   * This method sets clipping information on the node based on its hierarchy in the scene-graph.
   * A value is calculated that can be used during sorting to increase sort speed.
   * @param[in] clippingId The Clipping ID of the node to set
   * @param[in] clippingDepth The Clipping Depth of the node to set
   * @param[in] scissorDepth The Scissor Clipping Depth of the node to set
   */
  void SetClippingInformation(const uint32_t clippingId, const uint32_t clippingDepth, const uint32_t scissorDepth)
  {
    // We only set up the sort value if we have a stencil clipping depth, IE. At least 1 clipping node has been hit.
    // If not, if we traverse down a clipping tree and back up, and there is another
    // node on the parent, this will have a non-zero clipping ID that must be ignored
    if(clippingDepth > 0u)
    {
      mClippingDepth = clippingDepth;

      // Calculate the sort value here on write, as when read (during sort) it may be accessed several times.
      // The items must be sorted by Clipping ID first (so the ID is kept in the most-significant bits).
      // For the same ID, the clipping nodes must be first, so we negate the
      // clipping enabled flag and set it as the least significant bit.
      mClippingSortModifier = (clippingId << 1u) | (mClippingMode == ClippingMode::DISABLED ? 1u : 0u);
    }
    else
    {
      // If we do not have a clipping depth, then set this to 0 so we do not have a Clipping ID either.
      mClippingSortModifier = 0u;
    }

    // The scissor depth does not modify the clipping sort modifier (as scissor clips are 2D only).
    // For this reason we can always update the member variable.
    mScissorDepth = scissorDepth;
  }

  /**
   * Gets the Clipping ID for this node.
   * @return The Clipping ID for this node.
   */
  uint32_t GetClippingId() const
  {
    return mClippingSortModifier >> 1u;
  }

  /**
   * Gets the Clipping Depth for this node.
   * @return The Clipping Depth for this node.
   */
  uint32_t GetClippingDepth() const
  {
    return mClippingDepth;
  }

  /**
   * Gets the Scissor Clipping Depth for this node.
   * @return The Scissor Clipping Depth for this node.
   */
  uint32_t GetScissorDepth() const
  {
    return mScissorDepth;
  }

  /**
   * Sets the clipping mode for this node.
   * @param[in] clippingMode The ClippingMode to set
   */
  void SetClippingMode(const ClippingMode::Type clippingMode)
  {
    mClippingMode = clippingMode;
  }

  /**
   * Gets the Clipping Mode for this node.
   * @return The ClippingMode of this node
   */
  ClippingMode::Type GetClippingMode() const
  {
    return mClippingMode;
  }

  /**
   * Add a renderer to the node
   * @param[in] renderer The renderer added to the node
   */
  void AddRenderer(Renderer* renderer);

  /**
   * Remove a renderer from the node
   * @param[in] renderer The renderer to be removed
   */
  void RemoveRenderer(const Renderer* renderer);

  /*
   * Get the renderer at the given index
   * @param[in] index
   */
  Renderer* GetRendererAt(uint32_t index) const
  {
    return mRenderer[index];
  }

  /**
   * Retrieve the number of renderers for the node
   */
  uint32_t GetRendererCount() const
  {
    return static_cast<uint32_t>(mRenderer.Size());
  }

  // Containment methods

  /**
   * Query whether a node is the root node. Root nodes cannot have a parent node.
   * A node becomes a root node, when it is installed by UpdateManager.
   * @return True if the node is a root node.
   */
  bool IsRoot() const
  {
    return mIsRoot;
  }

  /**
   * Set whether a node is the root node. Root nodes cannot have a parent node.
   * This method should only be called by UpdateManager.
   * @pre When isRoot is true, the node must not have a parent.
   * @param[in] isRoot Whether the node is now a root node.
   */
  void SetRoot(bool isRoot);

  /**
   * Retrieve the parent of a Node.
   * @return The parent node, or NULL if the Node has not been added to the scene-graph.
   */
  Node* GetParent()
  {
    return mParent;
  }

  /**
   * Retrieve the parent of a Node.
   * @return The parent node, or NULL if the Node has not been added to the scene-graph.
   */
  const Node* GetParent() const
  {
    return mParent;
  }

  /**
   * @return true if the node is connected to SceneGraph
   */
  bool ConnectedToScene()
  {
    return IsRoot() || GetParent();
  }

  /**
   * Connect a node to the scene-graph.
   * @pre A node cannot be added to itself.
   * @pre The parent node is connected to the scene-graph.
   * @pre The childNode does not already have a parent.
   * @pre The childNode is not a root node.
   * @param[in] childNode The child to add.
   */
  void ConnectChild(Node* childNode);

  /**
   * Disconnect a child (& its children) from the scene-graph.
   * @pre childNode is a child of this Node.
   * @param[in] updateBufferIndex The current update buffer index.
   * @param[in] childNode The node to disconnect.
   */
  void DisconnectChild(BufferIndex updateBufferIndex, Node& childNode);

  /**
   * Retrieve the children a Node.
   * @return The container of children.
   */
  const NodeContainer& GetChildren() const
  {
    return mChildren;
  }

  /**
   * Retrieve the children a Node.
   * @return The container of children.
   */
  NodeContainer& GetChildren()
  {
    return mChildren;
  }

  // Update methods

  /**
   * Flag that one of the node values has changed in the current frame.
   * @param[in] flag The flag to set.
   */
  void SetDirtyFlag(NodePropertyFlags flag)
  {
    mDirtyFlags |= flag;
  }

  /**
   * Flag that all of the node values are dirty.
   */
  void SetAllDirtyFlags()
  {
    mDirtyFlags = NodePropertyFlags::ALL;
  }

  /**
   * Query whether a node is dirty.
   * @return The dirty flags
   */
  NodePropertyFlags GetDirtyFlags() const;

  /**
   * Query inherited dirty flags.
   *
   * @param The parentFlags to or with
   * @return The inherited dirty flags
   */
  NodePropertyFlags GetInheritedDirtyFlags(NodePropertyFlags parentFlags) const;

  /**
   * Retrieve the parent-origin of the node.
   * @return The parent-origin.
   */
  const Vector3& GetParentOrigin() const
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      return mParentOrigin.Get(0);
    }

    return Vector3::ZERO;
  }

  /**
   * Sets both the local & base parent-origins of the node.
   * @param[in] origin The new local & base parent-origins.
   */
  void SetParentOrigin(const Vector3& origin)
  {
    mParentOrigin.Set(0, origin);
  }

  /**
   * Retrieve the anchor-point of the node.
   * @return The anchor-point.
   */
  const Vector3& GetAnchorPoint() const
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      return mAnchorPoint.Get(0);
    }

    return Vector3::ZERO;
  }

  /**
   * Sets both the local & base anchor-points of the node.
   * @param[in] anchor The new local & base anchor-points.
   */
  void SetAnchorPoint(const Vector3& anchor)
  {
    mAnchorPoint.Set(0, anchor);
  }

  /**
   * Retrieve the local position of the node, relative to its parent.
   * @param[in] bufferIndex The buffer to read from.
   * @return The local position.
   */
  const Vector3& GetPosition(BufferIndex bufferIndex) const
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      return mPosition.Get(bufferIndex);
    }

    return Vector3::ZERO;
  }

  /**
   * Retrieve the position of the node derived from the position of all its parents.
   * @return The world position.
   */
  const Vector3& GetWorldPosition(BufferIndex bufferIndex) const
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      return mWorldPosition.Get(bufferIndex);
    }
    return Vector3::ZERO;
  }

  /**
   * Set whether the Node inherits position.
   * @param[in] inherit True if the parent position is inherited.
   */
  void SetInheritPosition(bool inherit)
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      mTransformManagerData.Manager()->SetInheritPosition(mTransformManagerData.Id(), inherit);
    }
  }

  /**
   * Retrieve the local orientation of the node, relative to its parent.
   * @param[in] bufferIndex The buffer to read from.
   * @return The local orientation.
   */
  const Quaternion& GetOrientation(BufferIndex bufferIndex) const
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      return mOrientation.Get(0);
    }

    return Quaternion::IDENTITY;
  }

  /**
   * Retrieve the orientation of the node derived from the rotation of all its parents.
   * @param[in] bufferIndex The buffer to read from.
   * @return The world rotation.
   */
  const Quaternion& GetWorldOrientation(BufferIndex bufferIndex) const
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      return mWorldOrientation.Get(0);
    }
    return Quaternion::IDENTITY;
  }

  /**
   * Set whether the Node inherits orientation.
   * @param[in] inherit True if the parent orientation is inherited.
   */
  void SetInheritOrientation(bool inherit)
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      mTransformManagerData.Manager()->SetInheritOrientation(mTransformManagerData.Id(), inherit);
    }
  }

  /**
   * Retrieve the local scale of the node, relative to its parent.
   * @param[in] bufferIndex The buffer to read from.
   * @return The local scale.
   */
  const Vector3& GetScale(BufferIndex bufferIndex) const
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      return mScale.Get(0);
    }

    return Vector3::ONE;
  }

  /**
   * Retrieve the scale of the node derived from the scale of all its parents.
   * @param[in] bufferIndex The buffer to read from.
   * @return The world scale.
   */
  const Vector3& GetWorldScale(BufferIndex bufferIndex) const
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      return mWorldScale.Get(0);
    }
    return Vector3::ONE;
  }

  /**
   * Set whether the Node inherits scale.
   * @param inherit True if the Node inherits scale.
   */
  void SetInheritScale(bool inherit)
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      mTransformManagerData.Manager()->SetInheritScale(mTransformManagerData.Id(), inherit);
    }
  }

  /**
   * Retrieve the visibility of the node.
   * @param[in] bufferIndex The buffer to read from.
   * @return True if the node is visible.
   */
  bool IsVisible(BufferIndex bufferIndex) const
  {
    return mVisible[bufferIndex];
  }

  /**
   * Retrieve the opacity of the node.
   * @param[in] bufferIndex The buffer to read from.
   * @return The opacity.
   */
  float GetOpacity(BufferIndex bufferIndex) const
  {
    return mColor[bufferIndex].a;
  }

  /**
   * Retrieve the color of the node.
   * @param[in] bufferIndex The buffer to read from.
   * @return The color.
   */
  const Vector4& GetColor(BufferIndex bufferIndex) const
  {
    return mColor[bufferIndex];
  }

  /**
   * Sets the color of the node derived from the color of all its parents.
   * @param[in] color The world color.
   * @param[in] updateBufferIndex The current update buffer index.
   */
  void SetWorldColor(const Vector4& color, BufferIndex updateBufferIndex)
  {
    mWorldColor.Set(updateBufferIndex, color);
  }

  /**
   * Sets the color of the node derived from the color of all its parents.
   * This method should only be called when the parents world color is up-to-date.
   * @pre The node has a parent.
   * @param[in] updateBufferIndex The current update buffer index.
   */
  void InheritWorldColor(BufferIndex updateBufferIndex)
  {
    DALI_ASSERT_DEBUG(mParent != NULL);

    // default first
    if(mColorMode == USE_OWN_MULTIPLY_PARENT_ALPHA)
    {
      const Vector4& ownColor = mColor[updateBufferIndex];
      mWorldColor.Set(updateBufferIndex, ownColor.r, ownColor.g, ownColor.b, ownColor.a * mParent->GetWorldColor(updateBufferIndex).a);
    }
    else if(mColorMode == USE_OWN_MULTIPLY_PARENT_COLOR)
    {
      mWorldColor.Set(updateBufferIndex, mParent->GetWorldColor(updateBufferIndex) * mColor[updateBufferIndex]);
    }
    else if(mColorMode == USE_PARENT_COLOR)
    {
      mWorldColor.Set(updateBufferIndex, mParent->GetWorldColor(updateBufferIndex));
    }
    else // USE_OWN_COLOR
    {
      mWorldColor.Set(updateBufferIndex, mColor[updateBufferIndex]);
    }
  }

  /**
   * Copies the previous inherited scale, if this changed in the previous frame.
   * This method should be called instead of InheritWorldScale i.e. if the inherited scale
   * does not need to be recalculated in the current frame.
   * @param[in] updateBufferIndex The current update buffer index.
   */
  void CopyPreviousWorldColor(BufferIndex updateBufferIndex)
  {
    mWorldColor.CopyPrevious(updateBufferIndex);
  }

  /**
   * Retrieve the color of the node, possibly derived from the color
   * of all its parents, depending on the value of mColorMode.
   * @param[in] bufferIndex The buffer to read from.
   * @return The world color.
   */
  const Vector4& GetWorldColor(BufferIndex bufferIndex) const
  {
    return mWorldColor[bufferIndex];
  }

  /**
   * Set the color mode. This specifies whether the Node uses its own color,
   * or inherits its parent color.
   * @param[in] colorMode The new color mode.
   */
  void SetColorMode(ColorMode colorMode)
  {
    mColorMode = colorMode;

    SetDirtyFlag(NodePropertyFlags::COLOR);
  }

  /**
   * Retrieve the color mode.
   * @return The color mode.
   */
  ColorMode GetColorMode() const
  {
    return mColorMode;
  }

  /**
   * Retrieve the size of the node.
   * @param[in] bufferIndex The buffer to read from.
   * @return The size.
   */
  const Vector3& GetSize(BufferIndex bufferIndex) const
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      return mSize.Get(0);
    }

    return Vector3::ZERO;
  }

  /**
   * Retrieve the update area hint of the node.
   * @return The update area hint.
   */
  const Vector4& GetUpdateAreaHint() const
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      return mUpdateAreaHint.Get(0);
    }

    return Vector4::ZERO;
  }

  /**
   * Retrieve the bounding sphere of the node
   * @return A vector4 describing the bounding sphere. XYZ is the center and W is the radius
   */
  const Vector4& GetBoundingSphere() const
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      return mTransformManagerData.Manager()->GetBoundingSphere(mTransformManagerData.Id());
    }

    return Vector4::ZERO;
  }

  /**
   * Retrieve world matrix and size of the node
   * @param[out] The local to world matrix of the node
   * @param[out] size The current size of the node
   */
  void GetWorldMatrixAndSize(Matrix& worldMatrix, Vector3& size) const
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      mTransformManagerData.Manager()->GetWorldMatrixAndSize(mTransformManagerData.Id(), worldMatrix, size);
    }
  }

  /**
   * Checks if local matrix has changed since last update
   * @return true if local matrix has changed, false otherwise
   */
  bool IsLocalMatrixDirty() const
  {
    return (mTransformManagerData.Id() != INVALID_TRANSFORM_ID) &&
           (mTransformManagerData.Manager()->IsLocalMatrixDirty(mTransformManagerData.Id()));
  }

  /**
   * Retrieve the cached world-matrix of a node.
   * @param[in] bufferIndex The buffer to read from.
   * @return The world-matrix.
   */
  const Matrix& GetWorldMatrix(BufferIndex bufferIndex) const
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
    {
      return mWorldMatrix.Get(bufferIndex);
    }

    return Matrix::IDENTITY;
  }

  /**
   * Mark the node as exclusive to a single RenderTask.
   * @param[in] renderTask The render-task, or NULL if the Node is not exclusive to a single RenderTask.
   */
  void SetExclusiveRenderTask(RenderTask* renderTask)
  {
    mExclusiveRenderTask = renderTask;
  }

  /**
   * Query whether the node is exclusive to a single RenderTask.
   * @return The render-task, or NULL if the Node is not exclusive to a single RenderTask.
   */
  RenderTask* GetExclusiveRenderTask() const
  {
    return mExclusiveRenderTask;
  }

  /**
   * Set how the Node and its children should be drawn; see Dali::Actor::SetDrawMode() for more details.
   * @param[in] drawMode The new draw-mode to use.
   */
  void SetDrawMode(const DrawMode::Type& drawMode)
  {
    mDrawMode = drawMode;
  }

  /**
   * Returns whether node is an overlay or not.
   * @return True if node is an overlay, false otherwise.
   */
  DrawMode::Type GetDrawMode() const
  {
    return mDrawMode;
  }

  void SetTransparent(bool transparent)
  {
    mTransparent = transparent;
  }

  bool IsTransparent() const
  {
    return mTransparent;
  }

  /*
   * Returns the transform id of the node
   * @return The transform component id of the node
   */
  TransformId GetTransformId() const
  {
    return mTransformManagerData.Id();
  }

  /**
   * Equality operator, checks for identity, not values.
   * @param[in]
   */
  bool operator==(const Node* rhs) const
  {
    return (this == rhs);
  }

  /**
   * @brief Sets the sibling order of the node
   * @param[in] order The new order
   */
  void SetDepthIndex(uint32_t depthIndex)
  {
    if(depthIndex != mDepthIndex)
    {
      SetDirtyFlag(NodePropertyFlags::DEPTH_INDEX);
      mDepthIndex = depthIndex;
    }
  }

  /**
   * @brief Get the depth index of the node
   * @return Current depth index
   */
  uint32_t GetDepthIndex() const
  {
    return mDepthIndex;
  }

  /**
   * @brief Sets the boolean which states whether the position should use the anchor-point.
   * @param[in] positionUsesAnchorPoint True if the position should use the anchor-point
   */
  void SetPositionUsesAnchorPoint(bool positionUsesAnchorPoint)
  {
    if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID && mPositionUsesAnchorPoint != positionUsesAnchorPoint)
    {
      mPositionUsesAnchorPoint = positionUsesAnchorPoint;
      mTransformManagerData.Manager()->SetPositionUsesAnchorPoint(mTransformManagerData.Id(), mPositionUsesAnchorPoint);
    }
  }

  /**
   * @brief Sets whether the node is culled or not.
   * @param[in] bufferIndex The buffer to read from.
   * @param[in] culled True if the node is culled.
   */
  void SetCulled(BufferIndex bufferIndex, bool culled)
  {
    mCulled[bufferIndex] = culled;
  }

  /**
   * @brief Retrieves whether the node is culled or not.
   * @param[in] bufferIndex The buffer to read from.
   * @return True if the node is culled.
   */
  bool IsCulled(BufferIndex bufferIndex) const
  {
    return mCulled[bufferIndex];
  }

public:
  /**
   * @copydoc Dali::Internal::SceneGraph::PropertyOwner::IsAnimationPossible
   */
  bool IsAnimationPossible() const override;

  /**
   * Called by UpdateManager when the node is added.
   * Creates a new transform component in the transform manager and initialize all the properties
   * related to the transformation
   * @param[in] transformManager A pointer to the trnasform manager (Owned by UpdateManager)
   */
  void CreateTransform(SceneGraph::TransformManager* transformManager);

  /**
   * Reset dirty flags
   */
  void ResetDirtyFlags(BufferIndex updateBufferIndex);

protected:
  /**
   * Set the parent of a Node.
   * @param[in] parentNode the new parent.
   */
  void SetParent(Node& parentNode);

protected:
  /**
   * Protected constructor; See also Node::New()
   */
  Node();

  /**
   * Protected virtual destructor; See also Node::Delete( Node* )
   * Kept protected to allow destructor chaining from layer
   */
  ~Node() override;

private: // from NodeDataProvider
  /**
   * @copydoc NodeDataProvider::GetModelMatrix
   */
  const Matrix& GetModelMatrix(BufferIndex bufferIndex) const override
  {
    return GetWorldMatrix(bufferIndex);
  }

  /**
   * @copydoc NodeDataProvider::GetRenderColor
   */
  const Vector4& GetRenderColor(BufferIndex bufferIndex) const override
  {
    return GetWorldColor(bufferIndex);
  }

  /**
   * @copydoc NodeDataProvider::GetNodeUniformMap
   */
  const UniformMap& GetNodeUniformMap() const override
  {
    return GetUniformMap();
  }

private:
  // Delete copy and move
  Node(const Node&) = delete;
  Node(Node&&)      = delete;
  Node& operator=(const Node& rhs) = delete;
  Node& operator=(Node&& rhs) = delete;

  /**
   * Recursive helper to disconnect a Node and its children.
   * Disconnected Nodes have no parent or children.
   * @param[in] updateBufferIndex The current update buffer index.
   */
  void RecursiveDisconnectFromSceneGraph(BufferIndex updateBufferIndex);

public: // Default properties
  using TransformManagerParentsOrigin = TransformManagerPropertyVector3<TRANSFORM_PROPERTY_PARENT_ORIGIN>;
  using TransformManagerAnchorPoint   = TransformManagerPropertyVector3<TRANSFORM_PROPERTY_ANCHOR_POINT>;
  using TransformManagerSize          = TransformManagerPropertyVector3<TRANSFORM_PROPERTY_SIZE>;
  using TransformManagerPosition      = TransformManagerPropertyVector3<TRANSFORM_PROPERTY_POSITION>;
  using TransformManagerScale         = TransformManagerPropertyVector3<TRANSFORM_PROPERTY_SCALE>;

  TransformManagerData               mTransformManagerData;
  TransformManagerParentsOrigin      mParentOrigin; ///< Local transform; the position is relative to this. Sets the Transform flag dirty when changed
  TransformManagerAnchorPoint        mAnchorPoint;  ///< Local transform; local center of rotation. Sets the Transform flag dirty when changed
  TransformManagerSize               mSize;         ///< Size is provided for layouting
  TransformManagerPosition           mPosition;     ///< Local transform; distance between parent-origin & anchor-point
  TransformManagerScale              mScale;        ///< Local transform; scale relative to parent node
  TransformManagerPropertyQuaternion mOrientation;  ///< Local transform; rotation relative to parent node

  AnimatableProperty<bool>    mVisible;        ///< Visibility can be inherited from the Node hierachy
  AnimatableProperty<bool>    mCulled;         ///< True if the node is culled. This is not animatable. It is just double-buffered.
  AnimatableProperty<Vector4> mColor;          ///< Color can be inherited from the Node hierarchy
  AnimatableProperty<Vector4> mUpdateAreaHint; ///< Update area hint is provided for damaged area calculation. (x, y, width, height)
                                               ///< This is not animatable. It is just double-buffered. (Because all these bloody properties are).

  // Inherited properties; read-only from public API

  TransformManagerVector3Input    mWorldPosition; ///< Full inherited position
  TransformManagerVector3Input    mWorldScale;
  TransformManagerQuaternionInput mWorldOrientation; ///< Full inherited orientation
  TransformManagerMatrixInput     mWorldMatrix;      ///< Full inherited world matrix
  InheritedColor                  mWorldColor;       ///< Full inherited color

  uint32_t       mClippingSortModifier; ///< Contains bit-packed clipping information for quick access when sorting
  const uint32_t mId;                   ///< The Unique ID of the node.

protected:
  static uint32_t mNodeCounter; ///< count of total nodes, used for unique ids

  Node*       mParent;              ///< Pointer to parent node (a child is owned by its parent)
  RenderTask* mExclusiveRenderTask; ///< Nodes can be marked as exclusive to a single RenderTask

  RendererContainer mRenderer; ///< Container of renderers; not owned

  NodeContainer mChildren; ///< Container of children; not owned

  uint32_t mClippingDepth; ///< The number of stencil clipping nodes deep this node is
  uint32_t mScissorDepth;  ///< The number of scissor clipping nodes deep this node is

  uint32_t mDepthIndex; ///< Depth index of the node

  // flags, compressed to bitfield
  NodePropertyFlags  mDirtyFlags;                  ///< Dirty flags for each of the Node properties
  DrawMode::Type     mDrawMode : 3;                ///< How the Node and its children should be drawn
  ColorMode          mColorMode : 3;               ///< Determines whether mWorldColor is inherited, 2 bits is enough
  ClippingMode::Type mClippingMode : 3;            ///< The clipping mode of this node
  bool               mIsRoot : 1;                  ///< True if the node cannot have a parent
  bool               mIsLayer : 1;                 ///< True if the node is a layer
  bool               mIsCamera : 1;                ///< True if the node is a camera
  bool               mPositionUsesAnchorPoint : 1; ///< True if the node should use the anchor-point when calculating the position
  bool               mTransparent : 1;             ///< True if this node is transparent. This value do not affect children.

  // Changes scope, should be at end of class
  DALI_LOG_OBJECT_STRING_DECLARATION;
};

// Messages for Node

inline void SetInheritOrientationMessage(EventThreadServices& eventThreadServices, const Node& node, bool inherit)
{
  using LocalType = MessageValue1<Node, bool>;

  // Reserve some memory inside the message queue
  uint32_t* slot = eventThreadServices.ReserveMessageSlot(sizeof(LocalType));

  // Construct message in the message queue memory; note that delete should not be called on the return value
  new(slot) LocalType(&node, &Node::SetInheritOrientation, inherit);
}

inline void SetParentOriginMessage(EventThreadServices& eventThreadServices, const Node& node, const Vector3& origin)
{
  using LocalType = MessageValue1<Node, Vector3>;

  // Reserve some memory inside the message queue
  uint32_t* slot = eventThreadServices.ReserveMessageSlot(sizeof(LocalType));

  // Construct message in the message queue memory; note that delete should not be called on the return value
  new(slot) LocalType(&node, &Node::SetParentOrigin, origin);
}

inline void SetAnchorPointMessage(EventThreadServices& eventThreadServices, const Node& node, const Vector3& anchor)
{
  using LocalType = MessageValue1<Node, Vector3>;

  // Reserve some memory inside the message queue
  uint32_t* slot = eventThreadServices.ReserveMessageSlot(sizeof(LocalType));

  // Construct message in the message queue memory; note that delete should not be called on the return value
  new(slot) LocalType(&node, &Node::SetAnchorPoint, anchor);
}

inline void SetInheritPositionMessage(EventThreadServices& eventThreadServices, const Node& node, bool inherit)
{
  using LocalType = MessageValue1<Node, bool>;

  // Reserve some memory inside the message queue
  uint32_t* slot = eventThreadServices.ReserveMessageSlot(sizeof(LocalType));

  // Construct message in the message queue memory; note that delete should not be called on the return value
  new(slot) LocalType(&node, &Node::SetInheritPosition, inherit);
}

inline void SetInheritScaleMessage(EventThreadServices& eventThreadServices, const Node& node, bool inherit)
{
  using LocalType = MessageValue1<Node, bool>;

  // Reserve some memory inside the message queue
  uint32_t* slot = eventThreadServices.ReserveMessageSlot(sizeof(LocalType));

  // Construct message in the message queue memory; note that delete should not be called on the return value
  new(slot) LocalType(&node, &Node::SetInheritScale, inherit);
}

inline void SetColorModeMessage(EventThreadServices& eventThreadServices, const Node& node, ColorMode colorMode)
{
  using LocalType = MessageValue1<Node, ColorMode>;

  // Reserve some memory inside the message queue
  uint32_t* slot = eventThreadServices.ReserveMessageSlot(sizeof(LocalType));

  // Construct message in the message queue memory; note that delete should not be called on the return value
  new(slot) LocalType(&node, &Node::SetColorMode, colorMode);
}

inline void SetDrawModeMessage(EventThreadServices& eventThreadServices, const Node& node, DrawMode::Type drawMode)
{
  using LocalType = MessageValue1<Node, DrawMode::Type>;

  // Reserve some memory inside the message queue
  uint32_t* slot = eventThreadServices.ReserveMessageSlot(sizeof(LocalType));

  // Construct message in the message queue memory; note that delete should not be called on the return value
  new(slot) LocalType(&node, &Node::SetDrawMode, drawMode);
}

inline void SetTransparentMessage(EventThreadServices& eventThreadServices, const Node& node, bool transparent)
{
  using LocalType = MessageValue1<Node, bool>;

  // Reserve some memory inside the message queue
  uint32_t* slot = eventThreadServices.ReserveMessageSlot(sizeof(LocalType));

  // Construct message in the message queue memory; note that delete should not be called on the return value
  new(slot) LocalType(&node, &Node::SetTransparent, transparent);
}

inline void DetachRendererMessage(EventThreadServices& eventThreadServices, const Node& node, const Renderer& renderer)
{
  using LocalType = MessageValue1<Node, const Renderer*>;

  // Reserve some memory inside the message queue
  uint32_t* slot = eventThreadServices.ReserveMessageSlot(sizeof(LocalType));

  // Construct message in the message queue memory; note that delete should not be called on the return value
  new(slot) LocalType(&node, &Node::RemoveRenderer, &renderer);
}

inline void SetDepthIndexMessage(EventThreadServices& eventThreadServices, const Node& node, uint32_t depthIndex)
{
  using LocalType = MessageValue1<Node, uint32_t>;

  // Reserve some memory inside the message queue
  uint32_t* slot = eventThreadServices.ReserveMessageSlot(sizeof(LocalType));

  // Construct message in the message queue memory; note that delete should not be called on the return value
  new(slot) LocalType(&node, &Node::SetDepthIndex, depthIndex);
}

inline void SetClippingModeMessage(EventThreadServices& eventThreadServices, const Node& node, ClippingMode::Type clippingMode)
{
  using LocalType = MessageValue1<Node, ClippingMode::Type>;

  // Reserve some memory inside the message queue
  uint32_t* slot = eventThreadServices.ReserveMessageSlot(sizeof(LocalType));

  // Construct message in the message queue memory; note that delete should not be called on the return value
  new(slot) LocalType(&node, &Node::SetClippingMode, clippingMode);
}

inline void SetPositionUsesAnchorPointMessage(EventThreadServices& eventThreadServices, const Node& node, bool positionUsesAnchorPoint)
{
  using LocalType = MessageValue1<Node, bool>;

  // Reserve some memory inside the message queue
  uint32_t* slot = eventThreadServices.ReserveMessageSlot(sizeof(LocalType));

  // Construct message in the message queue memory; note that delete should not be called on the return value
  new(slot) LocalType(&node, &Node::SetPositionUsesAnchorPoint, positionUsesAnchorPoint);
}

} // namespace SceneGraph

// Template specialisation for OwnerPointer<Node>, because delete is protected
template<>
inline void OwnerPointer<Dali::Internal::SceneGraph::Node>::Reset()
{
  if(mObject != nullptr)
  {
    Dali::Internal::SceneGraph::Node::Delete(mObject);
    mObject = nullptr;
  }
}
} // namespace Internal

// Template specialisations for OwnerContainer<Node*>, because delete is protected
template<>
inline void OwnerContainer<Dali::Internal::SceneGraph::Node*>::Delete(Dali::Internal::SceneGraph::Node* pointer)
{
  Dali::Internal::SceneGraph::Node::Delete(pointer);
}
} // namespace Dali

#endif // DALI_INTERNAL_SCENE_GRAPH_NODE_H


text:
'use strict';

var idGen = 0;

function MockApp(opts) {
  /* default values */
  this.origin = 'https://testapp.gaiamobile.org';
  this.manifestURL = 'https://testapp.gaiamobile.org/manifest' +
                      idGen + '.webapp';
  this.manifest = {
    name: 'Mock app'
  };

  this.removable = true;
  this.installState = 'installed';
  this.downloadAvailable = false;
  this.downloadError = null;
  this.downloadSize = null;

  this.mId = idGen++;
  this.mDownloadCalled = false;
  this.mCancelCalled = false;

  /* overwrite default values with whatever comes in "opts" from the test */
  if (opts) {
    for (var key in opts) {
      this[key] = opts[key];
    }
  }
}

MockApp.prototype.download = function() {
  this.mDownloadCalled = true;
};

MockApp.prototype.cancelDownload = function() {
  this.mCancelCalled = true;
};

MockApp.prototype.mTriggerDownloadAvailable = function(size) {
  this.downloadAvailable = true;
  this.downloadSize = size;
  if (this.ondownloadavailable) {
    this.ondownloadavailable({
        application: this
    });
  }
};

MockApp.prototype.mTriggerDownloadSuccess = function() {
  this.downloadAvailable = false;
  this.downloadSize = null;
  if (this.ondownloadsuccess) {
    this.ondownloadsuccess({
        application: this
    });
  }
};

MockApp.prototype.mTriggerDownloadError = function(error) {
  this.downloadSize = null;

  this.downloadError = {
    name: error || 'UNKNOWN_ERROR'
  };

  if (this.ondownloaderror) {
    this.ondownloaderror({
        application: this
    });
  }
};

MockApp.prototype.mTriggerDownloadProgress = function(progress) {
  this.progress = progress;

  if (this.onprogress) {
    this.onprogress({
        application: this
    });
  }
};

MockApp.prototype.mTriggerDownloadApplied = function() {
  this.downloadAvailable = false;
  this.downloadSize = null;
  if (this.ondownloadapplied) {
    this.ondownloadapplied({
        application: this
    });
  }
};


text:
package org.apache.hadoop.hive.ql.optimizer.calcite.rules;

import org.apache.calcite.plan.RelOptPredicateList;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.calcite.plan.RelOptRule;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Aggregate;
import org.apache.calcite.rel.core.Filter;
import org.apache.calcite.rel.core.Join;
import org.apache.calcite.rel.core.Project;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexInputRef;
import org.apache.calcite.rex.RexCall;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.SqlKind;
import org.apache.hadoop.hive.ql.optimizer.calcite.HiveRelFactories;
import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveFilter;
import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveJoin;

import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;

/**
 * Planner rule that removes UDF sq_count_check from a plan if
 *  1) either group by keys in a subquery are constant and there is no windowing or grouping sets
 *  2) OR there are no group by keys but only aggregate
 *  Both of the above case will produce at most one row, therefore it is safe to remove sq_count_check
 *    which was introduced earlier in the plan to ensure that this condition is met at run time
 */
public class HiveRemoveSqCountCheck extends RelOptRule {

  public static final HiveRemoveSqCountCheck INSTANCE =
          new HiveRemoveSqCountCheck();

  //match if there is filter (sq_count_check) as right input of a join which is left
  // input of another join
  public HiveRemoveSqCountCheck() {
    super(operand(Join.class,
        some(
            operand(Project.class,
                operand(Join.class,
                    some(
                        operand(RelNode.class, any()),
                        operand(Filter.class, any())))
            ),
            operand(Project.class,
                operand(Aggregate.class,
                    any()))
        )
    ), HiveRelFactories.HIVE_BUILDER, "HiveRemoveSqCountCheck");
  }

  @Override
  public boolean matches(RelOptRuleCall call) {
    final RelNode filter = call.rel(4);
    if(filter instanceof HiveFilter) {
      HiveFilter hiveFilter = (HiveFilter)filter;
      // check if it has sq_count_check
      return isSqlCountCheck(hiveFilter);
    }
    return false;
  }

  private boolean isSqlCountCheck(final HiveFilter filter) {
    // look at hivesubqueryremoverule to see how is this filter created
    if(filter.getCondition() instanceof RexCall) {
      final RexCall condition = (RexCall)filter.getCondition();
      return condition.getOperator().getName().equals("sq_count_check");
    }
    return false;
  }

  private boolean isAggregateWithoutGbyKeys(final Aggregate agg) {
    return agg.getGroupCount() == 0;
  }

  private boolean isAggWithConstantGbyKeys(final Aggregate aggregate, RelOptRuleCall call) {
    final RexBuilder rexBuilder = aggregate.getCluster().getRexBuilder();
    final RelMetadataQuery mq = call.getMetadataQuery();
    final RelOptPredicateList predicates =
        mq.getPulledUpPredicates(aggregate.getInput());
    if (predicates == null) {
      return false;
    }
    final NavigableMap<Integer, RexNode> map = new TreeMap<>();
    for (int key : aggregate.getGroupSet()) {
      final RexInputRef ref =
          rexBuilder.makeInputRef(aggregate.getInput(), key);
      if (predicates.constantMap.containsKey(ref)) {
        map.put(key, predicates.constantMap.get(ref));
      }
    }

    // None of the group expressions are constant. Nothing to do.
    if (map.isEmpty()) {
      return false;
    }

    final int groupCount = aggregate.getGroupCount();
    if (groupCount == map.size()) {
      return true;
    }
    return false;
  }

  @Override public void onMatch(RelOptRuleCall call) {
    final Join topJoin= call.rel(0);
    final Join join = call.rel(2);
    final Aggregate aggregate = call.rel(6);

    // in presence of grouping sets we can't remove sq_count_check
    if(aggregate.indicator) {
      return;
    }
    if(isAggregateWithoutGbyKeys(aggregate) || isAggWithConstantGbyKeys(aggregate, call)) {
      // join(left, join.getRight)
      RelNode newJoin = HiveJoin.getJoin(topJoin.getCluster(), join.getLeft(),  topJoin.getRight(),
          topJoin.getCondition(), topJoin.getJoinType());
      call.transformTo(newJoin);
    }
  }
}


text:
var user_callback;

$(function() {

      // Placeholder for user defined callback function
      var $ld = $(document.createElement('div')).attr('id','login-dialog').attr('title','KBase Login');
      $ld.load('{{base_url}}{% url session.login-form %}' ).appendTo('body');
      $ld.attr('style','height: "auto" ');

      $ld.dialog(
          {
              autoOpen : false,
              modal : true,
              resizable: true,
	      width : 'auto',
              buttons : {
                  Cancel : function () {
                      $( this ).dialog('close');
                  },
                  Login : function() {

                      var username = $("#login-username").val();
                      var password = $("#login-password").val();

                      $(this).trigger('message', username);

                      login.call(this, username, password, function(success, args) {

                                     if ( success ) {
                                         $(this).trigger('clearMessages');
                                         $("#login-entrance").hide();
                                         $("#login-loggedinusername").text(args.username);
                                         $("#login-loggedinsession").text(args.kbase_sessionid);
                                         $("#login-userdisplay").show();
                                         $(this).dialog('close');
					 if (user_callback) {
					     user_callback( args);
					 }
                                     }
                                     else {
                                         $(this).trigger('error', args.message);
                                     }
                                 });

                  },
                  Logout : function() {
		      logout();
                      $(this).trigger('clearMessages');
		      $('#form_input').show();
		      $(".ui-dialog-buttonpane button:contains('Login')").button("enable");
		      $(".ui-dialog-buttonpane button:contains('Logout')").button("disable");

                  },
              },
              open : function() {
                  $('form', $(this))[0].reset();
                  $(this).trigger('clearMessages');
                  $(this).unbind('keypress');
		  $(".ui-dialog-buttonpane button:contains('Logout')").button("disable");
                  $(this).keypress(function(e) {
                                       if (e.keyCode == $.ui.keyCode.ENTER) {
                                           $('button:last', $(this).parent()).trigger("click");
                                           e.stopPropagation();
                                       }
                                   });
              },
          }
      );

      $ld.bind('error', function(event, msg) {
		   $(this).attr('style','height: "auto" ');
                   $(this).trigger('clearMessages');
                   $("#login-error").show();
                   $("#login-errormsg").html(msg);
               });

      $ld.bind('message', function(event, msg) {
		   $(this).attr('style','height: "auto" ');
                   $(this).trigger('clearMessages');
                   $("#login-pending").show();
                   $("#login-pendinguser").html(msg);
               });

      $ld.bind('already_logged_in', function(event, msg) {
		   $(this).attr('style','height: "auto" ');
                   $(this).trigger('clearMessages');
                   $("#login-pending").hide();
                   $("#form_input").hide();
                   $("#already_logged_in").show();
                   $("#logged_in_user").html(msg);
		   $(".ui-dialog-buttonpane button:contains('Login')").button("disable");
		   $(".ui-dialog-buttonpane button:contains('Logout')").button("enable");

               });

      $ld.bind('clearMessages', function(event) {
                   $("#login-error").hide();
                   $("#login-pending").hide();
                   $("#already_logged_in").hide();
               });

      $( "#login-widget button" ).button();

  });

function login(username, password, callback) {

    // STEVE -

    // do whatever you need to do here to log the user into of the system
    // Right now the callback function takes a boolean and an object. the boolean
    // is whether or not the login was successful, and the object is just an arbitrary context.
    //
    // Right now, the important args keys that should be populated are:
    //
    // username - the user logged in. This can be the actual username, or a human readable name.
    //            we can break that out into separate keys if that seems useful.
    // message  - any status message provided. Usually a reason the login failed.

    //this is the boolean that gets passed into the callback to determine whether or not it was a succesful login.
    var status = 1;
    //and the arbitrary args, pre-populated with the username for your convenience.
    var args = { username : username };

    // this is just here to simulate the time of a login negotiation taking place. Set the value to 0
    // when in production to skip the arbitrary 1 second delay.
    // When running as a demo, it also randomly fails to login sometimes.
    var logindemo = 1;

    // here's a couple of simple cases that need to be handled somewhere. Figured I'd just toss 'em into this function
    // to keep 'em all in one place.
    var that = this;
    if (username.length == 0) {
        args.message = 'Cannot login w/o username';
        status = 0;
        callback.call(that, status, args);
    } else if (password.length == 0) {
        args.message = 'Cannot login w/o password';
        status = 0;
        callback.call(that, status, args);

    } else {
	var form_params = {
	    'user_id' : username,
	    'password' : password,
	    'cookie' : 1,
	    'fields' : 'token,user_id,name'
	};
	if (! user_callback) {
	//    form_params.cookie = "only";
	}
        $.ajax({ type: "POST",
		 url: "https://www.kbase.us/services/authorization/Sessions/Login",
		 //data : { 'user_id' : username,
		 //	  'password' : password,
		 //	  'cookie' : 'only' },
		 data : form_params,
		 dataType: "json",
		 crossDomain : true,
		 xhrFields: { withCredentials: true },
		 success: function (data,res,jqXHR) {
		     var args = {};
		     var cookie = '';
		     // Look for a kbase_session cookie
		     if (user_callback) {
			 if ('token' in data) {
			     args = data
			     callback.call(that,1,args)
			 } else {
			     args.message = data.error_msg;
			     callback.call(that,0,args);
			 }
		     } else {
			 var i,x,y,ARRcookies=document.cookie.split(";");
			 for (i=0;i<ARRcookies.length;i++) {
			     x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
			     y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
			     x=x.replace(/^\s+|\s+$/g,"");
			     if (x=='kbase_session') {
				 cookie = unescape(y);
			     }
			 }
			 if ( cookie ) {
			     var m = /un=(\w+)\|kbase_sessionid=(\w+)/g.exec( cookie );
			     args.username = m[1];
			     args.kbase_sessionid = m[2];
			     callback.call(that,1,args)
			 } else {
			     args.message = 'Failed to authenticate';
			     callback.call(that,0,args);
			 }
		     }
		 },
		 error: function (jqXHR, textStatus, errorThrown) {
		     // If we have a useless error message, replace with
		     // friendly, but useless error message
		     if (textStatus == "error") {
			 textStatus = "Error connecting to KBase login server";
		     }
		     callback.call(that,0, { 'message' : textStatus })
		 },
		 xhrFields: {
		     withCredentials: true
		 },
		 beforeSend : function(xhr){
		     // make cross-site requests
		     xhr.withCredentials = true;
		 },
	       });
    }
}

function get_kbase_cookie() {
    var cookie = '';
    var args = {};

    // Look for a kbase_session cookie
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
	x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
	y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
	x=x.replace(/^\s+|\s+$/g,"");
	if (x=='kbase_session') {
	    cookie = unescape(y);
	}
    }
    var m = /un=(\w+)\|kbase_sessionid=(\w+)/g.exec( cookie );
    if (m) {
	args.username = m[1];
	args.kbase_sessionid = m[2];
    }
    return( args);
}

function logout() {

    // Expire the current session cookie
    cookie = 'kbase_session=; domain=.kbase.us; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/';
    document.cookie = cookie;

    //automatically prompt to log in again
    $('#login-dialog').dialog('open');
}

function login_dialog( callback ) {
    var args = get_kbase_cookie();

    $('#login-dialog').dialog('open');
    if (callback) {
	user_callback = callback;
    }

    if ('username' in args) {
	$('#login-dialog').trigger('already_logged_in', args.username)
    }
}


text:
@interface SMArtistBiosResult ()

- (void)setCombinedResults:(NSArray *)results;

@end

@implementation SMArtistBiosResult
{
	@private
    NSArray *bios;
}

@synthesize bios;

+ (SMArtistBiosResult *)result
{
    SMArtistBiosResult *empty = [[SMArtistBiosResult alloc] init];
    return empty;
}

- (id)init
{
	return [self initWithResults:nil];
}

- (id)initWithResults:(NSArray *)results {
    self = [super init];
    if (self) {
		[self setCombinedResults:results];
    }

    return self;
}

- (void)setCombinedResults:(NSArray *)results {
    NSMutableSet *newBios = [NSMutableSet set];
    for (SMArtistBiosResult *result in results) {
		[self mergeProperties:result];
		[newBios addObjectsFromArray:result.bios];
    }
    self.bios = [newBios allObjects];
}

- (NSString *)description
{
    NSMutableString *desc = [NSMutableString stringWithString:@"SMArtistBiosResult with Bios:\n"];

    for (SMArtistBio *bio in self.bios) {
        [desc appendFormat:@"\n%@",[bio description]];
    }

    return desc;
}

- (void) encodeWithCoder:(NSCoder *)encoder {
    [super encodeWithCoder:encoder];
    [encoder encodeObject:bios forKey:kBios];
}

- (id)initWithCoder:(NSCoder *)decoder {
    self = [super initWithCoder:decoder];
    if (self) {
        self.bios = [decoder decodeObjectForKey:kBios];
    }
    return self;
}

@end