text:
using System.Xml;
using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace ETWManifest
{
    /// <summary>
    /// A ProviderManifest represents the XML manifest associated with the provider.
    /// </summary>
    public sealed class Provider
    {
        public static List<Provider> ParseManifest(string manifest)
        {
            var xmlReader = XmlReader.Create(manifest, new XmlReaderSettings() { IgnoreComments = true, IgnoreWhitespace = true });
            return ParseManifest(xmlReader, manifest);
        }
        public static List<Provider> ParseManifest(XmlReader reader, string fileName = null)
        {
            var ret = new List<Provider>();
            if (reader.ReadToDescendant("events"))
            {
                using (var events = reader.ReadSubtree())
                {
                    if (events.ReadToDescendant("provider"))
                    {
                        do
                        {
                            ret.Add(new Provider(reader, fileName));
                        } while (events.ReadToNextSibling("provider"));
                    }
                }
            }

            // Resolve all the localization strings that may have been used.
            //m_stringMap = new Dictionary<string, string>();
            //while (reader.Read())
            //{
            //    if (reader.NodeType == XmlNodeType.Element && reader.Name == "string")
            //    {
            //        var id = reader.GetAttribute("id");
            //        var value = reader.GetAttribute("value");
            //        m_stringMap[id] = value;
            //    }
            //}

            // Resolve all the localization strings that may have been used.
            if (0 < m_stringMap.Count)
            {
                foreach (var provider in ret)
                {
                    if (provider.m_keywordNames != null)
                    {
                        for (int i = 0; i < provider.m_keywordNames.Length; i++)
                            Provider.Replace(ref provider.m_keywordNames[i], m_stringMap);
                    }

                    if (provider.m_taskNames != null)
                    {
                        foreach (var taskId in new List<int>(provider.m_taskNames.Keys))
                        {
                            var taskName = provider.m_taskNames[taskId];
                            if (Provider.Replace(ref taskName, m_stringMap))
                                provider.m_taskNames[taskId] = taskName;
                        }
                    }

                    if (provider.m_opcodeNames != null)
                    {
                        foreach (var opcodeId in new List<int>(provider.m_opcodeNames.Keys))
                        {
                            var opcodeName = provider.m_opcodeNames[opcodeId];
                            if (Provider.Replace(ref opcodeName, m_stringMap))
                                provider.m_opcodeNames[opcodeId] = opcodeName;
                        }
                    }

                    foreach (Event ev in provider.Events)
                        ev.UpdateStrings(m_stringMap);
                }
            }

            return ret;
        }

        /// <summary>
        /// The name of the ETW provider
        /// </summary>
        public string Name { get; private set; }
        /// <summary>
        /// The GUID that uniquely identifies the ETW provider
        /// </summary>
        public Guid Id { get; private set; }
        /// <summary>
        /// The events for the
        /// </summary>
        public IList<Event> Events { get { return m_events; } }

        /* Support for pretty printing the Keywords */
        /// <summary>
        /// returns the name of the keyword which has the bit position bitPos
        /// (bitPos is 0 through 63).   It may return null if there is no
        /// keyword name for 'bitPos'.
        /// </summary>
        public string GetKeywordName(int bitPos)
        {
            Debug.Assert(0 <= bitPos && bitPos < 64);
            if (m_keywordNames == null)
                return null;

            return m_keywordNames[bitPos];
        }
        /// <summary>
        /// returns a string that is the best human readable representation of the keyword set
        /// represented by 'keywords'.   It the concatenation of all the keyword names separated
        /// by a comma, as well as a hexadecimal number (if there is anything that can't be
        /// represented by names).
        /// </summary>
        public string GetKeywordSetString(ulong keywords, string separator = ",")
        {
            var ret = "";
            ulong bitsWithNoName = 0;
            ulong bit = 1;
            for (int bitPos = 0; bitPos < 64; bitPos++)
            {
                if (keywords == 0)
                    break;
                if ((bit & keywords) != 0)
                {
                    var name = m_keywordNames[bitPos];
                    if (name != null)
                    {
                        if (ret.Length != 0)
                            ret += separator;
                        ret += name;
                    }
                    else
                        bitsWithNoName |= bit;
                }
                bit = bit << 1;
            }
            if (bitsWithNoName != 0)
            {
                if (ret.Length != 0)
                    ret += separator;
                ret += "0x" + bitsWithNoName.ToString("x");
            }
            if (ret.Length == 0)
                ret = "0";
            return ret;
        }

        /* These are relatively rare APIs, normally you only care in the context of an event */
        public string GetTaskName(ushort taskId)
        {
            if (m_taskNames == null)
                return "";
            string ret;
            if (m_taskNames.TryGetValue(taskId, out ret))
                return ret;
            if (taskId == 0)
                return "";
            return "Task" + taskId.ToString();
        }

        public string GetOpcodeName(ushort taskId, byte opcodeId)
        {
            int value = opcodeId + (taskId * 256);
            string ret;
            if (m_opcodeNames.TryGetValue(value, out ret))
                return ret;

            value = opcodeId + (GlobalScope * 256);
            if (m_opcodeNames.TryGetValue(value, out ret))
                return ret;
            return "Opcode" + opcodeId;
        }

        /// <summary>
        /// For debugging
        /// </summary>
        public override string ToString() { return Name + " " + Id; }

        #region private
        // create a manifest from a stream or a file
        /// <summary>
        /// Read a ProviderManifest from a stream
        /// </summary>
        internal Provider(XmlReader reader, string fileName)
        {
            var lineInfo = (IXmlLineInfo)reader;
            try
            {
                Debug.Assert(reader.NodeType == XmlNodeType.Element && reader.Name == "provider",
                    "Must advance to provider element (e.g. call ReadToDescendant)");

                m_enums = new Dictionary<string, Enumeration>();
                m_templateValues = new Dictionary<string, List<Field>>();
                InitStandardOpcodes();

                Name = reader.GetAttribute("name");
                Id = Guid.Parse(reader.GetAttribute("guid"));

                var inputDepth = reader.Depth;
                reader.Read();      // Advance to children
                var curTask = GlobalScope;
                var curTaskDepth = int.MaxValue;
                //while (inputDepth < reader.Depth)
                while (!reader.EOF)
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        switch (reader.Name)
                        {
                            case "keyword":
                                {
                                    if (m_keywordNames == null)
                                    {
                                        m_keywordNames = new string[64];
                                        m_keywordValues = new Dictionary<string, ulong>();
                                    }
                                    string name = reader.GetAttribute("name");
                                    string valueString = reader.GetAttribute("mask");
                                    ulong value = ParseNumber(valueString);
                                    int keywordIndex = GetBitPosition(value);

                                    string message = reader.GetAttribute("message");
                                    if (message == null)
                                        message = name;

                                    m_keywordNames[keywordIndex] = message;
                                    m_keywordValues.Add(name, value);
                                    reader.Skip();
                                } break;
                            case "task":
                                {
                                    if (m_taskNames == null)
                                    {
                                        m_taskNames = new Dictionary<int, string>();
                                        m_taskValues = new Dictionary<string, int>();
                                    }
                                    string name = reader.GetAttribute("name");
                                    int value = (int)ParseNumber(reader.GetAttribute("value"));

                                    string message = reader.GetAttribute("message");
                                    if (message == null)
                                        message = name;

                                    m_taskNames.Add(value, name);
                                    m_taskValues.Add(name, value);

                                    // Remember enuough to resolve opcodes nested inside this task.
                                    curTask = value;
                                    curTaskDepth = reader.Depth;
                                    reader.Read();
                                } break;
                            case "opcode":
                                {
                                    string name = reader.GetAttribute("name");
                                    int value = (int)ParseNumber(reader.GetAttribute("value"));
                                    int taskForOpcode = GlobalScope;
                                    if (reader.Depth > curTaskDepth)
                                        taskForOpcode = curTask;

                                    string message = reader.GetAttribute("message");
                                    if (message == null)
                                        message = name;

                                    AddOpcode(taskForOpcode, value, message, name);
                                    reader.Skip();
                                    break;
                                }
                            case "event":
                                m_events.Add(new Event(reader, this, lineInfo.LineNumber));
                                break;
                            case "template":
                                ReadTemplate(reader);
                                break;
                            case "bitMap":
                                ReadMap(reader, true);
                                break;
                            case "valueMap":
                                ReadMap(reader, false);
                                break;

                            case "string":
                                if (m_stringMap == null)
                                    m_stringMap = new Dictionary<string, string>();

                                var id = reader.GetAttribute("id");
                                var stringValue = reader.GetAttribute("value");
                                m_stringMap[id] = stringValue;
                                reader.Read();
                                break;
                            default:
                                Debug.WriteLine("Skipping unknown element {0}", reader.Name);
                                reader.Read();
                                break;
                        }
                    }
                    else if (!reader.Read())
                        break;
                }
            }
            catch (Exception e)
            {
                if (fileName == null)
                    fileName = "";
                var message = "Error on line " + fileName + "(" + lineInfo.LineNumber + "," + lineInfo.LinePosition + "): " + e.Message;
                throw new ApplicationException(message, e);
            }

            // Second pass, look up any Ids used in the events.
            foreach (var ev in m_events)
                ev.ResolveIdsInEvent(fileName);

            // We are done with these.  Free up some space.
            m_taskValues = null;
            m_opcodeValues = null;
            m_keywordValues = null;
            m_templateValues = null;
            m_enums = null;
        }

        // opcodes live inside a particular task, or you can have 'global' scope for the
        // opcode.   'GlobalScope' is a 'task' for this global scope.  Just needs to be an illegal task number.
        private const int GlobalScope = 0x10000;
        /// <summary>
        /// Adds an opcode with a  given name to the database.   'taskId' can be GlobalScope
        /// if the opcode works for any task.   'manifestName' is the name in the manifest (e.g. "win:Stop")
        /// and 'name' is the name that you will print (e.g. "Stop").   If manifestName is null then
        /// name and manifest name are considered the same.
        /// </summary>
        private void AddOpcode(int taskId, int opcodeId, string name, string manifestName = null)
        {
            Debug.Assert(0 <= taskId && taskId <= GlobalScope);
            Debug.Assert(0 <= opcodeId && opcodeId < 256);
            int value = opcodeId + (taskId * 256);
            m_opcodeNames.Add(value, name);
            if (manifestName == null)
                manifestName = name;
           if(!m_opcodeValues.ContainsKey(manifestName))
                m_opcodeValues.Add(manifestName, value);
        }

        internal static ulong ParseNumber(string valueString)
        {
            if (valueString.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                return ulong.Parse(valueString.Substring(2), System.Globalization.NumberStyles.AllowHexSpecifier);
            return ulong.Parse(valueString);
        }

        private static int GetBitPosition(ulong value)
        {
            if (value == 0)
                throw new ApplicationException("Keyword is not a power of 2");
            int ret = 0;
            for (; ; )
            {
                if (((int)value & 1) != 0)
                {
                    if (value == 0)
                        throw new ApplicationException("Keyword is not a power of 2");
                    break;
                }
                value = value >> 1;
                ret++;
            }
            return ret;
        }

        internal static bool Replace(ref string value, Dictionary<string, string> map)
        {
            if (value == null)
                return false;
            if (!value.Contains("$(string."))
                return false;

            var ret = false;
            value = Regex.Replace(value, @"\$\(string\.(.*)\)", delegate(Match m)
            {
                ret = true;
                var key = m.Groups[1].Value;
                return map[key];
            });
            return ret;
        }

        private void InitStandardOpcodes()
        {
            m_opcodeNames = new Dictionary<int, string>();
            m_opcodeValues = new Dictionary<string, int>();
            AddOpcode(GlobalScope, 0, "", "win:Info");
            AddOpcode(GlobalScope, 1, "Start", "win:Start");
            AddOpcode(GlobalScope, 2, "Stop", "win:Stop");
            AddOpcode(GlobalScope, 3, "DC_Start", "win:DC_Start");
            AddOpcode(GlobalScope, 4, "DC_Stop", "win:DC_Stop");
            AddOpcode(GlobalScope, 5, "Extension", "win:Extension");
            AddOpcode(GlobalScope, 6, "Reply", "win:Reply");
            AddOpcode(GlobalScope, 7, "Resume", "win:Resume");
            AddOpcode(GlobalScope, 8, "Suspend", "win:Suspend");
            AddOpcode(GlobalScope, 9, "Send", "win:Send");
            AddOpcode(GlobalScope, 240, "Receive", "win:Receive");
        }

        private void ReadMap(XmlReader reader, bool isBitMap)
        {
            Debug.Assert(reader.NodeType == XmlNodeType.Element && (reader.Name == "bitMap" || reader.Name == "valueMap"),
                "Must advance to bitMap/valueMap element (e.g. call ReadToDescendant)");

            string name = reader.GetAttribute("name");
            Enumeration enumeration = new Enumeration(name, isBitMap);
            var inputDepth = reader.Depth;
            reader.Read();      // Advance to children
            while (inputDepth < reader.Depth)
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                        case "map":
                            {
                                int value = (int)ParseNumber(reader.GetAttribute("value"));
                                string message = reader.GetAttribute("message");
                                enumeration.Add(value, message);
                            } break;
                        default:
                            Debug.WriteLine("Skipping unknown element {0}", reader.Name);
                            break;
                    }
                }
                if (!reader.Read())
                    break;
            }
            m_enums.Add(name, enumeration);
        }
        void ReadTemplate(XmlReader reader)
        {
            Debug.Assert(reader.NodeType == XmlNodeType.Element && reader.Name == "template",
                 "Must advance to template element (e.g. call ReadToDescendant)");

            string tid = reader.GetAttribute("tid");
            List<Field> template;
            if (m_templateValues.TryGetValue(tid, out template))
            {
                if (template.Count != 0)
                    throw new ApplicationException("Template " + tid + " is defined twice");
            }
            else
                m_templateValues[tid] = template = new List<Field>();

            var inputDepth = reader.Depth;
            reader.Read();      // Advance to children
            while (inputDepth < reader.Depth)
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                        case "data":
                            {
                                string name = reader.GetAttribute("name");
                                string inTypeStr = reader.GetAttribute("inType");
                                var mapId = reader.GetAttribute("map");
                                var countField = reader.GetAttribute("count");
                                countField = countField ?? reader.GetAttribute("length");
                                template.Add(new Field(name, inTypeStr, mapId, countField));
                            } break;
                        default:
                            Debug.WriteLine("Skipping unknown element {0}", reader.Name);
                            break;
                    }
                }
                if (!reader.Read())
                    break;
            }

            //when the manifest does not provide an AddressLen field for Binary addresses we need to fix the field,
            //otherwise instead of
            //        public byte[] Address { get { return GetByteArrayAt(HostOffset(36, 3), AddressLen); } }
            // we get this and the class does not build
            //        public byte[] Address { get { return GetByteArrayAt(HostOffset(8, 2)); } }
            // check for both AddressLen and AddressLength. either are used depending on the manifest.
            // examples that use AddressLen: Microsoft-Windows-QoS-qWAVE and Microsoft-Windows-Winsock-AFD
            // examples that use AddressLength: Microsoft-Windows-DNS-Client and Microsoft-Windows-HttpService
            if (template.Exists(x=>x.Name=="Address" && x.Type.EndsWith("Binary")) &&
                !template.Exists(x=>x.Name== "AddressLen" || x.Name=="AddressLength"))
            {
                var address = template.Find(x => x.Name == "Address");
                var fixedAddress = new Field(address.Name, address.Type, address.m_mapId, "AddressLen");

                //and we need a new field: AddressLen, that is always in the same format
                var addressLen = new Field("AddressLen", "win:UInt32", null);

                //replace the wrong address with the fixed version
                template.Remove(address);
                template.Add(fixedAddress);
                template.Add(addressLen);
            }
        }

        List<Event> m_events = new List<Event>();
        internal string[] m_keywordNames;
        internal Dictionary<int, string> m_taskNames;
        // Note that the key is task << 8 + opcode to allow for private opcode names
        internal Dictionary<int, string> m_opcodeNames;

        // These are not used after parsing.
        internal Dictionary<string, int> m_taskValues;
        // Note that the value is task << 8 + opcode to allow for private opcode names
        internal Dictionary<string, int> m_opcodeValues;
        internal Dictionary<string, ulong> m_keywordValues;
        internal Dictionary<string, List<Field>> m_templateValues;
        internal Dictionary<string, Enumeration> m_enums;
        private static Dictionary<string, string> m_stringMap;
        #endregion
    }

    /// <summary>
    /// An event represents the Event Element in the manifest.   It describes the meta-data of one ETW event
    /// </summary>
    public sealed class Event
    {
        public Provider Provider { get { return m_provider; } }
        public ushort Id { get; private set; }
        public ulong Keywords { get; private set; }
        /// <summary>
        /// A convininece method that returns the keywords as symbol names (comma separated)
        /// </summary>
        public string KeywordsString { get { return Provider.GetKeywordSetString(Keywords); } }
        public byte Version { get; private set; }
        public byte Level { get; private set; }
        public byte Opcode { get; private set; }
        public ushort Task { get; private set; }
        public string Channel { get; private set; }
        /// <summary>
        /// The fields associated with this event.  This can be null if there are no fields.
        /// </summary>
        public IList<Field> Fields { get; private set; }
        public string TaskName { get { return m_provider.GetTaskName(Task); } }
        public string OpcodeName { get { return m_provider.GetOpcodeName(Task, Opcode); } }
        /// <summary>
        /// The event name is synthesis (concatenation) of the Task and Opcode names.   This is never null.
        /// </summary>
        public string EventName
        {
            get
            {
                if (TaskName == null)
                    return Capitalize(OpcodeName);
                if (TaskName.EndsWith(OpcodeName, StringComparison.OrdinalIgnoreCase))
                    return TaskName;
                return TaskName + Capitalize(OpcodeName);
            }
        }
        public string Message { get; internal set; }

        /* These are not guarenteed to be present */
        /// <summary>
        /// Technically the Symbol attribute on an event is not part of the model (it is not stored in the binary manifest)
        /// but if it is present, it can be used to create better names.   This value can be null.
        /// </summary>
        public string Symbol { get; internal set; }
        /// <summary>
        /// Technically the name of the Template for the fields on an event is not part of the model (it is not stored in the binary manifest)
        /// but if it is present, it can be used to create better names.   This value can be null.
        /// </summary>
        public string TemplateName { get; internal set; }
        /// <summary>
        /// Get the line number in the file.  Used for error messages.
        /// </summary>
        public int LineNum { get; private set; }
        #region private
        internal static string Capitalize(string str)
        {
            if (0 < str.Length)
                str = str.Substring(0, 1).ToUpper() + str.Substring(1);
            return str;
        }

        internal static string CamelCase(string str)
        {
            if (str.IndexOf(' ') < 0)
                return str;

            string[] compontents = str.Split(' ');
            for (int i = 1; i < compontents.Length; i++)
                compontents[i] = Capitalize(compontents[i]);
            return string.Join("", compontents);
        }

        private byte ParseLevel(string levelStr)
        {
            switch (levelStr)
            {
                case "win:Always":
                    return 0;
                case "win:Critical":
                    return 1;
                case "win:Error":
                    return 2;
                case "win:Warning":
                    return 3;
                case "win:Informational":
                    return 4;
                case "win:Verbose":
                    return 5;
                default:
                    int ret;
                    if (int.TryParse(levelStr, out ret) && (byte)ret == ret)
                        return (byte)ret;
                    return 4;   // Informational
            }
        }
        internal Event(XmlReader reader, Provider provider, int lineNum)
        {
            m_lineNum = lineNum;
            m_provider = provider;
            Debug.Assert(reader.NodeType == XmlNodeType.Element && reader.Name == "event",
                 "Must advance to event element (e.g. call ReadToDescendant)");

            LineNum = ((IXmlLineInfo)reader).LineNumber;

            for (bool doMore = reader.MoveToFirstAttribute(); doMore; doMore = reader.MoveToNextAttribute())
            {
                switch (reader.Name)
                {
                    case "symbol":
                        Symbol = reader.Value;
                        break;
                    case "version":
                        Version = (byte)ETWManifest.Provider.ParseNumber(reader.Value);
                        break;
                    case "value":
                        Id = (ushort)ETWManifest.Provider.ParseNumber(reader.Value);
                        break;
                    case "task":
                        m_taskId = reader.Value;
                        break;
                    case "opcode":
                        m_opcodeId = reader.Value;
                        break;
                    case "keyword":
                        m_keywordsId = reader.Value;
                        break;
                    case "level":
                        Level = ParseLevel(reader.Value);
                        break;
                    case "template":
                        TemplateName = reader.Value;
                        break;
                    case "message":
                        Message = reader.Value;     // This is actually just a ref to the localization data, but we don't have that yet.
                        break;
                    case "channel":
                        Channel = reader.Value;
                        break;
                    default:
                        Debug.WriteLine("Skipping unknown event attribute " + reader.Name);
                        break;
                }
            }
        }

        /// <summary>
        /// We need a two pass system where after all the defintions are parsed, we go back and link
        /// up uses to their defs.   This routine does this for Events.
        /// </summary>
        internal void ResolveIdsInEvent(string fileName = null)
        {
            string id = "";
            try
            {
                id = m_taskId;
                m_taskId = null;
                if (id != null)
                    Task = (ushort)m_provider.m_taskValues[id];

                id = m_opcodeId;
                m_opcodeId = null;
                if (id != null)
                    Opcode = (byte)m_provider.m_opcodeValues[id];

                id = m_keywordsId;
                m_keywordsId = null;
                if (id != null)
                    Keywords = m_provider.m_keywordValues[id];

                id = TemplateName;
                if (id != null)
                {
                    List<Field> fields;
                    if (!m_provider.m_templateValues.TryGetValue(id, out fields))
                        m_provider.m_templateValues[id] = fields = new List<Field>();
                    Fields = fields;
                    foreach (var field in Fields)
                    {
                        if (field.m_mapId != null)
                            field.Enumeration = m_provider.m_enums[field.m_mapId];
                    }
                }
            }
            catch
            {
                if (fileName == null)
                    fileName = "";
                throw new ApplicationException("Error " + fileName + "(" + m_lineNum + "): Undefined Id " + id);
            }
        }

        internal void UpdateStrings(Dictionary<string, string> stringMap)
        {
            var message = Message;
            if (Provider.Replace(ref message, stringMap))
                Message = message;

            if (Fields != null)
            {
                foreach (var parameter in Fields)
                {
                    if (parameter.Enumeration != null)
                        parameter.Enumeration.UpdateStrings(stringMap);
                }
            }
        }

        Provider m_provider;
        int m_lineNum;          // used for error messages
        string m_opcodeId;      // String name used to look up opcode needed becasue def may be later in file
        string m_keywordsId;    // String name used to look up keywords needed becasue def may be later in file
        string m_taskId;        // String name used to look up tasks needed becasue def may be later in file
        #endregion
    }

    /// <summary>
    /// A field represents one field in a ETW event
    /// </summary>
    public sealed class Field
    {
        /// <summary>
        /// The name of the field.
        /// </summary>
        public string Name { get; private set; }
        /// <summary>
        /// If the type is a structure, then this points at its type.   'Enumeration' and 'Type' will be null in this case.
        /// </summary>
        public Struct Struct { get; private set; }
        /// <summary>
        /// If Type is a integral type, then Enumeration can be set which gives values either
        /// a bitfield or a enumerated type for the values of the parameter.    Otherwise it is null.
        /// </summary>
        public Enumeration Enumeration { get; internal set; }
        /// <summary>
        /// If the type is 'built in' then it has a string name, and this is it.   This is null for structs and an integer type for Enumerations.
        /// </summary>
        public string Type { get; private set; }

        /// <summary>
        /// There is no Array type.  Instead all field can have a 'Count' which might be a number
        /// (for fixed sized arrays) or a name of a Field (for variable sized arrays).    This
        /// can be null, which means the field is not an array.
        /// </summary>
        public string CountField { get; private set; }
        /// <summary>
        /// If set, it indicates that the integer value should be pretty-printed as hexadecimal rather than decimal.
        /// </summary>
        public bool HexFormat { get; private set; }
        #region private
        internal Field(string name, string type, string mapId, string countField = null) { this.Name = name; this.Type = type; m_mapId = mapId; this.CountField = countField; }
        internal string m_mapId;

        #endregion
    }

    /// <summary>
    /// A struct represents a composite type and can be used in field definitions
    /// </summary>
    public sealed class Struct
    {
        /// <summary>
        /// Then name of the type of the structure as a whole.
        /// </summary>
        public string Name { get; private set; }
        public IList<Field> Fields { get; private set; }
    }

    /// <summary>
    /// A Enumeration represents an enumerated type and can be used in field definitions.
    /// </summary>
    public sealed class Enumeration
    {
        public string Name { get; private set; }
        public bool IsBitField { get; private set; }
        public string GetNameForValue(int value)
        {
            return null;
        }
        public IEnumerable<KeyValuePair<int, string>> Values { get { return m_values; } }
        #region private
        internal Enumeration(string name, bool isBitField) { Name = name; IsBitField = isBitField; }
        internal void Add(int value, string name)
        {
            string otherName;
            if (m_values.TryGetValue(value, out otherName))
            {
                Console.WriteLine("Error: in Enumeration {0} the names {1} and {2} have the same value {3}",
                    Name, name, otherName, value);
                return;
            }
            m_values[value] =  name;
        }

        internal void UpdateStrings(Dictionary<string, string> stringMap)
        {
            if (m_stringsLookedUp)
                return;
            m_stringsLookedUp = true;
            List<int> keys = new List<int>(m_values.Keys);
            foreach (var key in keys)
            {
                var value = m_values[key];
                if (Provider.Replace(ref value, stringMap))
                {
                    value = Event.CamelCase(value);
                    value = Regex.Replace(value, @"[^\w\d_]", "");
                    if (value.Length == 0)
                        value = "_";
                    m_values[key] = value;
                }
            }
        }

        SortedDictionary<int, string> m_values = new SortedDictionary<int, string>();
        bool m_stringsLookedUp;
        #endregion
    }
}


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

namespace NXTLib
{
    public partial class Brick
    {

        //The brick is the front-end of the library.  It contains a simplified version of ALL FUNCTIONS in NXTLib.Protocol.
        //TODO: Add more functions to front-end
        //TODO: Add timer

    #region Connection and Timer
        public enum LinkType { Bluetooth }
        public Brick(LinkType type, string port)
        {
            try
            {
                switch (type)
                {
                    case LinkType.Bluetooth:
                        ProtocolLink = new Bluetooth(port);
                        break;
                    default:
                        throw new Exception("[NXTLib] Parameter 'type' formatted incorrectly.");
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
        }
        public Protocol ProtocolLink
        {
            get
            {
                return _link;
            }
            internal set
            {
                _link = value;
            }
        }
        private Protocol _link;
        private string error;
        public string LastError
        {
            get
            {
                return error;
            }
            internal set
            {
                error = value;
            }
        }

        public bool Connect()
        {
            if (!IsConnected)
            {
                if (!ProtocolLink.Connect())
                {
                    error = ProtocolLink.LastError;
                    return false;
                }
                InitSensors();
                EnableAutoPoll();
                return true;
            }
            else
            {
                return true;
            }
        }
        public bool Disconnect()
        {
            if (IsConnected)
            {
                if (!ProtocolLink.Disconnect())
                {
                    error = ProtocolLink.LastError;
                    return false;
                }
                DisableAutoPoll();
                return true;
            }
            else
            {
                return true;
            }
        }
        public bool IsConnected
        {
            get { return ProtocolLink.IsConnected; }
        }

        //private Timer timer = null;
        private void timer_Callback(object state)
        {
            if (IsConnected)
                ProtocolLink.KeepAlive();
        }
    #endregion

    #region Sensors

        private Dictionary<Protocol.SensorPort, Sensor> sensorArr =
            new Dictionary<Protocol.SensorPort, Sensor>();

        /// <summary>
        /// <para>The sensor attached to port 1.</para>
        /// </summary>
        public Sensor Sensor1
        {
            get { return sensorArr[Protocol.SensorPort.Port_1]; }
            set { AttachSensor(value, Protocol.SensorPort.Port_1); }
        }

        /// <summary>
        /// <para>The sensor attached to port 2.</para>
        /// </summary>
        public Sensor Sensor2
        {
            get { return sensorArr[Protocol.SensorPort.Port_2]; }
            set { AttachSensor(value, Protocol.SensorPort.Port_2); }
        }

        /// <summary>
        /// <para>The sensor attached to port 3.</para>
        /// </summary>
        public Sensor Sensor3
        {
            get { return sensorArr[Protocol.SensorPort.Port_3]; }
            set { AttachSensor(value, Protocol.SensorPort.Port_3); }
        }

        /// <summary>
        /// <para>The sensor attached to port 4.</para>
        /// </summary>
        public Sensor Sensor4
        {
            get { return sensorArr[Protocol.SensorPort.Port_4]; }
            set { AttachSensor(value, Protocol.SensorPort.Port_4); }
        }

        /// <summary>
        /// <para>Attaches a sensor to the NXT brick.</para>
        /// </summary>
        /// <param name="sensor">The sensor</param>
        /// <param name="port">The port to attach the sensor to</param>
        private void AttachSensor(Sensor sensor, Protocol.SensorPort port)
        {
            if (sensor != null)
            {
                sensor.brick = this;
                sensor.Port = port;
                sensorArr[port] = sensor;
            }
        }

        /// <summary>
        /// <para>Initializes all the sensors of the brick.</para>
        /// <remarks>Normally this is done as part of the Connect() method, and is not something you need to worry about. However, whenever a program is started on the brick e.g. the MotorControl-program, you will need to call this method to re-initialize the sensors.</remarks>
        /// </summary>
        public void InitSensors()
        {
            foreach (Sensor sensor in sensorArr.Values)
            {
                sensor.InitSensor();
            }
        }

        private void EnableAutoPoll()
        {
            foreach (Motor motor in motorArr.Values)
            {
                motor.EnableAutoPoll();
            }

            foreach (Sensor sensor in sensorArr.Values)
            {
                sensor.EnableAutoPoll();
            }
        }

        private void DisableAutoPoll()
        {
            foreach (Sensor sensor in sensorArr.Values)
            {
                sensor.DisableAutoPoll();
            }

            foreach (Motor motor in motorArr.Values)
            {
                motor.DisableAutoPoll();
            }
        }

    #endregion

    #region Motors
        private Dictionary<Protocol.MotorPortSingle, Motor> motorArr = new Dictionary<Protocol.MotorPortSingle, Motor>();

        /// <summary>
        /// <para>The motor attached to port A.</para>
        /// </summary>
        public Motor MotorA
        {
            get { return motorArr[Protocol.MotorPortSingle.A]; }
            set { AttachMotor(value, Protocol.MotorPortSingle.A); }
        }

        /// <summary>
        /// <para>The motor attached to port B.</para>
        /// </summary>
        public Motor MotorB
        {
            get { return motorArr[Protocol.MotorPortSingle.B]; }
            set { AttachMotor(value, Protocol.MotorPortSingle.B); }
        }

        /// <summary>
        /// <para>The motor attached to port C.</para>
        /// </summary>
        public Motor MotorC
        {
            get { return motorArr[Protocol.MotorPortSingle.C]; }
            set { AttachMotor(value, Protocol.MotorPortSingle.C); }
        }

        /// <summary>
        /// <para>Attaches a motor to the NXT brick.</para>
        /// </summary>
        /// <param name="motor">The motor</param>
        /// <param name="port">The port to attach the motor to</param>
        private void AttachMotor(Motor motor, Protocol.MotorPortSingle port)
        {
            if (motor != null)
            {
                motorArr[port] = motor;
                motor.Brick = this;
                motor.Port = port;
            }
        }
    #endregion

    #region Files

        private string[] FindFiles(string fileMask)
        {
            List<string> fileArr = new List<string>();

            Protocol.FindFileReply? reply = ProtocolLink.FindFirst(fileMask);
            while (reply.HasValue && reply.Value.fileFound)
            {
                fileArr.Add(reply.Value.fileName);
                reply = ProtocolLink.FindNext(reply.Value.handle);
            }

            return fileArr.ToArray();
        }

    #endregion

    #region Programs

        public string Program
        {
            get
            {
                try
                {
                    return ProtocolLink.GetCurrentProgramName();
                }
                catch (Exception ex)
                {
                    error = ex.Message;
                    return null;
                }
            }
            set
            {
                string fileName = value ?? "";

                fileName = fileName.Trim();

                if (fileName != "")
                    ProtocolLink.StartProgram(fileName);
                else
                    ProtocolLink.StopProgram();
            }
        }

        public string[] Programs
        {
            get { return FindFiles("*.rxe"); }
        }

    #endregion

    #region Sounds

        /// <summary>
        /// <para>The sounds currently stored in the NXT brick.</para>
        /// </summary>
        public string[] Sounds
        {
            get { return FindFiles("*.rso"); }
        }

        /// <summary>
        /// <para>Plays a sound file stored in the NXT brick.</para>
        /// </summary>
        /// <param name="soundFile">The sound file</param>
        public void PlaySoundfile(string soundFile)
        {
            ProtocolLink.PlaySoundFile(false, soundFile);
        }

        /// <summary>
        /// <para>Stops all playing sound; sound files and tones.</para>
        /// </summary>
        public void StopSound()
        {
            ProtocolLink.StopSoundPlayback();
        }

        /// <summary>
        /// <para>Plays a tone.</para>
        /// </summary>
        /// <param name="frequency">Frequency for the tone, Hz</param>
        /// <param name="duration">Duration of the tone, ms</param>
        public void PlayTone(UInt16 frequency, UInt16 duration)
        {
            ProtocolLink.PlayTone(frequency, duration);
        }

    #endregion

    #region Miscellaneous

        /// <summary>
        /// <para>The name of the NXT brick.</para>
        /// </summary>
        /// <remarks>
        /// <para>For some reason only the first 8 characters is remembered when the NXT is turned off. This is with version 1.4 of the firmware, and it may be fixed with newer versions.</para>
        /// </remarks>
        public string Name
        {
            get
            {
                Protocol.GetDeviceInfoReply? reply = ProtocolLink.GetDeviceInfo();
                if (reply.HasValue)
                    return reply.Value.Name;
                else
                    return null;
            }
            set { ProtocolLink.SetBrickName(value); }
        }

        /// <summary>
        /// <para>The battery level of the NXT brick in millivolts.</para>
        /// </summary>
        public int BatteryLevel
        {
            get
            {
                int? reply = ProtocolLink.GetBatteryLevel();
                if (reply.HasValue)
                    return reply.Value;
                else
                    return 0;
            }
        }

    #endregion

    }
}

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <Python.h>
#include <string>
#include <tuple>
#include <vector>
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/memory/memcpy.h"
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/float16.h"
#include "pybind11/numpy.h"
#include "pybind11/pybind11.h"

namespace paddle {
namespace pybind {
namespace details {

template <bool less, size_t I, typename... ARGS>
struct CastToPyBufferImpl;

template <size_t I, typename... ARGS>
struct CastToPyBufferImpl<false, I, ARGS...> {
  pybind11::buffer_info operator()(const framework::Tensor &tensor) {
    PADDLE_THROW("This type of tensor cannot be expose to Python");
    return pybind11::buffer_info();
  }
};

template <size_t I, typename... ARGS>
struct CastToPyBufferImpl<true, I, ARGS...> {
  using CUR_TYPE = typename std::tuple_element<I, std::tuple<ARGS...>>::type;
  pybind11::buffer_info operator()(const framework::Tensor &tensor) {
    if (std::type_index(typeid(CUR_TYPE)) == tensor.type()) {
      auto dim_vec = framework::vectorize(tensor.dims());
      std::vector<size_t> dims_outside;
      std::vector<size_t> strides;
      dims_outside.resize(dim_vec.size());
      strides.resize(dim_vec.size());

      size_t prod = 1;
      for (size_t i = dim_vec.size(); i != 0; --i) {
        dims_outside[i - 1] = (size_t)dim_vec[i - 1];
        strides[i - 1] = sizeof(CUR_TYPE) * prod;
        prod *= dims_outside[i - 1];
      }
      framework::Tensor dst_tensor;
      if (paddle::platform::is_gpu_place(tensor.place())) {
#ifdef PADDLE_WITH_CUDA
        auto *src_ptr = static_cast<const void *>(tensor.data<CUR_TYPE>());
        auto *dst_ptr = static_cast<void *>(dst_tensor.mutable_data<CUR_TYPE>(
            tensor.dims(), platform::CPUPlace()));

        paddle::platform::GpuMemcpySync(dst_ptr, src_ptr,
                                        sizeof(CUR_TYPE) * tensor.numel(),
                                        cudaMemcpyDeviceToHost);
#else
        PADDLE_THROW("'CUDAPlace' is not supported in CPU only device.");
#endif
      } else if (paddle::platform::is_cpu_place(tensor.place())) {
        dst_tensor = tensor;
      }

      if (std::type_index(typeid(CUR_TYPE)) ==
          std::type_index(typeid(platform::float16))) {
        return pybind11::buffer_info(
            dst_tensor.data<CUR_TYPE>(), sizeof(CUR_TYPE),
            "e", /* np.dtype('e') == np.float16 */
            (size_t)framework::arity(dst_tensor.dims()), dims_outside, strides);
      } else {
        return pybind11::buffer_info(
            dst_tensor.data<CUR_TYPE>(), sizeof(CUR_TYPE),
            pybind11::format_descriptor<CUR_TYPE>::format(),
            (size_t)framework::arity(dst_tensor.dims()), dims_outside, strides);
      }
    } else {
      constexpr bool less = I + 1 < std::tuple_size<std::tuple<ARGS...>>::value;
      return CastToPyBufferImpl<less, I + 1, ARGS...>()(tensor);
    }
  }
};

}  // namespace details

inline pybind11::buffer_info CastToPyBuffer(const framework::Tensor &tensor) {
  auto buffer_info =
      details::CastToPyBufferImpl<true, 0, float, int, double, int64_t, bool,
                                  uint8_t, platform::float16>()(tensor);
  return buffer_info;
}

template <typename T>
T TensorGetElement(const framework::Tensor &self, size_t offset) {
  if (platform::is_cpu_place(self.place())) {
    return self.data<T>()[offset];
  } else {
    std::shared_ptr<framework::Tensor> dst(new framework::Tensor);
    framework::TensorCopySync(self, platform::CPUPlace(), dst.get());
    return dst->data<T>()[offset];
  }
}

// TODO(dzhwinter) : fix the redundent Tensor allocate and free
template <typename T>
void TensorSetElement(framework::Tensor *self, size_t offset, T elem) {
  if (platform::is_gpu_place(self->place())) {
    std::shared_ptr<framework::Tensor> dst(new framework::Tensor);
    framework::TensorCopySync(*self, platform::CPUPlace(), dst.get());
    dst->data<T>()[offset] = elem;
    framework::TensorCopySync(*dst.get(), self->place(), self);

  } else if (platform::is_cpu_place(self->place())) {
    self->data<T>()[offset] = elem;
  }
}

template <typename T>
void PyCPUTensorSetFromArray(
    framework::Tensor *self,
    pybind11::array_t<T, pybind11::array::c_style | pybind11::array::forcecast>
        array,
    paddle::platform::CPUPlace place) {
  std::vector<int64_t> dims;
  dims.reserve(array.ndim());
  for (size_t i = 0; i < array.ndim(); ++i) {
    dims.push_back(static_cast<int>(array.shape()[i]));
  }

  self->Resize(framework::make_ddim(dims));
  auto *dst = self->mutable_data<T>(place);
  std::memcpy(dst, array.data(), sizeof(T) * array.size());
}

template <>
// This following specialization maps uint16_t in the parameter type to
// platform::float16.
inline void PyCPUTensorSetFromArray(
    framework::Tensor *self,
    pybind11::array_t<uint16_t,
                      pybind11::array::c_style | pybind11::array::forcecast>
        array,
    paddle::platform::CPUPlace place) {
  std::vector<int64_t> dims;
  dims.reserve(array.ndim());
  for (size_t i = 0; i < array.ndim(); ++i) {
    dims.push_back(static_cast<int>(array.shape()[i]));
  }

  self->Resize(framework::make_ddim(dims));
  auto *dst = self->mutable_data<platform::float16>(place);
  std::memcpy(dst, array.data(), sizeof(uint16_t) * array.size());
}

#ifdef PADDLE_WITH_CUDA
template <typename T>
void PyCUDATensorSetFromArray(
    framework::Tensor *self,
    pybind11::array_t<T, pybind11::array::c_style | pybind11::array::forcecast>
        array,
    paddle::platform::CUDAPlace place) {
  std::vector<int64_t> dims;
  dims.reserve(array.ndim());
  for (size_t i = 0; i < array.ndim(); ++i) {
    dims.push_back(static_cast<int>(array.shape()[i]));
  }

  self->Resize(framework::make_ddim(dims));
  auto *dst = self->mutable_data<T>(place);
  paddle::platform::GpuMemcpySync(dst, array.data(), sizeof(T) * array.size(),
                                  cudaMemcpyHostToDevice);
}

template <>
// This following specialization maps uint16_t in the parameter type to
// platform::float16.
inline void PyCUDATensorSetFromArray(
    framework::Tensor *self,
    pybind11::array_t<uint16_t,
                      pybind11::array::c_style | pybind11::array::forcecast>
        array,
    paddle::platform::CUDAPlace place) {
  std::vector<int64_t> dims;
  dims.reserve(array.ndim());
  for (size_t i = 0; i < array.ndim(); ++i) {
    dims.push_back(static_cast<int>(array.shape()[i]));
  }

  self->Resize(framework::make_ddim(dims));
  auto *dst = self->mutable_data<platform::float16>(place);
  paddle::platform::GpuMemcpySync(dst, array.data(),
                                  sizeof(uint16_t) * array.size(),
                                  cudaMemcpyHostToDevice);
}

template <typename T>
void PyCUDAPinnedTensorSetFromArray(
    framework::Tensor *self,
    pybind11::array_t<T, pybind11::array::c_style | pybind11::array::forcecast>
        array,
    const paddle::platform::CUDAPinnedPlace &place) {
  std::vector<int64_t> dims;
  dims.reserve(array.ndim());
  for (size_t i = 0; i < array.ndim(); ++i) {
    dims.push_back(static_cast<int>(array.shape()[i]));
  }

  self->Resize(framework::make_ddim(dims));
  auto *dst = self->mutable_data<T>(place);
  std::memcpy(dst, array.data(), sizeof(T) * array.size());
}

template <>
// This following specialization maps uint16_t in the parameter type to
// platform::float16.
inline void PyCUDAPinnedTensorSetFromArray(
    framework::Tensor *self,
    pybind11::array_t<uint16_t,
                      pybind11::array::c_style | pybind11::array::forcecast>
        array,
    const paddle::platform::CUDAPinnedPlace &place) {
  std::vector<int64_t> dims;
  dims.reserve(array.ndim());
  for (size_t i = 0; i < array.ndim(); ++i) {
    dims.push_back(static_cast<int>(array.shape()[i]));
  }

  self->Resize(framework::make_ddim(dims));
  auto *dst = self->mutable_data<platform::float16>(place);
  std::memcpy(dst, array.data(), sizeof(uint16_t) * array.size());
}
#endif

}  // namespace pybind
}  // namespace paddle


text:
function Controller() {
    function loadBrands() {
        brands = [];
        brands.push({
            name: "Abita Flagship",
            id: 191
        });
        brands.push({
            name: "Amstel Light",
            id: 93
        });
        brands.push({
            name: "Banks Beer",
            id: 308
        });
        brands.push({
            name: "Blue Moon",
            id: 5
        });
    }
    function loadPackages(brandId) {
        packages = [];
        if (191 === brandId) {
            packages.push({
                name: "Abita Amber 1/4 Keg",
                id: 2174
            });
            packages.push({
                name: "Abita Amber 4/6/12 B",
                id: 1282
            });
            packages.push({
                name: "Abita Amber Jockamo Ipa 4/6/12 B",
                id: 1480
            });
            packages.push({
                name: "Abita Purple Haze 1/2 Keg",
                id: 1505
            });
            packages.push({
                name: "Abita Purple Haze 1/4 Keg",
                id: 3501
            });
        }
    }
    function brandShowDialog() {
        var options = [];
        options.push("Select a brand...");
        for (var i = 0; brands.length - 1 > i; i++) options.push(brands[i].name);
        var brandOption = {
            options: options
        };
        var dialog = Ti.UI.createOptionDialog(brandOption);
        dialog.addEventListener("click", function(c) {
            $.brandButton.title = options[c.index];
            selectedBrandId = brands[c.index - 1].id;
            loadPackages(selectedBrandId);
        });
        dialog.show();
    }
    function packageShowDialog() {
        var options = [];
        options.push("Select a package(optional)...");
        for (var i = 0; packages.length - 1 > i; i++) options.push(packages[i].name);
        var brandOption = {
            options: options
        };
        var dialog = Ti.UI.createOptionDialog(brandOption);
        dialog.addEventListener("click", function(c) {
            $.packageButton.title = options[c.index];
            selectedPackageId = packages[c.index - 1].id;
        });
        dialog.show();
    }
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "index";
    arguments[0] ? arguments[0]["__parentSymbol"] : null;
    arguments[0] ? arguments[0]["$model"] : null;
    arguments[0] ? arguments[0]["__itemTemplate"] : null;
    var $ = this;
    var exports = {};
    $.__views.window = Ti.UI.createWindow({
        backgroundColor: "#EFEFEF",
        apiName: "Ti.UI.Window",
        id: "window",
        classes: []
    });
    $.__views.window && $.addTopLevelView($.__views.window);
    $.__views.header = Ti.UI.createLabel({
        text: "Locate Brews!",
        textAlign: Titanium.UI.TEXT_ALIGNMENT_CENTER,
        font: {
            fontWeight: "bold"
        },
        width: "100%",
        height: "40",
        backgroundColor: "black",
        color: "white",
        top: "20",
        apiName: "Ti.UI.Label",
        id: "header",
        classes: []
    });
    $.__views.window.add($.__views.header);
    $.__views.brandView = Ti.UI.createView({
        top: "70",
        width: "95%",
        height: "60",
        apiName: "Ti.UI.View",
        id: "brandView",
        classes: []
    });
    $.__views.window.add($.__views.brandView);
    $.__views.brandButton = Ti.UI.createButton({
        backgroundImage: "images/buttonBackground.png",
        backgroundFocusedImage: "images/buttonBackgroundFocused.png",
        color: "black",
        title: "Select a brand...",
        width: Ti.UI.FILL,
        height: Ti.UI.FILL,
        apiName: "Ti.UI.Button",
        id: "brandButton",
        classes: [ "selectButtons" ]
    });
    $.__views.brandView.add($.__views.brandButton);
    $.__views.arrowBrand = Ti.UI.createImageView({
        image: "images/arrow.png",
        left: "90%",
        apiName: "Ti.UI.ImageView",
        id: "arrowBrand",
        classes: []
    });
    $.__views.brandView.add($.__views.arrowBrand);
    $.__views.packageView = Ti.UI.createView({
        top: "140",
        width: "95%",
        height: "60",
        apiName: "Ti.UI.View",
        id: "packageView",
        classes: []
    });
    $.__views.window.add($.__views.packageView);
    $.__views.packageButton = Ti.UI.createButton({
        backgroundImage: "images/buttonBackground.png",
        backgroundFocusedImage: "images/buttonBackgroundFocused.png",
        color: "black",
        title: "Select a package (optional)...",
        width: Ti.UI.FILL,
        height: Ti.UI.FILL,
        apiName: "Ti.UI.Button",
        id: "packageButton",
        classes: [ "selectButtons" ]
    });
    $.__views.packageView.add($.__views.packageButton);
    $.__views.arrowPackage = Ti.UI.createImageView({
        image: "images/arrow.png",
        left: "90%",
        apiName: "Ti.UI.ImageView",
        id: "arrowPackage",
        classes: []
    });
    $.__views.packageView.add($.__views.arrowPackage);
    $.__views.buttonBar = Ti.UI.createView({
        width: "95%",
        height: "60",
        top: "210",
        apiName: "Ti.UI.View",
        id: "buttonBar",
        classes: []
    });
    $.__views.window.add($.__views.buttonBar);
    $.__views.allButton = Ti.UI.createButton({
        title: "All",
        width: "33%",
        left: "0%",
        apiName: "Ti.UI.Button",
        id: "allButton",
        classes: []
    });
    $.__views.buttonBar.add($.__views.allButton);
    $.__views.restaurantButton = Ti.UI.createButton({
        title: "Restaurants",
        width: "33%",
        left: "33%",
        apiName: "Ti.UI.Button",
        id: "restaurantButton",
        classes: []
    });
    $.__views.buttonBar.add($.__views.restaurantButton);
    $.__views.storeButton = Ti.UI.createButton({
        title: "Stores",
        width: "33%",
        left: "66%",
        apiName: "Ti.UI.Button",
        id: "storeButton",
        classes: []
    });
    $.__views.buttonBar.add($.__views.storeButton);
    $.__views.findBeer = Ti.UI.createButton({
        title: "Find Beer!",
        top: "280",
        height: "60",
        width: "95%",
        color: "black",
        font: {
            fontSize: "20",
            fontWeight: "bold"
        },
        backgroundImage: "images/buttonBackground.png",
        backgroundFocusedImage: "images/buttonBackgroundFocused.png",
        apiName: "Ti.UI.Button",
        id: "findBeer",
        classes: []
    });
    $.__views.window.add($.__views.findBeer);
    exports.destroy = function() {};
    _.extend($, $.__views);
    var selectedBrandId = -1, selectedPackageId = -1, selectedLocation = 0;
    var brands = [];
    var packages = [];
    $.resetClass($.allButton, "selectionButtons buttonSelected");
    $.resetClass($.restaurantButton, "selectionButtons buttonNotSelected");
    $.resetClass($.storeButton, "selectionButtons buttonNotSelected");
    $.window.addEventListener("open", function() {
        loadBrands();
    });
    $.brandButton.addEventListener("click", function() {
        brandShowDialog();
    });
    $.arrowBrand.addEventListener("click", function() {
        brandShowDialog();
    });
    $.packageButton.addEventListener("click", function() {
        packageShowDialog();
    });
    $.arrowPackage.addEventListener("click", function() {
        packageShowDialog();
    });
    $.allButton.addEventListener("click", function() {
        selectedLocation = 0;
        $.resetClass($.allButton, "selectionButtons buttonSelected");
        $.resetClass($.restaurantButton, "selectionButtons buttonNotSelected");
        $.resetClass($.storeButton, "selectionButtons buttonNotSelected");
    });
    $.restaurantButton.addEventListener("click", function() {
        selectedLocation = 1;
        $.resetClass($.allButton, "selectionButtons buttonNotSelected");
        $.resetClass($.restaurantButton, "selectionButtons buttonSelected");
        $.resetClass($.storeButton, "selectionButtons buttonNotSelected");
    });
    $.storeButton.addEventListener("click", function() {
        selectedLocation = 2;
        $.resetClass($.allButton, "selectionButtons buttonNotSelected");
        $.resetClass($.restaurantButton, "selectionButtons buttonNotSelected");
        $.resetClass($.storeButton, "selectionButtons buttonSelected");
    });
    $.findBeer.addEventListener("click", function() {
        var markers = [];
        markers.push({
            name: "Bi-lo #05720",
            street: "1329 W Hwy 160",
            cityState: "Fort Mill, SC  29715",
            phone: "803.547.7147",
            latitude: "35.021332204341903",
            longitude: "-80.959557518362999"
        });
        markers.push({
            name: "Publix #1485",
            street: "2186 Cherry Rd Ste 101",
            cityState: "Rock Hill, SC 29730",
            phone: "803.366.7500",
            latitude: "35.0053956",
            longitude: "-80.8545282"
        });
        var mapController = Alloy.createController("map", markers);
        $.window.open(mapController.getView());
    });
    $.window.open();
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
module Rapidfire
  class QuestionsController < Rapidfire::ApplicationController
    before_filter :authenticate_administrator!
    respond_to :html, :js

    before_filter :find_question_group!
    before_filter :find_question!, :only => [:edit, :update, :destroy]

    def index
      @questions = @question_group.questions
      respond_with(@questions)
    end

    def sort
      item = Question.find(params[:id])
      item.position = params[:thing][:position]
      item.save

      render nothing: true
    end

    def new
      @question = QuestionForm.new(:question_group => @question_group)
      respond_with(@question)
    end

    def create
      form_params = params[:question].merge(:question_group => @question_group)
      @question = QuestionForm.new(form_params)
      @question.save

      respond_with(@question, location: index_location)
    end

    def edit
      @question = QuestionForm.new(:question => @question)
      respond_with(@question)
    end

    def update
      form_params = params[:question].merge(:question => @question)
      @question = QuestionForm.new(form_params)
      @question.save

      respond_with(@question, location: index_location)
    end

    def destroy
      @question.destroy
      respond_with(@question, location: index_location)
    end

    private
    def find_question_group!
      @question_group = QuestionGroup.find(params[:question_group_id])
    end

    def find_question!
      @question = @question_group.questions.find(params[:id])
    end

    def index_location
      rapidfire.question_group_questions_url(@question_group)
    end
  end
end


text:
using UnityEngine;
using System.Collections;

namespace NewtonVR
{
    public class NVRInteractableRotator : NVRInteractable
    {
        public float CurrentAngle;

        protected virtual float DeltaMagic { get { return 1f; } }
        protected Transform InitialAttachPoint;

        protected override void Awake()
        {
            base.Awake();
            this.Rigidbody.maxAngularVelocity = 100f;
        }

        protected virtual void FixedUpdate()
        {
            if (IsAttached == true)
            {
                Vector3 PositionDelta = (AttachedHand.transform.position - InitialAttachPoint.position) * DeltaMagic;

                this.Rigidbody.AddForceAtPosition(PositionDelta, InitialAttachPoint.position, ForceMode.VelocityChange);
            }

            CurrentAngle = Quaternion.Angle(Quaternion.identity, this.transform.rotation);
        }

        public override void BeginInteraction(NVRHand hand)
        {
            base.BeginInteraction(hand);

            InitialAttachPoint = new GameObject(string.Format("[{0}] InitialAttachPoint", this.gameObject.name)).transform;
            InitialAttachPoint.position = hand.transform.position;
            InitialAttachPoint.rotation = hand.transform.rotation;
            InitialAttachPoint.localScale = Vector3.one * 0.25f;
            InitialAttachPoint.parent = this.transform;
        }

        public override void EndInteraction(NVRHand hand)
        {
            base.EndInteraction(hand);

            if (InitialAttachPoint != null)
                Destroy(InitialAttachPoint.gameObject);
        }

    }
}


text:
#include "condor_common.h"
#include "condor_daemon_core.h"
#include "condor_debug.h"
#include "subsystem_info.h"
#include "condor_open.h"
#include "match_prefix.h"
#include "condor_base64.h"
#include "directory.h"
#include "condor_classad.h"
#include "condor_config.h"
#include "condor_arglist.h"
#include "basename.h"
#include "tmp_dir.h"

//-------------------------------------------------------------

	/* Here we have base64 coding routines based on gSOAP, as the one
	 * currently in the c++_util_lib based on OpenSSL are very flakey.
	 * Once they are fixed/improved, these should go away.
	 */

// For base64 coding, we use functions in the gSOAP support library
#include "stdsoap2.h"

// Caller needs to free the returned pointer
char* condor_base64_encode(const unsigned char *input, int length)
{
	char *buff = NULL;

	if ( length < 1 ) {
		buff = (char *)malloc(1);
		buff[0] = '\0';
		return buff;
	}

	int buff_len = (length+2)/3*4+1;
	buff = (char *)malloc(buff_len);
	ASSERT(buff);
	memset(buff,0,buff_len);

	struct soap soap;
	soap_init(&soap);

	soap_s2base64(&soap,input,buff,length);

	soap_destroy(&soap);
	soap_end(&soap);
	soap_done(&soap);

	return buff;
}

// Caller needs to free *output if non-NULL
void condor_base64_decode(const char *input,unsigned char **output, int *output_length)
{
	ASSERT( input );
	ASSERT( output );
	ASSERT( output_length );
	int input_length = strlen(input);

		// safe to assume output length is <= input_length
	*output = (unsigned char *)malloc(input_length + 1);
	ASSERT( *output );
	memset(*output, 0, input_length);

	struct soap soap;
	soap_init(&soap);

	soap_base642s(&soap,input,(char*)(*output),input_length,output_length);

	soap_destroy(&soap);
	soap_end(&soap);
	soap_done(&soap);

	if( *output_length < 0 ) {
		free( *output );
		*output = NULL;
	}
}

//-------------------------------------------------------------

/* Helper function: encode file filename into the resultAd as attribute attrname */
bool
stash_output_file(ClassAd* resultAd, const char* filename, const char* attrname)
{
	ASSERT(filename);
	ASSERT(attrname);
	ASSERT(resultAd);

	FILE *fp = safe_fopen_wrapper(filename,"r");
	if (!fp) return false;

	/* get the file size */
    fseek (fp, 0 , SEEK_END);
    long file_size = ftell (fp);
    rewind (fp);

	char *buffer = NULL;
	if ( file_size > 0 ) {
		/* allocate memory to contain the whole file */
		buffer = (char*) malloc (file_size);
		ASSERT(buffer);

		/* read the file into the buffer. */
		fread(buffer,1,file_size,fp);

		/* Encode - note caller needs to free the returned pointer */
		char* encoded_data = condor_base64_encode((const unsigned char*)buffer, file_size);

		/* Shove into ad */
		if ( encoded_data ) {
			resultAd->Assign(attrname,encoded_data);
			free(encoded_data);
		}
	} else {
		resultAd->Assign(attrname,"");
	}

	if (buffer) free(buffer);
	fclose(fp);

	return true;
}

/* Helper function: write the input files mime encode in the inputAd into iwd */
bool
write_input_files(const ClassAd* inputAd, const char *iwd)
{
	bool return_value = true;
	char *file_name, *file_data;
	unsigned char *output;
	char buf[60];
	int i, output_length, fd;
	int flags = O_WRONLY | O_CREAT | O_TRUNC | O_APPEND | O_LARGEFILE;

	TmpDir tmpdir;
	MyString tmpdir_error;
	if (tmpdir.Cd2TmpDir(iwd,tmpdir_error) == false ) {
		// We failed to cd to our iwd.  This should NEVER happen.
		EXCEPT("write_input_files iwd failure: %s",tmpdir_error.Value());
	}

	i=0; file_name=NULL; file_data=NULL;output=NULL;
	while (return_value==true) {	// keep looping until break or failure
		i++;
		sprintf(buf,"INPUT_FILE_NAME_%d",i);
		inputAd->LookupString(buf,&file_name);
		if (!file_name) break;		// no more files
		sprintf(buf,"INPUT_FILE_DATA_%d",i);
		inputAd->LookupString(buf,&file_data);
		if ( file_data ) {
			// Caller needs to free *output if non-NULL
			condor_base64_decode(file_data,&output,&output_length);
			if ( output ) {
				fd = safe_open_wrapper_follow( condor_basename(file_name), flags, 0666 );
				if ( fd > -1 ) {
					write(fd,output,output_length);
					close(fd);
					dprintf(D_FULLDEBUG,"Wrote %d bytes to file %s%c%s\n",
								output_length, iwd, DIR_DELIM_CHAR,
								condor_basename(file_name));
				} else {
					return_value = false;
				}
				free(output);
				output = NULL;
			} else {
				dprintf(D_ALWAYS,"Failed to decode base64 in attribute %s for file %s\n",
						buf,condor_basename(file_name));
				return_value = false;
			}
			free(file_data);
			file_data = NULL;
		} else {
			// INPUT_FILE_NAME specified, but no data... so just touch the file
			fd = safe_open_wrapper_follow( condor_basename(file_name), flags, 0666 );
			if ( fd > -1 ) {
				close(fd);
				dprintf(D_FULLDEBUG,"Wrote empty file %s%c%s\n",
								iwd, DIR_DELIM_CHAR,
								condor_basename(file_name));
			}
		}
		free(file_name);
		file_name = NULL;
	}

	if ( return_value ) {
		dprintf(D_ALWAYS,"Wrote %d files to subdir %s\n",i-1,iwd);
	} else {
		dprintf(D_ALWAYS,"Failed to write file %d to subdir %s\n",i,iwd);
	}

	return return_value;
}

void
handle_process_request_error( const char* reason, int req_number, ClassAd* resultAd )
{
	const char * why = reason ? reason : "unknown failure";

	dprintf(D_ALWAYS,"ERROR: failed to process request %d - %s\n",
		req_number, why);

	if ( resultAd ) {
		resultAd->Assign("ERROR_STRING",why);
	}

	return;
}

void
do_process_request(const ClassAd *inputAd, ClassAd *resultAd, const int req_number,
				   const char *iwd, const char *stdio_iwd)
{
		// Check for inputAd
	if ( !inputAd ) {
		handle_process_request_error("No input ad",req_number,resultAd);
		return;
	}

		// Map the CMD specified in the input via the config file.
	MyString UnmappedJobName,JobName;
	if (inputAd->LookupString(ATTR_JOB_CMD,UnmappedJobName) == 0 ) {
			// no CMD specified.
		handle_process_request_error("No CMD specified",req_number,resultAd);
		return;
	}
	char *auth_commands = param("SOAPSHELL_AUTHORIZED_COMMANDS");
	StringList auth_list(auth_commands,",");
	if ( auth_commands ) free(auth_commands);
		// Each command needs four tuples; anything else is a misconfiguration
	if ( auth_list.number() % 4 != 0 ) {
		handle_process_request_error("Service is misconfigured: SOAPSHELL_AUTHORIZED_COMMANDS malformed",req_number,resultAd);
		return;
	}

	if ( auth_list.contains_anycase(UnmappedJobName.Value()) == TRUE ) {
		JobName = auth_list.next();
	}
	if ( JobName.IsEmpty() ) {
			// the CMD not authorized
		handle_process_request_error("Requested CMD not authorized via SOAPSHELL_AUTHORIZED_COMMANDS",req_number,resultAd);
		return;
	}

		// handle command line arguments.
	ArgList args;
	args.SetArgV1SyntaxToCurrentPlatform();
	args.AppendArg(JobName.Value());	// set argv[0] to command
	char *soapshell_args = auth_list.next();
	if ( soapshell_args && strcmp(soapshell_args,"*") ) {
		if(!args.AppendArgsV1RawOrV2Quoted(soapshell_args,NULL)) {
			dprintf( D_ALWAYS, "ERROR: SOAPSHELL_ARGS config macro invalid\n" );
		}
	} else if(!args.AppendArgsFromClassAd(inputAd,NULL)) {
		handle_process_request_error("Failed to setup CMD arguments",req_number,resultAd);
		return;
	}

		// handle the environment.
	Env job_env;
	char *env_str = auth_list.next();
	if ( env_str && strcmp(env_str,"*") ) {
		if(!job_env.MergeFromV1RawOrV2Quoted(env_str,NULL) ) {
			dprintf(D_ALWAYS,"ERROR: SOAPSHELL_ENVIRONMENT config macro invalid\n");
		}
	} else if(!job_env.MergeFrom(inputAd,NULL)) {
		// bad environment string in job ad!
		handle_process_request_error("Request has faulty environment string",req_number,resultAd);
		return;
	}

		// Write input files into iwd (we will write stdin later)
	if ( !write_input_files(inputAd, iwd) ) {
		// failed to write input files
		handle_process_request_error("Failed to write input files",req_number,resultAd);
		return;
	}

		// handle stdin, stdout, and stderr redirection
	const char* jobstdin_ = dircat(stdio_iwd,"stdin");
	MyString jobstdin(jobstdin_);
	const char* jobstdout_ = dircat(stdio_iwd,"stdout");
	MyString jobstdout(jobstdout_);
	const char* jobstderr_ = dircat(stdio_iwd,"stderr");
	MyString jobstderr(jobstderr_);
	delete [] jobstdin_;
	delete [] jobstdout_;
	delete [] jobstderr_;
	int flags = O_WRONLY | O_CREAT | O_TRUNC | O_APPEND | O_LARGEFILE;
		// write stdin file is needed
	{
		char *input = NULL;
		unsigned char *output = NULL;
		int output_length = 0;
		int fd = -1;
		inputAd->LookupString(ATTR_JOB_INPUT,&input);
		if ( input ) {
			// Caller needs to free *output if non-NULL
			condor_base64_decode(input,&output,&output_length);
			if ( output ) {
				fd = safe_open_wrapper_follow( jobstdin.Value(), flags, 0666 );
				if ( fd > -1 ) {
					write(fd,output,output_length);
					close(fd);
				}
				free(output);
			}
			free(input);
			if ( fd < 0 ) {
				handle_process_request_error("Failed to write stdin",req_number,resultAd);
				return;
			}
		}
	}
	int fds[3];
		// initialize these to -2 to mean they're not specified.
		// -1 will be treated as an error.
	fds[0] = -2; fds[1] = -2; fds[2] = -2;
	fds[0] = safe_open_wrapper_follow( jobstdin.Value(), O_RDONLY | O_LARGEFILE ); // stdin
	fds[1] = safe_open_wrapper_follow( jobstdout.Value(), flags, 0666 );	// stdout
	fds[2] = safe_open_wrapper_follow( jobstderr.Value(), flags, 0666 );	// stderr
	/* Bail out if we couldn't open stdout/err files correctly */
	if( fds[1]==-1 || fds[2]==-1 ) {
		/* only close ones that had been opened correctly */
		for ( int i = 0; i <= 2; i++ ) {
			if ( fds[i] >= 0 ) {
				daemonCore->Close_FD ( fds[i] );
			}
		}
		handle_process_request_error("Failed to write stdout/err files",req_number,resultAd);
		return;
	}

		// Print what we are about to do to the log
	MyString args_string;
	args.GetArgsStringForDisplay(&args_string,1);
	dprintf( D_ALWAYS, "About to exec %s %s\n", JobName.Value(),
				 args_string.Value() );

		// Spawn a process, baby!!!
	int JobPid = daemonCore->Create_Process( JobName.Value(),	// executable
		                                     args,				// args
		                                     PRIV_UNKNOWN,		// priv_state - TODO
		                                     0,					// reaper id - TODO
		                                     FALSE,				// want_command_port
		                                     &job_env,			// job environment
		                                     iwd,				// job iwd
		                                     NULL,				// family_info - TODO
		                                     NULL,				// sock_inherit_list
		                                     fds				// stdio redirection
										);

		// NOTE: Create_Process() saves the errno for us if it is an
		// "interesting" error.
	char const *create_process_error = NULL;
	if(JobPid == FALSE && errno) create_process_error = strerror(errno);

		// now close the descriptors in fds array.  our child has inherited
		// them already, so we should close them so we do not leak descriptors.
	for ( int i = 0; i <= 2; i++ ) {
		if ( fds[i] >= 0 ) {
			daemonCore->Close_FD ( fds[i] );
		}
	}

	if ( JobPid == FALSE ) {
		JobPid = -1;
		MyString errormsg;
		errormsg.formatstr("Create_Process failed %s",create_process_error ? create_process_error : "");
		handle_process_request_error(errormsg.Value(),req_number,resultAd);
		return;
	}

	dprintf(D_ALWAYS,"Create_Process succeeded, pid=%d\n",JobPid);

		// TODO - For now, just deal w/ one at a time. :(
		// So for now just wait for the child to exit.
#ifdef WIN32
#error This service does not yet work on Windows
#else
	{
		int exit_status;
		pid_t pid;
		for (;;) {
			pid = wait(&exit_status);
			dprintf(D_FULLDEBUG,"WAIT returned %d, errno=%d\n",pid,errno);
			if (pid == JobPid ) break;
			if (pid == -1 && errno != EINTR) {
				EXCEPT("waitpid failed errno=%d",errno);
			}
		}
		if ( WIFEXITED(exit_status) ) {
			int status = WEXITSTATUS(exit_status);
			resultAd->Assign("EXIT_STATUS",status);
		}
	}
#endif

		// Job has completed, exit status is in the ad.  Now put
		// the output files into the result ad.
	stash_output_file(resultAd, jobstdout.Value(), ATTR_JOB_OUTPUT);
	stash_output_file(resultAd, jobstderr.Value(), ATTR_JOB_ERROR);

}

ClassAd *
process_request(const ClassAd *inputAd)
{
	static unsigned int req_number = 0;

		// Number each new request.
	ClassAd *resultAd = new ClassAd();
	ASSERT(resultAd);
	resultAd->Assign("REQUEST_NUMBER",++req_number);

	dprintf(D_ALWAYS,"----------------------------------------\nProcessing request %d\n",req_number);

	dprintf(D_FULLDEBUG,"Contents of request classad:\n");
	if ( inputAd ) {
		((ClassAd*)inputAd)->dPrint(D_FULLDEBUG);
	}

		// Create two temp dirs, one to serve as the iwd for the command, another
		// to hold the stdout/err.
	char *iwd = create_temp_file(true);
	char *stdio_iwd = create_temp_file(true);
	if (!iwd || !stdio_iwd) {
		handle_process_request_error("failed to create temp dirs",req_number,resultAd);
		return resultAd;
	}

		// Do the work.
	do_process_request(inputAd, resultAd, req_number, iwd, stdio_iwd);

		// Blow away our temp dirs unless we are in debug mode
	bool debug_mode = param_boolean("SOAPSHELL_DEBUG_MODE",false);
	if ( !debug_mode ) {
		if ( iwd ) {
			Directory dir(iwd);
			dir.Remove_Full_Path(iwd);
			free(iwd);
		}
		if ( stdio_iwd ) {
			Directory dir(stdio_iwd);
			dir.Remove_Full_Path(stdio_iwd);
			free(stdio_iwd);
		}
	} else {
		if ( iwd ) {
			dprintf(D_ALWAYS,"SOAPSHELL_DEBUG_MODE=True so not removing iwd %s\n",
					iwd);
			free(iwd);
		}
		if ( stdio_iwd ) {
			dprintf(D_ALWAYS,"SOAPSHELL_DEBUG_MODE=True so not removing stdio_iwd %s\n",
					stdio_iwd);
			free(stdio_iwd);
		}
	}

	dprintf(D_FULLDEBUG,"Contents of result classad:\n");
	resultAd->dPrint(D_FULLDEBUG);

	dprintf(D_ALWAYS,"Finished processing request %d\n",req_number);
	return resultAd;
}

//-------------------------------------------------------------

void main_init(int  argc , char *  argv  [])
{
	char *testfile = NULL;
	ClassAd *inputAd = NULL;
	int i;

	dprintf(D_ALWAYS, "main_init() called\n");

	for (i=1; i<argc; i++ ) {

		if (match_prefix(argv[i],"-withfile")) {
			i++;
			if (argc <= i) {
				fprintf(stderr,
						"ERROR: Argument -withfile requires a parameter\n ");
				exit(1);
			}
			testfile = argv[i];
		}

	}	// end of parsing command line options

	if ( testfile ) {
		FILE* fp = safe_fopen_wrapper(testfile,"r");
		if (!fp) {
			fprintf(stderr,"ERROR: Unable to open test file %s\n",
					testfile);
			DC_Exit(1);
		}
		int EndFlag=0, ErrorFlag=0, EmptyFlag=0;
        if( !( inputAd=new ClassAd(fp,"***", EndFlag, ErrorFlag, EmptyFlag) ) ){
            fprintf( stderr, "ERROR:  Out of memory\n" );
            DC_Exit( 1 );
        }
		fclose(fp);
		if ( ErrorFlag || EmptyFlag ) {
			fprintf( stderr, "ERROR - file %s does not contain a parseable ClassAd\n",
					 testfile);
			DC_Exit(1);
		}
		// since this option is for testing, process then exit
		ClassAd * resultAd =  process_request(inputAd);
		resultAd->dPrint(D_ALWAYS);
		DC_Exit( 0 );
	}
}

//-------------------------------------------------------------

void
main_config()
{
	dprintf(D_ALWAYS, "main_config() called\n");
}

//-------------------------------------------------------------

void main_shutdown_fast()
{
	dprintf(D_ALWAYS, "main_shutdown_fast() called\n");
	DC_Exit(0);
}

//-------------------------------------------------------------

void main_shutdown_graceful()
{
	dprintf(D_ALWAYS, "main_shutdown_graceful() called\n");
	DC_Exit(0);
}

//-------------------------------------------------------------

int
main( int argc, char **argv )
{
	set_mySubSystem("SOAPSHELL", SUBSYSTEM_TYPE_DAEMON );	// used by Daemon Core

	dc_main_init = main_init;
	dc_main_config = main_config;
	dc_main_shutdown_fast = main_shutdown_fast;
	dc_main_shutdown_graceful = main_shutdown_graceful;
	return dc_main( argc, argv );
}


text:
<?php

use Mockery as m;

class QueueSyncQueueTest extends PHPUnit_Framework_TestCase
{
    public function tearDown()
    {
        m::close();
    }

    public function testPushShouldFireJobInstantly()
    {
        unset($_SERVER['__sync.test']);

        /*
         * Test Synced Closure
         */
        $sync = new Illuminate\Queue\SyncQueue;
        $container = new Illuminate\Container\Container;
        $encrypter = new Illuminate\Encryption\Encrypter(str_repeat('b', 16));
        $container->instance('Illuminate\Contracts\Encryption\Encrypter', $encrypter);
        $sync->setContainer($container);
        $sync->setEncrypter($encrypter);
        $sync->push(function ($job) {
            $_SERVER['__sync.test'] = true;
            $job->delete();
        });

        $this->assertTrue($_SERVER['__sync.test']);
        unset($_SERVER['__sync.test']);

        /*
         * Test Synced Class Handler
         */
        $sync->push('SyncQueueTestHandler', ['foo' => 'bar']);
        $this->assertInstanceOf('Illuminate\Queue\Jobs\SyncJob', $_SERVER['__sync.test'][0]);
        $this->assertEquals(['foo' => 'bar'], $_SERVER['__sync.test'][1]);
    }

    public function testQueueableEntitiesAreSerializedAndResolved()
    {
        $sync = new Illuminate\Queue\SyncQueue;
        $sync->setContainer($container = new Illuminate\Container\Container);
        $container->instance('Illuminate\Contracts\Queue\EntityResolver', $resolver = m::mock('Illuminate\Contracts\Queue\EntityResolver'));
        $resolver->shouldReceive('resolve')->once()->with('SyncQueueTestEntity', 1)->andReturn(new SyncQueueTestEntity);
        $sync->push('SyncQueueTestHandler', ['entity' => new SyncQueueTestEntity]);

        $this->assertInstanceOf('SyncQueueTestEntity', $_SERVER['__sync.test'][1]['entity']);
    }

    public function testQueueableEntitiesAreSerializedAndResolvedWhenPassedAsSingleEntities()
    {
        $sync = new Illuminate\Queue\SyncQueue;
        $sync->setContainer($container = new Illuminate\Container\Container);
        $container->instance('Illuminate\Contracts\Queue\EntityResolver', $resolver = m::mock('Illuminate\Contracts\Queue\EntityResolver'));
        $resolver->shouldReceive('resolve')->once()->with('SyncQueueTestEntity', 1)->andReturn(new SyncQueueTestEntity);
        $sync->push('SyncQueueTestHandler', new SyncQueueTestEntity);

        $this->assertInstanceOf('SyncQueueTestEntity', $_SERVER['__sync.test'][1]);
    }

    public function testFailedJobGetsHandledWhenAnExceptionIsThrown()
    {
        unset($_SERVER['__sync.failed']);

        $sync = new Illuminate\Queue\SyncQueue;
        $container = new Illuminate\Container\Container;
        $encrypter = new Illuminate\Encryption\Encrypter(str_repeat('c', 16));
        $container->instance('Illuminate\Contracts\Encryption\Encrypter', $encrypter);
        $events = m::mock('Illuminate\Contracts\Events\Dispatcher');
        $events->shouldReceive('fire')->once();
        $container->instance('events', $events);
        $sync->setContainer($container);
        $sync->setEncrypter($encrypter);

        try {
            $sync->push('FailingSyncQueueTestHandler', ['foo' => 'bar']);
        } catch (Exception $e) {
            $this->assertTrue($_SERVER['__sync.failed']);
        }
    }
}

class SyncQueueTestEntity implements Illuminate\Contracts\Queue\QueueableEntity
{
    public function getQueueableId()
    {
        return 1;
    }
}

class SyncQueueTestHandler
{
    public function fire($job, $data)
    {
        $_SERVER['__sync.test'] = func_get_args();
    }
}

class FailingSyncQueueTestHandler
{
    public function fire($job, $data)
    {
        throw new Exception();
    }

    public function failed()
    {
        $_SERVER['__sync.failed'] = true;
    }
}


text:
int main(int argc, char** argv) {
  if (argc != 2) {
    printf("Usage: %s server_ip:server_port,...\n", argv[0]);
    return -1;
  }

  saber::SetLogHandler(nullptr);
  saber::DefaultWatcher watcher;
  saber::ClientOptions options;
  options.root = "/ls";
  options.servers = argv[1];
  options.watcher = &watcher;
  saber::RunLoop loop;
  saber::MySaber mysaber(&loop, options);
  mysaber.Start();
  loop.Loop();
  return 0;
}


text:
% export_csv_dataset_stats
function export_csv_dataset_stats(handles)

    datasetNames=dir(fullfile(handles.datasetdir,'*.mat'));
    if isempty(datasetNames)
        errordlg('Please create a dataset first.','No dataset created');
        return;
    end

    guihandle=handles.output;
    datasetdir=handles.datasetdir;

    csvdir=fullfile(datasetdir,'CSV');
    if ~exist(csvdir)
      mkdir(csvdir)
    end

    % FFT
    if ~exist('Nfft', 'var')
       Nfft=512;
    end

    fs = handles.config{7};

    % figure
    set(guihandle, 'HandleVisibility', 'off');
    % close all;
    set(guihandle, 'HandleVisibility', 'on');
    perc_quant=0.7;
    syllable_activity_threshold=0.005;
    barcolors={[1 102/256 102/256], [1 153/256 153/256], [0.5 0.5 0.5], [102/256 153/256 1] ,[153/256 204/256 1]};
    datasetnames=cell(1,length(datasetNames));

    % limit
    max_syl_dist_tot=200;
    max_syl_dur_tot=110;
    max_syl_count_tot=11;

    % csv header
    csv_header=sprintf('%s,%s (kHz),%s (kHz),%s (kHz),%s (counts),%s (counts),%s (counts),%s (msec),%s (msec),%s (msec),%s (msec),%s (msec),%s (msec),%s (counts),%s (sec),%s (sec)\n', ...
        'data set', ...
        'PSD mean', ...
        'PSD std', ...
        'frequency bandwidth', ...
        'syllables/second mean', ...
        'syllables/second median', ...
        'syllables/second std', ...
        'inter-syllable interval mean', ...
        'inter-syllable interval median', ...
        'inter-syllable interval std', ...
        'syllable duration mean', ...
        'syllable duration median', ...
        'syllable duration std', ...
        'total number of syllables', ...
        'total syllable activity', ...
        'total recording time');

    csvfile=fullfile(csvdir,sprintf('datasets_USV_profile_stats.csv'));
    fid = fopen(csvfile,'wt');
    fwrite(fid, csv_header);

    csv_header_psdn=sprintf('%s (kHz),%s\n', ...
        'frequency', ...
        'PSD (normalized)');

    for datasetID = 1:length(datasetNames)

        dataset_filename = fullfile(datasetdir,datasetNames(datasetID).name);
        [~, datasetnames{datasetID}]=fileparts(dataset_filename);

        if isempty(whos('-file',dataset_filename,'psdn'))
            fprintf('PSD stats of data set does not exist. Recreate the data set.\n');
        else
            load(dataset_filename,'psdn','fs');
        end
        if isempty(whos('-file',dataset_filename,'dataset_stats'))
            fprintf('Data set stats does not exist. Recreate data set.\n');
        else
            load(dataset_filename,'dataset_stats','fs');
        end

        % PSD stats
        psdsum=sum(psdn);
        psdline=psdn./psdsum;
        [sigma,mu]=gaussfit(1:length(psdline), psdline, handles);
        psdcum=cumsum(psdn);
        bw=find(psdn./psdsum>.025*max(psdn./psdsum));
        psd_interval=perc_quant*psdcum(end);
        [~,maxk]=min(abs(psdcum-(psdcum(end)-psd_interval)));
        intervals=zeros(1,maxk);
        for k=1:maxk
        [~,tmp1]=min(abs(psdcum-(psdcum(k)+psd_interval)));
        intervals(k)=tmp1-k;
        end
        muf = mu/Nfft*fs/2;
        sigmaf = sigma/Nfft*fs/2;
        bwq=sigmaf*2;

        % vocalization time
        syl_activity=dataset_stats.syllable_activity;
        syl_activity(syl_activity<syllable_activity_threshold)=[];
        muY=mean(syl_activity);
        stdY=std(syl_activity);

        % syllable stats
        dataset_stats.syllable_count_per_second(dataset_stats.syllable_count_per_second>max_syl_count_tot)=[];
        syl_count_mean=mean(dataset_stats.syllable_count_per_second(dataset_stats.syllable_count_per_second>0));
        syl_count_median=median(dataset_stats.syllable_count_per_second(dataset_stats.syllable_count_per_second>0));
        syl_count_std=std(dataset_stats.syllable_count_per_second(dataset_stats.syllable_count_per_second>0));
        dataset_stats.syllable_distance(dataset_stats.syllable_distance>max_syl_dist_tot)=[];
        syllable_dist_mean=mean(dataset_stats.syllable_distance);
        syllable_dist_median=median(dataset_stats.syllable_distance);
        syllable_dist_std=std(dataset_stats.syllable_distance);
        dataset_stats.syllable_dur(dataset_stats.syllable_dur>max_syl_dur_tot)=[];
        syllable_dur_mean=mean(dataset_stats.syllable_dur);
        syllable_dur_median=median(dataset_stats.syllable_dur);
        syllable_dur_std=std(dataset_stats.syllable_dur);

        fprintf('\nStatistics of dataset "%s"\n',datasetnames{datasetID});
        fprintf('  PSD curve:   %.2f kHz (mean), %.2f kHz (std)\n',(muf/1e3),(sigmaf/1e3));
        fprintf('  frequency bandwidth:   %.2f kHz\n',(bwq/1e3));
        fprintf('  syllables/second:   %.2f (mean),  %.2f (median), %.2f (std)\n',syl_count_mean,syl_count_median,syl_count_std);
        fprintf('  inter-syllable interval:   %.2f ms (mean), %.2f ms (median), %.2f ms (std)\n',syllable_dist_mean,syllable_dist_median,syllable_dist_std);
        fprintf('  syllable duration:   %.2f ms (mean), %.2f ms (median), %.2f ms (std)\n',syllable_dur_mean,syllable_dur_median,syllable_dur_std);
        fprintf('  total number of syllables:   %i\n',dataset_stats.nb_of_syllables);
        fprintf('  total syllable activity:   %.2f\n',dataset_stats.syllable_time);
        fprintf('  total recording time:   %.2f\n',dataset_stats.recording_time);

        dataset_info=sprintf('%s,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%i,%.2f,%.2f\n', ...
        datasetnames{datasetID}, ...
        (muf/1e3), ...
        (sigmaf/1e3), ...
        (bwq/1e3), ...
        syl_count_mean, ...
        syl_count_median, ...
        syl_count_std, ...
        syllable_dist_mean, ...
        syllable_dist_median, ...
        syllable_dist_std, ...
        syllable_dur_mean, ...
        syllable_dur_median, ...
        syllable_dur_std, ...
        dataset_stats.nb_of_syllables, ...
        dataset_stats.syllable_time, ...
        dataset_stats.recording_time);
        fwrite(fid, dataset_info);

        % export PSD values
        csvfile_psdn=fullfile(csvdir,sprintf('psd_stats_dataset_%s.csv', datasetnames{datasetID}));
        fid_psd = fopen(csvfile_psdn,'wt');
        fwrite(fid_psd, csv_header_psdn);
        nfft_max = size(psdn,1);
        khz=1;
        nfft_skip=1000*khz*nfft_max/(fs/2);
        % ensuring NFFT bins larger than requested frequency steps from 0
        % to fs/2
        while nfft_skip < 0
            khz=khz+1;
            nfft_skip=1000*khz*nfft_max/(fs/2);
        end
        for nfft_bin=nfft_skip:nfft_skip:nfft_max
            fwrite(fid_psd,sprintf('%.1f, %.6f\n',fix(nfft_bin/nfft_skip)*khz,psdn(fix(nfft_bin))));
        end
        fclose(fid_psd);

    end

    fclose(fid);
    msgbox(sprintf('***       All data sets stats exported to CSV files       ***\n See folder %s/CSV',handles.datasetdir),'MUPET info');

end


text:
package org.jusecase.builders.streams;

import org.jusecase.builders.Builder;

import java.io.InputStream;

public class InputStreamBuilder implements Builder<InputStream> {

    private Builder<InputStream> concreteBuilder;

    public InputStreamBuilder() {
        concreteBuilder = new StringInputStreamBuilder();
    }

    public InputStreamBuilder withString(String content) {
        concreteBuilder = new StringInputStreamBuilder(content);
        return this;
    }

    public InputStreamBuilder withResource(String resource) {
        concreteBuilder = new ResourceInputStreamBuilder(resource);
        return this;
    }

    @Override
    public InputStream build() {
        return concreteBuilder.build();
    }
}


text:
<Alloy>
	<RefreshControl id="refreshControl">
	</RefreshControl>
</Alloy>


text:
package hashdb;

/**
 * The Class Settings.
 * <p/>
 * Used for basic settings of system. Constants should be kept at minimum.
 *
 * @author filip
 */
public final class Settings {

	/**
	 * The Class CommunicationCodes.
	 */
	public static final class CommunicationCodes {

		/**
		 * The Constant ACK.
		 */
		public static final short ACK = (byte) 0xFFFF;
		public static final short KEEPALIVE = (short) 0xFFFE;
		public static final short CLIENT = (short) -1;
		public static final short CALLBACK = (short) 0xFFFD;
		public static final short NACK = 0x0000;

        public static final class DataTransferCodes {
            public static final short PUT = 0;
            public static final short GET_FIRST = 1;
            public static final short DELETE_FIRST = 2;
            public static final short CHECK_KEY = 3;
        }
    }

    public static final class Fields{
        /**
         * One of the constant field that exists in entries.
         */
        public static final Field KEY = new Field(0, Settings.KEY_SIZE);
        /**
         * One of the constant field that exists in entries.
         */
        public static final Field STATUS = new Field(KEY.getEnd(), Settings.STATUS_SIZE);
        /**
         * One of the constant field that exists in entries.
         */
        public static final Field LENGTH = new Field(STATUS.getEnd(),
                                                     (int) Math.ceil(Math.log(Settings.DATA_SIZE) / (Math.log(2) * 8)));
        /**
         * One of the constant field that exists in entries.
         */
        public static final Field DATA = new Field(LENGTH.getEnd(), Settings.DATA_SIZE);
        /**
         * One of the constant field that exists in entries.
         */
        public static final Field LINK = new Field(DATA.getEnd(), Settings.KEY_SIZE);
        /**
         * One special field used to determine size of entry.
         */
        public static final Field END = new Field(LINK.getEnd(), 0);
    }

	/**
	 * The Class Field.
	 */
	public static final class Field {

		/**
		 * The offset in bytes from beginning of entry.
		 */
		private final int offset;

		/**
		 * The size in bytes of field in bytes.
		 */
		private final int size;

		/**
		 * Instantiates a new field.
		 *
		 * @param offset the offset
		 * @param size   the size
		 */
		public Field(final int offset, final int size) {
			this.offset = offset;
			this.size = size;
		}

		/**
		 * Gets the end.
		 *
		 * @return the end
		 */
		public final int getEnd() {
			return this.size + this.offset;
		}

		/**
		 * Gets the offset.
		 *
		 * @return the offset
		 */
		public final int getOffset() {
			return this.offset;
		}

		/**
		 * Gets the size.
		 *
		 * @return the size
		 */
		public final int getSize() {
			return this.size;
		}
	}

	/**
	 * The Class Server.
	 */
	public static final class Server {

		/**
		 * The Class Master.
		 */
		public static final class Master {
			/**
			 * The Constant PORT.
			 */
			public static final int PORT = 9999;

			/**
			 * The Constant WORKERS.
			 */
			public static final int WORKERS = 1;

			/**
			 * The Constant IP.
			 */
			public static final String IP = "localhost";
		}

		/**
		 * The Class Master.
		 */
		public static final class Slave {
			/**
			 * The Constant PORT.
			 */
			public static final int PORT = 10000;

			/**
			 * The Constant WORKERS.
			 */
			public static final int WORKERS = 1;

			/**
			 * The Constant SETTINGS_LACKING.
			 */
			public static final boolean SETTINGS_LACKING = false;
			public static final int ENTRIES_PER_SERVER = 19;
		}

		/**
		 * The Constant IP_SIZE.
		 */
		public static final short IP_SIZE = 4; // in bytes; IPv4

		/**
		 * The Constant INACTIVE_THRESHOLD.
		 */
		public static final long INACTIVE_THRESHOLD = 10*60*60* 1000;

		/**
		 * The Constant RECEPTIONIST_RETRY.
		 */
		public static final boolean RECEPTIONIST_RETRY = true;

		/**
		 * The worker names.
		 */
		public static final String[] workerNames = {"Andrija", "Branislav", "Cvetko", "Časlav", "Ćirilo", "Dejan", "Džordž", "Đorđe", "Emir", "Filip", "Goran", "Hristivoje", "Ilija", "Jovan", "Kosta", "Lazar", "Ljubivoje", "Milan", "Novak", "Njegomir", "Ostoja", "Petar", "Radovan", "Stevan", "Špira", "Trifun", "Uros", "Veroljub", "Zoran", "Živorad"};

	}

	/**
	 * The Constant EMPTY.
	 */
	public static final byte[] EMPTY = {0x01};

	/**
	 * Size of data part in bytes.
	 */
	private static final int DATA_SIZE = 10*1024*1024; //10 MB

	/**
	 * Number of status bytes.
	 */
	private static final int STATUS_SIZE = 1;

	/**
	 * The key size.
	 */
	private static final int KEY_SIZE = 4;

    /**
	 * The Constant JUMPED.
	 */
	public static final byte[] JUMPED = {0x02};
}