text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using Orleans.CodeGeneration;
using Orleans.GrainDirectory;
using Orleans.Runtime;

namespace Orleans.Serialization
{
    internal static class BinaryTokenStreamReaderExtensinons
    {
        internal static IdSpan ReadIdSpan<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
        {
            var hashCode = @this.ReadInt();
            var len = @this.ReadUShort();
            if (len == 0)
            {
                return default;
            }

            var bytes = @this.ReadBytes(len);
            return IdSpan.UnsafeCreate(bytes, hashCode);
        }

        /// <summary> Read an <c>GrainId</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        internal static GrainId ReadGrainId<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
        {
            var type = @this.ReadIdSpan();
            var key = @this.ReadIdSpan();
            return new GrainId(new GrainType(type), key);
        }

        internal static GrainInterfaceType ReadGrainInterfaceType<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
        {
            var id = @this.ReadIdSpan();
            return new GrainInterfaceType(id);
        }

        /// <summary> Read an <c>ActivationId</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        internal static ActivationId ReadActivationId<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
        {
            UniqueKey key = @this.ReadUniqueKey();
            return ActivationId.GetActivationId(key);
        }

        internal static UniqueKey ReadUniqueKey<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
        {
            ulong n0 = @this.ReadULong();
            ulong n1 = @this.ReadULong();
            ulong typeCodeData = @this.ReadULong();
            string keyExt = @this.ReadString();
            return UniqueKey.NewKey(n0, n1, typeCodeData, keyExt);
        }

        internal static CorrelationId ReadCorrelationId<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
        {
            return new CorrelationId(@this.ReadLong());
        }

        internal static GrainDirectoryEntryStatus ReadMultiClusterStatus<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
        {
            byte val = @this.ReadByte();
            return (GrainDirectoryEntryStatus)val;
        }

        /// <summary> Read an <c>ActivationAddress</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        internal static ActivationAddress ReadActivationAddress<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
        {
            var silo = @this.ReadSiloAddress();
            var grain = @this.ReadGrainId();
            var act = @this.ReadActivationId();

            if (silo.Equals(SiloAddress.Zero))
                silo = null;

            if (act.Equals(ActivationId.Zero))
                act = default;

            return ActivationAddress.GetAddress(silo, grain, act);
        }

        /// <summary>
        /// Peek at the next token in this input stream.
        /// </summary>
        /// <returns>Next token that will be read from the stream.</returns>
        internal static SerializationTokenType PeekToken<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
        {
            return (SerializationTokenType)@this.PeekByte();
        }

        /// <summary> Read a <c>SerializationTokenType</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        internal static SerializationTokenType ReadToken<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
        {
            return (SerializationTokenType)@this.ReadByte();
        }

        internal static bool TryReadSimpleType<TReader>(this TReader @this, out object result, out SerializationTokenType token) where TReader : IBinaryTokenStreamReader
        {
            token = @this.ReadToken();
            switch (token)
            {
                case SerializationTokenType.True:
                    result = true;
                    break;
                case SerializationTokenType.False:
                    result = false;
                    break;
                case SerializationTokenType.Null:
                    result = null;
                    break;
                case SerializationTokenType.Object:
                    result = new object();
                    break;
                case SerializationTokenType.Int:
                    result = @this.ReadInt();
                    break;
                case SerializationTokenType.Uint:
                    result = @this.ReadUInt();
                    break;
                case SerializationTokenType.Short:
                    result = @this.ReadShort();
                    break;
                case SerializationTokenType.Ushort:
                    result = @this.ReadUShort();
                    break;
                case SerializationTokenType.Long:
                    result = @this.ReadLong();
                    break;
                case SerializationTokenType.Ulong:
                    result = @this.ReadULong();
                    break;
                case SerializationTokenType.Byte:
                    result = @this.ReadByte();
                    break;
                case SerializationTokenType.Sbyte:
                    result = @this.ReadSByte();
                    break;
                case SerializationTokenType.Float:
                    result = @this.ReadFloat();
                    break;
                case SerializationTokenType.Double:
                    result = @this.ReadDouble();
                    break;
                case SerializationTokenType.Decimal:
                    result = @this.ReadDecimal();
                    break;
                case SerializationTokenType.String:
                    result = @this.ReadString();
                    break;
                case SerializationTokenType.Character:
                    result = @this.ReadChar();
                    break;
                case SerializationTokenType.Guid:
                    if (@this is BinaryTokenStreamReader2 reader)
                    {
                        result = reader.ReadGuid();
                    }
                    else
                    {
                        var bytes = @this.ReadBytes(16);
                        result = new Guid(bytes);
                    }

                    break;
                case SerializationTokenType.Date:
                    result = DateTime.FromBinary(@this.ReadLong());
                    break;
                case SerializationTokenType.TimeSpan:
                    result = new TimeSpan(@this.ReadLong());
                    break;
                case SerializationTokenType.GrainId:
                    result = @this.ReadGrainId();
                    break;
                case SerializationTokenType.ActivationId:
                    result = @this.ReadActivationId();
                    break;
                case SerializationTokenType.SiloAddress:
                    result = @this.ReadSiloAddress();
                    break;
                case SerializationTokenType.ActivationAddress:
                    result = @this.ReadActivationAddress();
                    break;
                case SerializationTokenType.IpAddress:
                    result = @this.ReadIPAddress();
                    break;
                case SerializationTokenType.IpEndPoint:
                    result = @this.ReadIPEndPoint();
                    break;
                case SerializationTokenType.CorrelationId:
                    result = new CorrelationId(@this.ReadLong());
                    break;
                default:
                    result = null;
                    return false;
            }
            return true;
        }

        internal static Type CheckSpecialTypeCode(SerializationTokenType token)
        {
            switch (token)
            {
                case SerializationTokenType.Boolean:
                    return typeof(bool);
                case SerializationTokenType.Int:
                    return typeof(int);
                case SerializationTokenType.Short:
                    return typeof(short);
                case SerializationTokenType.Long:
                    return typeof(long);
                case SerializationTokenType.Sbyte:
                    return typeof(sbyte);
                case SerializationTokenType.Uint:
                    return typeof(uint);
                case SerializationTokenType.Ushort:
                    return typeof(ushort);
                case SerializationTokenType.Ulong:
                    return typeof(ulong);
                case SerializationTokenType.Byte:
                    return typeof(byte);
                case SerializationTokenType.Float:
                    return typeof(float);
                case SerializationTokenType.Double:
                    return typeof(double);
                case SerializationTokenType.Decimal:
                    return typeof(decimal);
                case SerializationTokenType.String:
                    return typeof(string);
                case SerializationTokenType.Character:
                    return typeof(char);
                case SerializationTokenType.Guid:
                    return typeof(Guid);
                case SerializationTokenType.Date:
                    return typeof(DateTime);
                case SerializationTokenType.TimeSpan:
                    return typeof(TimeSpan);
                case SerializationTokenType.IpAddress:
                    return typeof(IPAddress);
                case SerializationTokenType.IpEndPoint:
                    return typeof(IPEndPoint);
                case SerializationTokenType.GrainId:
                    return typeof(GrainId);
                case SerializationTokenType.ActivationId:
                    return typeof(ActivationId);
                case SerializationTokenType.SiloAddress:
                    return typeof(SiloAddress);
                case SerializationTokenType.ActivationAddress:
                    return typeof(ActivationAddress);
                case SerializationTokenType.CorrelationId:
                    return typeof(CorrelationId);
#if false // Note: not yet implemented as simple types on the Writer side
                case SerializationTokenType.Object:
                    return typeof(Object);
                case SerializationTokenType.ByteArray:
                    return typeof(byte[]);
                case SerializationTokenType.ShortArray:
                    return typeof(short[]);
                case SerializationTokenType.IntArray:
                    return typeof(int[]);
                case SerializationTokenType.LongArray:
                    return typeof(long[]);
                case SerializationTokenType.UShortArray:
                    return typeof(ushort[]);
                case SerializationTokenType.UIntArray:
                    return typeof(uint[]);
                case SerializationTokenType.ULongArray:
                    return typeof(ulong[]);
                case SerializationTokenType.FloatArray:
                    return typeof(float[]);
                case SerializationTokenType.DoubleArray:
                    return typeof(double[]);
                case SerializationTokenType.CharArray:
                    return typeof(char[]);
                case SerializationTokenType.BoolArray:
                    return typeof(bool[]);
#endif
                default:
                    break;
            }

            return null;
        }

        /// <summary> Read a <c>Type</c> value from the stream. </summary>
        internal static Type ReadSpecifiedTypeHeader<TReader>(this TReader @this, SerializationManager serializationManager) where TReader : IBinaryTokenStreamReader
        {
            // Assumes that the SpecifiedType token has already been read

            var token = @this.ReadToken();
            switch (token)
            {
                case SerializationTokenType.Boolean:
                    return typeof(bool);
                case SerializationTokenType.Int:
                    return typeof(int);
                case SerializationTokenType.Short:
                    return typeof(short);
                case SerializationTokenType.Long:
                    return typeof(long);
                case SerializationTokenType.Sbyte:
                    return typeof(sbyte);
                case SerializationTokenType.Uint:
                    return typeof(uint);
                case SerializationTokenType.Ushort:
                    return typeof(ushort);
                case SerializationTokenType.Ulong:
                    return typeof(ulong);
                case SerializationTokenType.Byte:
                    return typeof(byte);
                case SerializationTokenType.Float:
                    return typeof(float);
                case SerializationTokenType.Double:
                    return typeof(double);
                case SerializationTokenType.Decimal:
                    return typeof(decimal);
                case SerializationTokenType.String:
                    return typeof(string);
                case SerializationTokenType.Character:
                    return typeof(char);
                case SerializationTokenType.Guid:
                    return typeof(Guid);
                case SerializationTokenType.Date:
                    return typeof(DateTime);
                case SerializationTokenType.TimeSpan:
                    return typeof(TimeSpan);
                case SerializationTokenType.IpAddress:
                    return typeof(IPAddress);
                case SerializationTokenType.IpEndPoint:
                    return typeof(IPEndPoint);
                case SerializationTokenType.GrainId:
                    return typeof(GrainId);
                case SerializationTokenType.ActivationId:
                    return typeof(ActivationId);
                case SerializationTokenType.SiloAddress:
                    return typeof(SiloAddress);
                case SerializationTokenType.ActivationAddress:
                    return typeof(ActivationAddress);
                case SerializationTokenType.CorrelationId:
                    return typeof(CorrelationId);
                case SerializationTokenType.Request:
                    return typeof(InvokeMethodRequest);
                case SerializationTokenType.Response:
                    return typeof(Response);
                case SerializationTokenType.StringObjDict:
                    return typeof(Dictionary<string, object>);
                case SerializationTokenType.Object:
                    return typeof(Object);
                case SerializationTokenType.Tuple + 1:
                    return typeof(Tuple<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
                case SerializationTokenType.Tuple + 2:
                    return typeof(Tuple<,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 2));
                case SerializationTokenType.Tuple + 3:
                    return typeof(Tuple<,,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 3));
                case SerializationTokenType.Tuple + 4:
                    return typeof(Tuple<,,,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 4));
                case SerializationTokenType.Tuple + 5:
                    return typeof(Tuple<,,,,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 5));
                case SerializationTokenType.Tuple + 6:
                    return typeof(Tuple<,,,,,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 6));
                case SerializationTokenType.Tuple + 7:
                    return typeof(Tuple<,,,,,,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 7));
                case SerializationTokenType.Array + 1:
                    var et1 = @this.ReadFullTypeHeader(serializationManager);
                    return et1.MakeArrayType();
                case SerializationTokenType.Array + 2:
                    var et2 = @this.ReadFullTypeHeader(serializationManager);
                    return et2.MakeArrayType(2);
                case SerializationTokenType.Array + 3:
                    var et3 = @this.ReadFullTypeHeader(serializationManager);
                    return et3.MakeArrayType(3);
                case SerializationTokenType.Array + 4:
                    var et4 = @this.ReadFullTypeHeader(serializationManager);
                    return et4.MakeArrayType(4);
                case SerializationTokenType.Array + 5:
                    var et5 = @this.ReadFullTypeHeader(serializationManager);
                    return et5.MakeArrayType(5);
                case SerializationTokenType.Array + 6:
                    var et6 = @this.ReadFullTypeHeader(serializationManager);
                    return et6.MakeArrayType(6);
                case SerializationTokenType.Array + 7:
                    var et7 = @this.ReadFullTypeHeader(serializationManager);
                    return et7.MakeArrayType(7);
                case SerializationTokenType.Array + 8:
                    var et8 = @this.ReadFullTypeHeader(serializationManager);
                    return et8.MakeArrayType(8);
                case SerializationTokenType.List:
                    return typeof(List<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
                case SerializationTokenType.Dictionary:
                    return typeof(Dictionary<,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 2));
                case SerializationTokenType.KeyValuePair:
                    return typeof(KeyValuePair<,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 2));
                case SerializationTokenType.Set:
                    return typeof(HashSet<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
                case SerializationTokenType.SortedList:
                    return typeof(SortedList<,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 2));
                case SerializationTokenType.SortedSet:
                    return typeof(SortedSet<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
                case SerializationTokenType.Stack:
                    return typeof(Stack<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
                case SerializationTokenType.Queue:
                    return typeof(Queue<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
                case SerializationTokenType.LinkedList:
                    return typeof(LinkedList<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
                case SerializationTokenType.Nullable:
                    return typeof(Nullable<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
                case SerializationTokenType.ByteArray:
                    return typeof(byte[]);
                case SerializationTokenType.ShortArray:
                    return typeof(short[]);
                case SerializationTokenType.IntArray:
                    return typeof(int[]);
                case SerializationTokenType.LongArray:
                    return typeof(long[]);
                case SerializationTokenType.UShortArray:
                    return typeof(ushort[]);
                case SerializationTokenType.UIntArray:
                    return typeof(uint[]);
                case SerializationTokenType.ULongArray:
                    return typeof(ulong[]);
                case SerializationTokenType.FloatArray:
                    return typeof(float[]);
                case SerializationTokenType.DoubleArray:
                    return typeof(double[]);
                case SerializationTokenType.CharArray:
                    return typeof(char[]);
                case SerializationTokenType.BoolArray:
                    return typeof(bool[]);
                case SerializationTokenType.SByteArray:
                    return typeof(sbyte[]);
                case SerializationTokenType.NamedType:
                    var typeName = @this.ReadString();
                    try
                    {
                        var type = serializationManager.ResolveTypeName(typeName);
                        return type;
                    }
                    catch (TypeAccessException ex)
                    {
                        throw new TypeAccessException("Named type \"" + typeName + "\" is invalid: " + ex.Message);
                    }
                default:
                    break;
            }

            throw new SerializationException("Unexpected '" + token + "' found when expecting a type reference");
        }
        /// <summary> Read a <c>Type</c> value from the stream. </summary>
        /// <param name="this">The IBinaryTokenStreamReader to read from</param>
        /// <param name="serializationManager">The serialization manager used to resolve type names.</param>
        /// <param name="expected">Expected Type, if known.</param>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        private static Type ReadFullTypeHeader<TReader>(this TReader @this, SerializationManager serializationManager, Type expected = null) where TReader: IBinaryTokenStreamReader
        {
            var token = @this.ReadToken();

            if (token == SerializationTokenType.ExpectedType)
            {
                return expected;
            }

            var t = CheckSpecialTypeCode(token);
            if (t != null)
            {
                return t;
            }

            if (token == SerializationTokenType.SpecifiedType)
            {
#if TRACE_SERIALIZATION
                var tt = ReadSpecifiedTypeHeader();
                Trace("--Read specified type header for type {0}", tt);
                return tt;
#else
                return @this.ReadSpecifiedTypeHeader(serializationManager);
#endif
            }

            throw new SerializationException("Invalid '" + token + "'token in input stream where full type header is expected");
        }

        private static Type[] ReadGenericArguments(this IBinaryTokenStreamReader @this, SerializationManager serializationManager, int n)
        {
            var args = new Type[n];
            for (var i = 0; i < n; i++)
            {
                args[i] = @this.ReadFullTypeHeader(serializationManager);
            }
            return args;
        }
    }

    /// <summary>
    /// Reader for Orleans binary token streams
    /// </summary>
    public class BinaryTokenStreamReader : IBinaryTokenStreamReader
    {
        private IList<ArraySegment<byte>> buffers;
        private int buffersCount;
        private int currentSegmentIndex;
        private ArraySegment<byte> currentSegment;
        private byte[] currentBuffer;
        private int currentOffset;
        private int currentSegmentOffset;
        private int currentSegmentCount;
        private int totalProcessedBytes;
        private int currentSegmentOffsetPlusCount;
        private int totalLength;

        private static readonly ArraySegment<byte> emptySegment = new ArraySegment<byte>(new byte[0]);
        private static readonly byte[] emptyByteArray = new byte[0];

        /// <summary>
        /// Create a new BinaryTokenStreamReader to read from the specified input byte array.
        /// </summary>
        /// <param name="input">Input binary data to be tokenized.</param>
        public BinaryTokenStreamReader(byte[] input)
            : this(new List<ArraySegment<byte>> { new ArraySegment<byte>(input) })
        {
        }

        /// <summary>
        /// Create a new BinaryTokenStreamReader to read from the specified input buffers.
        /// </summary>
        /// <param name="buffs">The list of ArraySegments to use for the data.</param>
        public BinaryTokenStreamReader(IList<ArraySegment<byte>> buffs)
        {
            this.Reset(buffs);
            Trace("Starting new stream reader");
        }

        /// <summary>
        /// Resets this instance with the provided data.
        /// </summary>
        /// <param name="buffs">The underlying buffers.</param>
        public void Reset(IList<ArraySegment<byte>> buffs)
        {
            buffers = buffs;
            totalProcessedBytes = 0;
            currentSegmentIndex = 0;
            InitializeCurrentSegment(0);
            totalLength = buffs.Sum(b => b.Count);
            buffersCount = buffs.Count;
        }

        private void InitializeCurrentSegment(int segmentIndex)
        {
            currentSegment = buffers[segmentIndex];
            currentBuffer = currentSegment.Array;
            currentOffset = currentSegment.Offset;
            currentSegmentOffset = currentOffset;
            currentSegmentCount = currentSegment.Count;
            currentSegmentOffsetPlusCount = currentSegmentOffset + currentSegmentCount;
        }

        /// <summary>
        /// Create a new BinaryTokenStreamReader to read from the specified input buffer.
        /// </summary>
        /// <param name="buff">ArraySegment to use for the data.</param>
        public BinaryTokenStreamReader(ArraySegment<byte> buff)
            : this(new[] { buff })
        {
        }

        /// <summary> Current read position in the stream. </summary>
        public int CurrentPosition => currentOffset + totalProcessedBytes - currentSegmentOffset;

        /// <summary>
        /// Gets the total length.
        /// </summary>
        public long Length => this.totalLength;

        /// <summary>
        /// Creates a copy of the current stream reader.
        /// </summary>
        /// <returns>The new copy</returns>
        public IBinaryTokenStreamReader Copy()
        {
            return new BinaryTokenStreamReader(this.buffers);
        }

        private void StartNextSegment()
        {
            totalProcessedBytes += currentSegment.Count;
            currentSegmentIndex++;
            if (currentSegmentIndex < buffersCount)
            {
                InitializeCurrentSegment(currentSegmentIndex);
            }
            else
            {
                currentSegment = emptySegment;
                currentBuffer = null;
                currentOffset = 0;
                currentSegmentOffset = 0;
                currentSegmentOffsetPlusCount = currentSegmentOffset + currentSegmentCount;
            }
        }

        private byte[] CheckLength(int n, out int offset)
        {
            bool ignore;
            byte[] res;
            if (TryCheckLengthFast(n, out res, out offset, out ignore))
            {
                return res;
            }

            return CheckLength(n, out offset, out ignore);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private bool TryCheckLengthFast(int n, out byte[] res, out int offset, out bool safeToUse)
        {
            safeToUse = false;
            res = null;
            offset = 0;
            var nextOffset = currentOffset + n;
            if (nextOffset <= currentSegmentOffsetPlusCount)
            {
                offset = currentOffset;
                currentOffset = nextOffset;
                res = currentBuffer;
                return true;
            }

            return false;
        }

        private byte[] CheckLength(int n, out int offset, out bool safeToUse)
        {
            safeToUse = false;
            offset = 0;
            if (currentOffset == currentSegmentOffsetPlusCount)
            {
                StartNextSegment();
            }

            byte[] res;
            if (TryCheckLengthFast(n, out res, out offset, out safeToUse))
            {
                return res;
            }

            if ((CurrentPosition + n > totalLength))
            {
                throw new SerializationException(
                    String.Format("Attempt to read past the end of the input stream: CurrentPosition={0}, n={1}, totalLength={2}",
                    CurrentPosition, n, totalLength));
            }

            var temp = new byte[n];
            var i = 0;

            while (i < n)
            {
                var segmentOffsetPlusCount = currentSegmentOffsetPlusCount;
                var bytesFromThisBuffer = Math.Min(segmentOffsetPlusCount - currentOffset, n - i);
                Buffer.BlockCopy(currentBuffer, currentOffset, temp, i, bytesFromThisBuffer);
                i += bytesFromThisBuffer;
                currentOffset += bytesFromThisBuffer;
                if (currentOffset >= segmentOffsetPlusCount)
                {
                    if (currentSegmentIndex >= buffersCount)
                    {
                        throw new SerializationException(
                            String.Format("Attempt to read past buffers.Count: currentSegmentIndex={0}, buffers.Count={1}.", currentSegmentIndex, buffers.Count));
                    }

                    StartNextSegment();
                }
            }
            safeToUse = true;
            offset = 0;
            return temp;
        }

        /// <summary> Read a <c>bool</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public bool ReadBoolean()
        {
            return this.ReadToken() == SerializationTokenType.True;
        }

        /// <summary> Read an <c>Int32</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public int ReadInt()
        {
            int offset;
            var buff = CheckLength(sizeof(int), out offset);
            var val = BitConverter.ToInt32(buff, offset);
            Trace("--Read int {0}", val);
            return val;
        }

        /// <summary> Read an <c>UInt32</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public uint ReadUInt()
        {
            int offset;
            var buff = CheckLength(sizeof(uint), out offset);
            var val = BitConverter.ToUInt32(buff, offset);
            Trace("--Read uint {0}", val);
            return val;
        }

        /// <summary> Read an <c>Int16</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public short ReadShort()
        {
            int offset;
            var buff = CheckLength(sizeof(short), out offset);
            var val = BitConverter.ToInt16(buff, offset);
            Trace("--Read short {0}", val);
            return val;
        }

        /// <summary> Read an <c>UInt16</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public ushort ReadUShort()
        {
            int offset;
            var buff = CheckLength(sizeof(ushort), out offset);
            var val = BitConverter.ToUInt16(buff, offset);
            Trace("--Read ushort {0}", val);
            return val;
        }

        /// <summary> Read an <c>Int64</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public long ReadLong()
        {
            int offset;
            var buff = CheckLength(sizeof(long), out offset);
            var val = BitConverter.ToInt64(buff, offset);
            Trace("--Read long {0}", val);
            return val;
        }

        /// <summary> Read an <c>UInt64</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public ulong ReadULong()
        {
            int offset;
            var buff = CheckLength(sizeof(ulong), out offset);
            var val = BitConverter.ToUInt64(buff, offset);
            Trace("--Read ulong {0}", val);
            return val;
        }

        /// <summary> Read an <c>float</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public float ReadFloat()
        {
            int offset;
            var buff = CheckLength(sizeof(float), out offset);
            var val = BitConverter.ToSingle(buff, offset);
            Trace("--Read float {0}", val);
            return val;
        }

        /// <summary> Read an <c>double</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public double ReadDouble()
        {
            int offset;
            var buff = CheckLength(sizeof(double), out offset);
            var val = BitConverter.ToDouble(buff, offset);
            Trace("--Read double {0}", val);
            return val;
        }

        /// <summary> Read an <c>decimal</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public decimal ReadDecimal()
        {
            int offset;
            var buff = CheckLength(4 * sizeof(int), out offset);
            var raw = new int[4];
            Trace("--Read decimal");
            var n = offset;
            for (var i = 0; i < 4; i++)
            {
                raw[i] = BitConverter.ToInt32(buff, n);
                n += sizeof(int);
            }
            return new decimal(raw);
        }

        public DateTime ReadDateTime()
        {
            var n = ReadLong();
            return n == 0 ? default(DateTime) : DateTime.FromBinary(n);
        }

        /// <summary> Read an <c>string</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public string ReadString()
        {
            var n = ReadInt();
            if (n == 0)
            {
                Trace("--Read empty string");
                return String.Empty;
            }

            string s = null;
            // a length of -1 indicates that the string is null.
            if (-1 != n)
            {
                int offset;
                var buff = CheckLength(n, out offset);
                s = Encoding.UTF8.GetString(buff, offset, n);
            }

            Trace("--Read string '{0}'", s);
            return s;
        }

        /// <summary> Read the next bytes from the stream. </summary>
        /// <param name="count">Number of bytes to read.</param>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public byte[] ReadBytes(int count)
        {
            if (count == 0)
            {
                return emptyByteArray;
            }
            bool safeToUse;

            int offset;
            byte[] buff;
            if (!TryCheckLengthFast(count, out buff, out offset, out safeToUse))
            {
                buff = CheckLength(count, out offset, out safeToUse);
            }

            Trace("--Read byte array of length {0}", count);
            if (!safeToUse)
            {
                var result = new byte[count];
                Array.Copy(buff, offset, result, 0, count);
                return result;
            }
            else
            {
                return buff;
            }
        }

        /// <summary> Read the next bytes from the stream. </summary>
        /// <param name="destination">Output array to store the returned data in.</param>
        /// <param name="offset">Offset into the destination array to write to.</param>
        /// <param name="count">Number of bytes to read.</param>
        public void ReadByteArray(byte[] destination, int offset, int count)
        {
            if (offset + count > destination.Length)
            {
                throw new ArgumentOutOfRangeException("count", "Reading into an array that is too small");
            }

            var buffOffset = 0;
            var buff = count == 0 ? emptyByteArray : CheckLength(count, out buffOffset);
            Buffer.BlockCopy(buff, buffOffset, destination, offset, count);
        }

        /// <summary> Read an <c>char</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public char ReadChar()
        {
            Trace("--Read char");
            return Convert.ToChar(ReadShort());
        }

        /// <summary> Read an <c>byte</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public byte ReadByte()
        {
            int offset;
            var buff = CheckLength(1, out offset);
            Trace("--Read byte");
            return buff[offset];
        }

        public byte PeekByte()
        {
            if (currentOffset == currentSegment.Count + currentSegment.Offset)
                StartNextSegment();

            return currentBuffer[currentOffset];
        }

        /// <summary> Read an <c>sbyte</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public sbyte ReadSByte()
        {
            int offset;
            var buff = CheckLength(1, out offset);
            Trace("--Read sbyte");
            return unchecked((sbyte)(buff[offset]));
        }

        /// <summary> Read an <c>IPAddress</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public IPAddress ReadIPAddress()
        {
            int offset;
            var buff = CheckLength(16, out offset);
            bool v4 = true;
            for (var i = 0; i < 12; i++)
            {
                if (buff[offset + i] != 0)
                {
                    v4 = false;
                    break;
                }
            }

            if (v4)
            {
                var v4Bytes = new byte[4];
                for (var i = 0; i < 4; i++)
                {
                    v4Bytes[i] = buff[offset + 12 + i];
                }
                return new IPAddress(v4Bytes);
            }
            else
            {
                var v6Bytes = new byte[16];
                for (var i = 0; i < 16; i++)
                {
                    v6Bytes[i] = buff[offset + i];
                }
                return new IPAddress(v6Bytes);
            }
        }

        public Guid ReadGuid()
        {
            byte[] bytes = ReadBytes(16);
            return new Guid(bytes);
        }

        /// <summary> Read an <c>IPEndPoint</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public IPEndPoint ReadIPEndPoint()
        {
            var addr = ReadIPAddress();
            var port = ReadInt();
            return new IPEndPoint(addr, port);
        }

        /// <summary> Read an <c>SiloAddress</c> value from the stream. </summary>
        /// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
        public SiloAddress ReadSiloAddress()
        {
            var ep = ReadIPEndPoint();
            var gen = ReadInt();
            return SiloAddress.New(ep, gen);
        }

        public TimeSpan ReadTimeSpan()
        {
            return new TimeSpan(ReadLong());
        }

        /// <summary>
        /// Read a block of data into the specified output <c>Array</c>.
        /// </summary>
        /// <param name="array">Array to output the data to.</param>
        /// <param name="n">Number of bytes to read.</param>
        public void ReadBlockInto(Array array, int n)
        {
            int offset;
            var buff = CheckLength(n, out offset);
            Buffer.BlockCopy(buff, offset, array, 0, n);
            Trace("--Read block of {0} bytes", n);
        }

        private StreamWriter trace;

        [Conditional("TRACE_SERIALIZATION")]
        private void Trace(string format, params object[] args)
        {
            if (trace == null)
            {
                var path = String.Format("d:\\Trace-{0}.{1}.{2}.txt", DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Ticks);
                Console.WriteLine("Opening trace file at '{0}'", path);
                trace = File.CreateText(path);
            }
            trace.Write(format, args);
            trace.WriteLine(" at offset {0}", CurrentPosition);
            trace.Flush();
        }
    }
}


text:
from django.db import models
from django.utils import timezone

# Create your models here.

class Comment(models.Model):
    title = models.CharField(max_length=200)
    comment_text = models.TextField()
    rating = models.IntegerField()
    created_date = models.DateTimeField(default = timezone.now)
    published_date = models.DateTimeField(blank=True, null= True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

class Reservation(models.Model):
    name = models.CharField(max_length=200)
    people_amount = models.IntegerField(default = 1)
    time = models.TimeField(default = timezone.now)
    created_date = models.DateTimeField(default = timezone.now)
    published_date = models.DateTimeField(blank=True,null = True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__ (self):
        return self.name

redpajama_set_name: RedPajamaGithub


text:
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory(require("darch/lib/utils"), require("react"), require("lodash"));
	else if(typeof define === 'function' && define.amd)
		define(["darch/lib/utils", "react", "lodash"], factory);
	else if(typeof exports === 'object')
		exports["darch"] = factory(require("darch/lib/utils"), require("react"), require("lodash"));
	else
		root["darch"] = factory(root["darch/lib/utils"], root["react"], root["lodash"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_0__, __WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_4__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;
/******/
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// identity function for calling harmony imports with the correct context
/******/ 	__webpack_require__.i = function(value) { return value; };
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 341);
/******/ })
/************************************************************************/
/******/ ({

/***/ 0:
/***/ (function(module, exports) {

module.exports = __WEBPACK_EXTERNAL_MODULE_0__;

/***/ }),

/***/ 1:
/***/ (function(module, exports) {

module.exports = __WEBPACK_EXTERNAL_MODULE_1__;

/***/ }),

/***/ 2:
/***/ (function(module, exports) {

/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
module.exports = function() {
	var list = [];

	// return the list of modules as css string
	list.toString = function toString() {
		var result = [];
		for(var i = 0; i < this.length; i++) {
			var item = this[i];
			if(item[2]) {
				result.push("@media " + item[2] + "{" + item[1] + "}");
			} else {
				result.push(item[1]);
			}
		}
		return result.join("");
	};

	// import a list of modules into the list
	list.i = function(modules, mediaQuery) {
		if(typeof modules === "string")
			modules = [[null, modules, ""]];
		var alreadyImportedModules = {};
		for(var i = 0; i < this.length; i++) {
			var id = this[i][0];
			if(typeof id === "number")
				alreadyImportedModules[id] = true;
		}
		for(i = 0; i < modules.length; i++) {
			var item = modules[i];
			// skip already imported module
			// this implementation is not 100% perfect for weird media query combinations
			//  when a module is imported multiple times with different media queries.
			//  I hope this will never occur (Hey this way we have smaller bundles)
			if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) {
				if(mediaQuery && !item[2]) {
					item[2] = mediaQuery;
				} else if(mediaQuery) {
					item[2] = "(" + item[2] + ") and (" + mediaQuery + ")";
				}
				list.push(item);
			}
		}
	};
	return list;
};

/***/ }),

/***/ 3:
/***/ (function(module, exports) {

/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var stylesInDom = {},
	memoize = function(fn) {
		var memo;
		return function () {
			if (typeof memo === "undefined") memo = fn.apply(this, arguments);
			return memo;
		};
	},
	isOldIE = memoize(function() {
		return /msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase());
	}),
	getHeadElement = memoize(function () {
		return document.head || document.getElementsByTagName("head")[0];
	}),
	singletonElement = null,
	singletonCounter = 0,
	styleElementsInsertedAtTop = [];

module.exports = function(list, options) {
	if(typeof DEBUG !== "undefined" && DEBUG) {
		if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
	}

	options = options || {};
	// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
	// tags it will allow on a page
	if (typeof options.singleton === "undefined") options.singleton = isOldIE();

	// By default, add <style> tags to the bottom of <head>.
	if (typeof options.insertAt === "undefined") options.insertAt = "bottom";

	var styles = listToStyles(list);
	addStylesToDom(styles, options);

	return function update(newList) {
		var mayRemove = [];
		for(var i = 0; i < styles.length; i++) {
			var item = styles[i];
			var domStyle = stylesInDom[item.id];
			domStyle.refs--;
			mayRemove.push(domStyle);
		}
		if(newList) {
			var newStyles = listToStyles(newList);
			addStylesToDom(newStyles, options);
		}
		for(var i = 0; i < mayRemove.length; i++) {
			var domStyle = mayRemove[i];
			if(domStyle.refs === 0) {
				for(var j = 0; j < domStyle.parts.length; j++)
					domStyle.parts[j]();
				delete stylesInDom[domStyle.id];
			}
		}
	};
}

function addStylesToDom(styles, options) {
	for(var i = 0; i < styles.length; i++) {
		var item = styles[i];
		var domStyle = stylesInDom[item.id];
		if(domStyle) {
			domStyle.refs++;
			for(var j = 0; j < domStyle.parts.length; j++) {
				domStyle.parts[j](item.parts[j]);
			}
			for(; j < item.parts.length; j++) {
				domStyle.parts.push(addStyle(item.parts[j], options));
			}
		} else {
			var parts = [];
			for(var j = 0; j < item.parts.length; j++) {
				parts.push(addStyle(item.parts[j], options));
			}
			stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts};
		}
	}
}

function listToStyles(list) {
	var styles = [];
	var newStyles = {};
	for(var i = 0; i < list.length; i++) {
		var item = list[i];
		var id = item[0];
		var css = item[1];
		var media = item[2];
		var sourceMap = item[3];
		var part = {css: css, media: media, sourceMap: sourceMap};
		if(!newStyles[id])
			styles.push(newStyles[id] = {id: id, parts: [part]});
		else
			newStyles[id].parts.push(part);
	}
	return styles;
}

function insertStyleElement(options, styleElement) {
	var head = getHeadElement();
	var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1];
	if (options.insertAt === "top") {
		if(!lastStyleElementInsertedAtTop) {
			head.insertBefore(styleElement, head.firstChild);
		} else if(lastStyleElementInsertedAtTop.nextSibling) {
			head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling);
		} else {
			head.appendChild(styleElement);
		}
		styleElementsInsertedAtTop.push(styleElement);
	} else if (options.insertAt === "bottom") {
		head.appendChild(styleElement);
	} else {
		throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");
	}
}

function removeStyleElement(styleElement) {
	styleElement.parentNode.removeChild(styleElement);
	var idx = styleElementsInsertedAtTop.indexOf(styleElement);
	if(idx >= 0) {
		styleElementsInsertedAtTop.splice(idx, 1);
	}
}

function createStyleElement(options) {
	var styleElement = document.createElement("style");
	styleElement.type = "text/css";
	insertStyleElement(options, styleElement);
	return styleElement;
}

function createLinkElement(options) {
	var linkElement = document.createElement("link");
	linkElement.rel = "stylesheet";
	insertStyleElement(options, linkElement);
	return linkElement;
}

function addStyle(obj, options) {
	var styleElement, update, remove;

	if (options.singleton) {
		var styleIndex = singletonCounter++;
		styleElement = singletonElement || (singletonElement = createStyleElement(options));
		update = applyToSingletonTag.bind(null, styleElement, styleIndex, false);
		remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true);
	} else if(obj.sourceMap &&
		typeof URL === "function" &&
		typeof URL.createObjectURL === "function" &&
		typeof URL.revokeObjectURL === "function" &&
		typeof Blob === "function" &&
		typeof btoa === "function") {
		styleElement = createLinkElement(options);
		update = updateLink.bind(null, styleElement);
		remove = function() {
			removeStyleElement(styleElement);
			if(styleElement.href)
				URL.revokeObjectURL(styleElement.href);
		};
	} else {
		styleElement = createStyleElement(options);
		update = applyToTag.bind(null, styleElement);
		remove = function() {
			removeStyleElement(styleElement);
		};
	}

	update(obj);

	return function updateStyle(newObj) {
		if(newObj) {
			if(newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap)
				return;
			update(obj = newObj);
		} else {
			remove();
		}
	};
}

var replaceText = (function () {
	var textStore = [];

	return function (index, replacement) {
		textStore[index] = replacement;
		return textStore.filter(Boolean).join('\n');
	};
})();

function applyToSingletonTag(styleElement, index, remove, obj) {
	var css = remove ? "" : obj.css;

	if (styleElement.styleSheet) {
		styleElement.styleSheet.cssText = replaceText(index, css);
	} else {
		var cssNode = document.createTextNode(css);
		var childNodes = styleElement.childNodes;
		if (childNodes[index]) styleElement.removeChild(childNodes[index]);
		if (childNodes.length) {
			styleElement.insertBefore(cssNode, childNodes[index]);
		} else {
			styleElement.appendChild(cssNode);
		}
	}
}

function applyToTag(styleElement, obj) {
	var css = obj.css;
	var media = obj.media;

	if(media) {
		styleElement.setAttribute("media", media)
	}

	if(styleElement.styleSheet) {
		styleElement.styleSheet.cssText = css;
	} else {
		while(styleElement.firstChild) {
			styleElement.removeChild(styleElement.firstChild);
		}
		styleElement.appendChild(document.createTextNode(css));
	}
}

function updateLink(linkElement, obj) {
	var css = obj.css;
	var sourceMap = obj.sourceMap;

	if(sourceMap) {
		// http://stackoverflow.com/a/26603875
		css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
	}

	var blob = new Blob([css], { type: "text/css" });

	var oldSrc = linkElement.href;

	linkElement.href = URL.createObjectURL(blob);

	if(oldSrc)
		URL.revokeObjectURL(oldSrc);
}

/***/ }),

/***/ 302:
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(1);

var _react2 = _interopRequireDefault(_react);

var _utils = __webpack_require__(0);

var _styles = __webpack_require__(413);

var _styles2 = _interopRequireDefault(_styles);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function _makeJsClassGreatAgain(_this, funcName, params) {
    return Object.getPrototypeOf(_this)[funcName].apply(_this, params);
}

var Logger = new _utils.LoggerFactory("grid.cell", { level: "error" });

/**
 * Main component class.
 */

var Component = function (_React$Component) {
    _inherits(Component, _React$Component);

    function Component() {
        var _ref;

        var _temp, _temp2, _this2, _ret;

        _classCallCheck(this, Component);

        for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
        }

        return _ret = (_temp2 = (_temp = (_this2 = _possibleConstructorReturn(this, (_ref = Component.__proto__ || Object.getPrototypeOf(Component)).call.apply(_ref, [this].concat(args))), _this2), _this2.componentDidMount = function () {
            for (var _len2 = arguments.length, rest = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
                rest[_key2] = arguments[_key2];
            }

            return _makeJsClassGreatAgain(_this2, 'componentDidMount', rest);
        }, _temp), _this2.render = function () {
            for (var _len3 = arguments.length, rest = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
                rest[_key3] = arguments[_key3];
            }

            return _makeJsClassGreatAgain(_this2, 'render', rest);
        }, _temp2), _possibleConstructorReturn(_this2, _ret);
    }

    _createClass(Component, [{
        key: "componentDidMount",

        /**
         * LYFECICLE : This function is called when component
         * got mounted in the view.
         */
        value: function componentDidMount() {
            var logger = Logger.create("componentDidMount");
            logger.info("enter");
        }

        /**
         * This function is responsible for generating the component's view.
         */

        /** React properties **/

    }, {
        key: "render",
        value: function render() {
            var _props = this.props,
                span = _props.span,
                spots = _props.spots;

            var width = span / spots * 100;

            return _react2.default.createElement(
                "div",
                { className: _styles2.default.cell, style: { width: width + "%" } },
                this.props.children
            );
        }
    }]);

    return Component;
}(_react2.default.Component);

Component.displayName = "grid.cell";
Component.defaultProps = {
    span: 1,
    spots: 12
};
Component.propTypes = {
    span: _react2.default.PropTypes.number,
    spots: _react2.default.PropTypes.number
};
exports.default = Component;
module.exports = exports["default"];

/***/ }),

/***/ 324:
/***/ (function(module, exports, __webpack_require__) {

// style-loader: Adds some css to the DOM by adding a <style> tag

// load the styles
var content = __webpack_require__(381);
if(typeof content === 'string') content = [[module.i, content, '']];
// add the styles to the DOM
var update = __webpack_require__(3)(content, {});
if(content.locals) module.exports = content.locals;
// Hot Module Replacement
if(false) {
	// When the styles change, update the <style> tags
	if(!content.locals) {
		module.hot.accept("!!../../node_modules/css-loader/index.js?{\"modules\":true,\"sourceMap\":false,\"camelCase\":true,\"localIdentName\":\"[hash:base64:5]\"}!../../node_modules/stylus-loader/index.js?{\"preferPathResolver\":\"webpack\"}!./styles.styl", function() {
			var newContent = require("!!../../node_modules/css-loader/index.js?{\"modules\":true,\"sourceMap\":false,\"camelCase\":true,\"localIdentName\":\"[hash:base64:5]\"}!../../node_modules/stylus-loader/index.js?{\"preferPathResolver\":\"webpack\"}!./styles.styl");
			if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
			update(newContent);
		});
	}
	// When the module is disposed, remove the <style> tags
	module.hot.dispose(function() { update(); });
}

/***/ }),

/***/ 341:
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(1);

var _react2 = _interopRequireDefault(_react);

var _lodash = __webpack_require__(4);

var _lodash2 = _interopRequireDefault(_lodash);

var _utils = __webpack_require__(0);

var _styles = __webpack_require__(324);

var _styles2 = _interopRequireDefault(_styles);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function _makeJsClassGreatAgain(_this, funcName, params) {
    return Object.getPrototypeOf(_this)[funcName].apply(_this, params);
}

var Logger = new _utils.LoggerFactory("grid", { level: "error" });

/**
 * Main component class.
 */

var Component = function (_React$Component) {
    _inherits(Component, _React$Component);

    function Component() {
        var _ref;

        var _temp, _temp2, _temp3, _this2, _ret;

        _classCallCheck(this, Component);

        for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
        }

        return _ret = (_temp3 = (_temp2 = (_temp = (_this2 = _possibleConstructorReturn(this, (_ref = Component.__proto__ || Object.getPrototypeOf(Component)).call.apply(_ref, [this].concat(args))), _this2), _this2.componentDidMount = function () {
            for (var _len2 = arguments.length, rest = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
                rest[_key2] = arguments[_key2];
            }

            return _makeJsClassGreatAgain(_this2, 'componentDidMount', rest);
        }, _temp), _this2.processChildren = function () {
            for (var _len3 = arguments.length, rest = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
                rest[_key3] = arguments[_key3];
            }

            return _makeJsClassGreatAgain(_this2, 'processChildren', rest);
        }, _temp2), _this2.render = function () {
            for (var _len4 = arguments.length, rest = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
                rest[_key4] = arguments[_key4];
            }

            return _makeJsClassGreatAgain(_this2, 'render', rest);
        }, _temp3), _possibleConstructorReturn(_this2, _ret);
    }

    _createClass(Component, [{
        key: "componentDidMount",

        /**
         * LYFECICLE : This function is called when component
         * got mounted in the view.
         */

        /** React properties **/
        value: function componentDidMount() {
            var logger = Logger.create("componentDidMount");
            logger.info("enter");
        }

        /**
         * This function gets all cell children components and
         * adjust it's widths.
         */

        /** Nested components **/

    }, {
        key: "processChildren",
        value: function processChildren() {
            var _this3 = this;

            var logger = Logger.create("processChildren");
            logger.info("enter");

            var spots = 0;

            // Count cell children
            _react2.default.Children.forEach(this.props.children, function (component) {
                if (component.type.displayName == "grid.cell") {
                    spots += component.props.span || 1;
                }
            });

            logger.info("spots count", { spots: spots });

            return _react2.default.Children.map(this.props.children, function (component, idx) {
                logger.info("children map : " + idx, { type: component.type.displayName });

                // Strip non Cell component
                if (component.type.displayName != "grid.cell") {
                    return false;
                }

                // New processed component props
                var props = {};

                // Total cell spots
                props.spots = _this3.props.spots || spots;

                // Span
                props.span = component.props.span;

                logger.info("children map : " + idx + " : props", { props: props });

                // Get children
                props.children = component.props.children;

                // Clone cell with new props
                return _lodash2.default.size(props) ? _react2.default.cloneElement(component, props) : component;
            });
        }

        /**
         * This function is responsible for generating the component's view.
         */

    }, {
        key: "render",
        value: function render() {
            return _react2.default.createElement(
                "div",
                { className: _styles2.default.grid },
                this.processChildren()
            );
        }
    }]);

    return Component;
}(_react2.default.Component);

Component.displayName = "grid";
Component.defaultProps = {};
Component.propTypes = {
    spots: _react2.default.PropTypes.number
};
Component.Cell = __webpack_require__(302);
exports.default = Component;
module.exports = exports["default"];

/***/ }),

/***/ 380:
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports

// module
exports.push([module.i, ".UdUl4 {\n  position: relative;\n  min-height: 1px;\n  padding-left: 7.5px;\n  padding-right: 7.5px;\n}\n@media (max-width: 767px) {\n  .UdUl4 {\n    width: 100% !important;\n  }\n}\n@media (min-width: 768px) {\n  .UdUl4 {\n    float: left;\n  }\n}\n", ""]);

// exports
exports.locals = {
	"baseUnit": "px",
	"textSize": "18",
	"colorLight": "#fff",
	"colorDark": "#424242",
	"colorPositive": "#4183d7",
	"colorMoody": "#397cac",
	"colorCalm": "#26c6da",
	"colorStable": "#c6ccd2",
	"colorSuccess": "#26a65b",
	"colorWarning": "#f2b420",
	"colorDanger": "#ed4545",
	"cell": "UdUl4"
};

/***/ }),

/***/ 381:
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports

// module
exports.push([module.i, "._2TfCK {\n  margin-left: -7.5px;\n  margin-right: -7.5px;\n}\n._2TfCK:before,\n._2TfCK:after {\n  content: \" \";\n  display: table;\n}\n._2TfCK:after {\n  clear: both;\n}\n", ""]);

// exports
exports.locals = {
	"baseUnit": "px",
	"textSize": "18",
	"colorLight": "#fff",
	"colorDark": "#424242",
	"colorPositive": "#4183d7",
	"colorMoody": "#397cac",
	"colorCalm": "#26c6da",
	"colorStable": "#c6ccd2",
	"colorSuccess": "#26a65b",
	"colorWarning": "#f2b420",
	"colorDanger": "#ed4545",
	"grid": "_2TfCK"
};

/***/ }),

/***/ 4:
/***/ (function(module, exports) {

module.exports = __WEBPACK_EXTERNAL_MODULE_4__;

/***/ }),

/***/ 413:
/***/ (function(module, exports, __webpack_require__) {

// style-loader: Adds some css to the DOM by adding a <style> tag

// load the styles
var content = __webpack_require__(380);
if(typeof content === 'string') content = [[module.i, content, '']];
// add the styles to the DOM
var update = __webpack_require__(3)(content, {});
if(content.locals) module.exports = content.locals;
// Hot Module Replacement
if(false) {
	// When the styles change, update the <style> tags
	if(!content.locals) {
		module.hot.accept("!!../../../node_modules/css-loader/index.js?{\"modules\":true,\"sourceMap\":false,\"camelCase\":true,\"localIdentName\":\"[hash:base64:5]\"}!../../../node_modules/stylus-loader/index.js?{\"preferPathResolver\":\"webpack\"}!./styles.styl", function() {
			var newContent = require("!!../../../node_modules/css-loader/index.js?{\"modules\":true,\"sourceMap\":false,\"camelCase\":true,\"localIdentName\":\"[hash:base64:5]\"}!../../../node_modules/stylus-loader/index.js?{\"preferPathResolver\":\"webpack\"}!./styles.styl");
			if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
			update(newContent);
		});
	}
	// When the module is disposed, remove the <style> tags
	module.hot.dispose(function() { update(); });
}

/***/ })

/******/ });
});


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.sql.gen;

import com.facebook.presto.bytecode.CallSiteBinder;
import com.facebook.presto.bytecode.ClassDefinition;
import com.facebook.presto.bytecode.CompilationException;
import com.facebook.presto.common.function.SqlFunctionProperties;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.operator.project.CursorProcessor;
import com.facebook.presto.operator.project.PageFilter;
import com.facebook.presto.operator.project.PageProcessor;
import com.facebook.presto.operator.project.PageProjectionWithOutputs;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.function.SqlFunctionId;
import com.facebook.presto.spi.function.SqlInvokedFunction;
import com.facebook.presto.spi.relation.RowExpression;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import org.weakref.jmx.Managed;
import org.weakref.jmx.Nested;

import javax.inject.Inject;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.function.Supplier;

import static com.facebook.presto.bytecode.Access.FINAL;
import static com.facebook.presto.bytecode.Access.PUBLIC;
import static com.facebook.presto.bytecode.Access.a;
import static com.facebook.presto.bytecode.ParameterizedType.type;
import static com.facebook.presto.common.type.BooleanType.BOOLEAN;
import static com.facebook.presto.spi.StandardErrorCode.COMPILER_ERROR;
import static com.facebook.presto.sql.gen.BytecodeUtils.invoke;
import static com.facebook.presto.sql.relational.Expressions.constant;
import static com.facebook.presto.util.CompilerUtils.defineClass;
import static com.facebook.presto.util.CompilerUtils.makeClassName;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.Collections.emptyMap;
import static java.util.Objects.requireNonNull;

public class ExpressionCompiler
{
    private final PageFunctionCompiler pageFunctionCompiler;
    private final LoadingCache<CacheKey, Class<? extends CursorProcessor>> cursorProcessors;
    private final CacheStatsMBean cacheStatsMBean;

    @Inject
    public ExpressionCompiler(Metadata metadata, PageFunctionCompiler pageFunctionCompiler)
    {
        requireNonNull(metadata, "metadata is null");
        this.pageFunctionCompiler = requireNonNull(pageFunctionCompiler, "pageFunctionCompiler is null");
        this.cursorProcessors = CacheBuilder.newBuilder()
                .recordStats()
                .maximumSize(1000)
                .build(CacheLoader.from(key -> compile(
                        key.getSqlFunctionProperties(),
                        key.getFilter(),
                        key.getProjections(),
                        new CursorProcessorCompiler(metadata, key.isOptimizeCommonSubExpression(), key.getSessionFunctions()),
                        CursorProcessor.class)));

        this.cacheStatsMBean = new CacheStatsMBean(cursorProcessors);
    }

    @Managed
    @Nested
    public CacheStatsMBean getCursorProcessorCache()
    {
        return cacheStatsMBean;
    }

    public Supplier<CursorProcessor> compileCursorProcessor(
            SqlFunctionProperties sqlFunctionProperties,
            Optional<RowExpression> filter,
            List<? extends RowExpression> projections,
            Object uniqueKey)
    {
        return compileCursorProcessor(sqlFunctionProperties, filter, projections, uniqueKey, true);
    }

    public Supplier<CursorProcessor> compileCursorProcessor(
            SqlFunctionProperties sqlFunctionProperties,
            Optional<RowExpression> filter,
            List<? extends RowExpression> projections,
            Object uniqueKey,
            boolean isOptimizeCommonSubExpression)
    {
        return compileCursorProcessor(sqlFunctionProperties, filter, projections, uniqueKey, isOptimizeCommonSubExpression, emptyMap());
    }

    public Supplier<CursorProcessor> compileCursorProcessor(
            SqlFunctionProperties sqlFunctionProperties,
            Optional<RowExpression> filter,
            List<? extends RowExpression> projections,
            Object uniqueKey,
            boolean isOptimizeCommonSubExpression,
            Map<SqlFunctionId, SqlInvokedFunction> sessionFunctions)
    {
        Class<? extends CursorProcessor> cursorProcessor = cursorProcessors.getUnchecked(
                new CacheKey(
                        sqlFunctionProperties,
                        sessionFunctions,
                        filter,
                        projections,
                        uniqueKey,
                        isOptimizeCommonSubExpression));
        return () -> {
            try {
                return cursorProcessor.getConstructor().newInstance();
            }
            catch (ReflectiveOperationException e) {
                throw new RuntimeException(e);
            }
        };
    }

    public Supplier<PageProcessor> compilePageProcessor(
            SqlFunctionProperties sqlFunctionProperties,
            Optional<RowExpression> filter,
            List<? extends RowExpression> projections,
            boolean isOptimizeCommonSubExpression,
            Map<SqlFunctionId, SqlInvokedFunction> sessionFunctions,
            Optional<String> classNameSuffix)
    {
        return compilePageProcessor(sqlFunctionProperties, filter, projections, isOptimizeCommonSubExpression, sessionFunctions, classNameSuffix, OptionalInt.empty());
    }

    private Supplier<PageProcessor> compilePageProcessor(
            SqlFunctionProperties sqlFunctionProperties,
            Optional<RowExpression> filter,
            List<? extends RowExpression> projections,
            boolean isOptimizeCommonSubExpression,
            Map<SqlFunctionId, SqlInvokedFunction> sessionFunctions,
            Optional<String> classNameSuffix,
            OptionalInt initialBatchSize)
    {
        Optional<Supplier<PageFilter>> filterFunctionSupplier = filter.map(expression ->
                pageFunctionCompiler.compileFilter(sqlFunctionProperties, sessionFunctions, expression, isOptimizeCommonSubExpression, classNameSuffix));
        List<Supplier<PageProjectionWithOutputs>> pageProjectionSuppliers = pageFunctionCompiler.compileProjections(
                sqlFunctionProperties,
                sessionFunctions,
                projections,
                isOptimizeCommonSubExpression,
                classNameSuffix);

        return () -> {
            Optional<PageFilter> filterFunction = filterFunctionSupplier.map(Supplier::get);
            List<PageProjectionWithOutputs> pageProjections = pageProjectionSuppliers.stream()
                    .map(Supplier::get)
                    .collect(toImmutableList());
            return new PageProcessor(filterFunction, pageProjections, initialBatchSize);
        };
    }

    @VisibleForTesting
    public Supplier<PageProcessor> compilePageProcessor(SqlFunctionProperties sqlFunctionProperties, Optional<RowExpression> filter, List<? extends RowExpression> projections)
    {
        return compilePageProcessor(sqlFunctionProperties, filter, projections, true, emptyMap(), Optional.empty());
    }

    @VisibleForTesting
    public Supplier<PageProcessor> compilePageProcessor(SqlFunctionProperties sqlFunctionProperties, Optional<RowExpression> filter, List<? extends RowExpression> projections, boolean isOptimizeCommonSubExpression, int initialBatchSize)
    {
        return compilePageProcessor(sqlFunctionProperties, filter, projections, isOptimizeCommonSubExpression, emptyMap(), Optional.empty(), OptionalInt.of(initialBatchSize));
    }

    @VisibleForTesting
    public Supplier<PageProcessor> compilePageProcessor(SqlFunctionProperties sqlFunctionProperties, Optional<RowExpression> filter, List<? extends RowExpression> projections, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix)
    {
        return compilePageProcessor(sqlFunctionProperties, filter, projections, isOptimizeCommonSubExpression, emptyMap(), classNameSuffix);
    }

    private <T> Class<? extends T> compile(
            SqlFunctionProperties sqlFunctionProperties,
            Optional<RowExpression> filter,
            List<RowExpression> projections,
            BodyCompiler bodyCompiler,
            Class<? extends T> superType)
    {
        // create filter and project page iterator class
        try {
            return compileProcessor(sqlFunctionProperties, filter.orElse(constant(true, BOOLEAN)), projections, bodyCompiler, superType);
        }
        catch (CompilationException e) {
            throw new PrestoException(COMPILER_ERROR, e.getCause());
        }
    }

    private <T> Class<? extends T> compileProcessor(
            SqlFunctionProperties sqlFunctionProperties,
            RowExpression filter,
            List<RowExpression> projections,
            BodyCompiler bodyCompiler,
            Class<? extends T> superType)
    {
        ClassDefinition classDefinition = new ClassDefinition(
                a(PUBLIC, FINAL),
                makeClassName(superType.getSimpleName()),
                type(Object.class),
                type(superType));

        CallSiteBinder callSiteBinder = new CallSiteBinder();
        bodyCompiler.generateMethods(sqlFunctionProperties, classDefinition, callSiteBinder, filter, projections);

        //
        // toString method
        //
        generateToString(
                classDefinition,
                callSiteBinder,
                toStringHelper(classDefinition.getType().getJavaClassName())
                        .add("filter", filter)
                        .add("projections", projections)
                        .toString());

        return defineClass(classDefinition, superType, callSiteBinder.getBindings(), getClass().getClassLoader());
    }

    private static void generateToString(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, String string)
    {
        // bind constant via invokedynamic to avoid constant pool issues due to large strings
        classDefinition.declareMethod(a(PUBLIC), "toString", type(String.class))
                .getBody()
                .append(invoke(callSiteBinder.bind(string, String.class), "toString"))
                .retObject();
    }

    private static final class CacheKey
    {
        private final SqlFunctionProperties sqlFunctionProperties;
        private final Map<SqlFunctionId, SqlInvokedFunction> sessionFunctions;
        private final Optional<RowExpression> filter;
        private final List<RowExpression> projections;
        private final Object uniqueKey;
        private final boolean isOptimizeCommonSubExpression;

        private CacheKey(
                SqlFunctionProperties sqlFunctionProperties,
                Map<SqlFunctionId, SqlInvokedFunction> sessionFunctions,
                Optional<RowExpression> filter,
                List<? extends RowExpression> projections,
                Object uniqueKey,
                boolean isOptimizeCommonSubExpression)
        {
            this.sqlFunctionProperties = sqlFunctionProperties;
            this.sessionFunctions = sessionFunctions;
            this.filter = filter;
            this.uniqueKey = uniqueKey;
            this.projections = ImmutableList.copyOf(projections);
            this.isOptimizeCommonSubExpression = isOptimizeCommonSubExpression;
        }

        public SqlFunctionProperties getSqlFunctionProperties()
        {
            return sqlFunctionProperties;
        }

        public Map<SqlFunctionId, SqlInvokedFunction> getSessionFunctions()
        {
            return sessionFunctions;
        }

        private Optional<RowExpression> getFilter()
        {
            return filter;
        }

        private List<RowExpression> getProjections()
        {
            return projections;
        }

        private boolean isOptimizeCommonSubExpression()
        {
            return isOptimizeCommonSubExpression;
        }

        @Override
        public int hashCode()
        {
            return Objects.hash(sqlFunctionProperties, filter, projections, uniqueKey, isOptimizeCommonSubExpression);
        }

        @Override
        public boolean equals(Object obj)
        {
            if (this == obj) {
                return true;
            }
            if (obj == null || getClass() != obj.getClass()) {
                return false;
            }
            CacheKey other = (CacheKey) obj;
            return Objects.equals(this.sqlFunctionProperties, other.sqlFunctionProperties) &&
                    Objects.equals(this.filter, other.filter) &&
                    Objects.equals(this.projections, other.projections) &&
                    Objects.equals(this.uniqueKey, other.uniqueKey) &&
                    Objects.equals(this.isOptimizeCommonSubExpression, other.isOptimizeCommonSubExpression);
        }

        @Override
        public String toString()
        {
            return toStringHelper(this)
                    .add("sqlFunctionProperties", sqlFunctionProperties)
                    .add("filter", filter)
                    .add("projections", projections)
                    .add("uniqueKey", uniqueKey)
                    .add("isOptimizeCommonSubExpression", isOptimizeCommonSubExpression)
                    .toString();
        }
    }
}


text:
package org.batfish.datamodel.questions;

import static com.google.common.base.Preconditions.checkArgument;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import org.batfish.datamodel.BgpActivePeerConfig;
import org.batfish.datamodel.BgpPassivePeerConfig;
import org.batfish.datamodel.BgpPeerConfig;
import org.batfish.datamodel.BgpUnnumberedPeerConfig;
import org.batfish.datamodel.Ip;
import org.batfish.datamodel.answers.Schema;
import org.batfish.datamodel.bgp.AddressFamily;
import org.batfish.datamodel.bgp.AddressFamilyCapabilities;
import org.batfish.specifier.ConstantEnumSetSpecifier;
import org.batfish.specifier.Grammar;
import org.batfish.specifier.SpecifierFactories;

/**
 * Enables specification of a set of BGP peer properties.
 *
 *
Example specifiers:
 *
 *

 *
local_as —> gets the peer's local AS
 *
.*policy -> gets all properties that end with 'policy'
 *

 */
@ParametersAreNonnullByDefault
public class BgpPeerPropertySpecifier extends PropertySpecifier {

  public static final String CONFEDERATION = "Confederation";
  public static final String DESCRIPTION = "Description";
  public static final String LOCAL_AS = "Local_AS";
  public static final String LOCAL_IP = "Local_IP";
  public static final String IS_PASSIVE = "Is_Passive";
  public static final String REMOTE_AS = "Remote_AS";
  public static final String ROUTE_REFLECTOR_CLIENT = "Route_Reflector_Client";
  public static final String CLUSTER_ID = "Cluster_ID";
  public static final String PEER_GROUP = "Peer_Group";
  public static final String IMPORT_POLICY = "Import_Policy";
  public static final String EXPORT_POLICY = "Export_Policy";
  public static final String SEND_COMMUNITY = "Send_Community";

  private static final Map<String, PropertyDescriptor<BgpPeerConfig>> JAVA_MAP =
      new ImmutableMap.Builder<String, PropertyDescriptor<BgpPeerConfig>>()
          .put(
              LOCAL_AS,
              new PropertyDescriptor<>(BgpPeerConfig::getLocalAs, Schema.LONG, "Local AS number"))
          .put(
              LOCAL_IP,
              new PropertyDescriptor<>(
                  BgpPeerPropertySpecifier::getLocalIp,
                  Schema.IP,
                  "Local IPv4 address (null for BGP unnumbered peers)"))
          .put(
              IS_PASSIVE,
              new PropertyDescriptor<>(
                  BgpPeerPropertySpecifier::getIsPassive,
                  Schema.BOOLEAN,
                  "Whether this peer is passive"))
          .put(
              REMOTE_AS,
              new PropertyDescriptor<>(
                  BgpPeerConfig::getRemoteAsns,
                  Schema.STRING,
                  "Remote AS numbers with which this peer may establish a session"))
          .put(
              ROUTE_REFLECTOR_CLIENT,
              new PropertyDescriptor<>(
                  c ->
                      Optional.ofNullable(c.getIpv4UnicastAddressFamily())
                          .map(AddressFamily::getRouteReflectorClient)
                          .orElse(false),
                  Schema.BOOLEAN,
                  "Whether this peer is a route reflector client"))
          .put(
              CLUSTER_ID,
              new PropertyDescriptor<>(
                  BgpPeerPropertySpecifier::getClusterId,
                  Schema.IP,
                  "Cluster ID of this peer (null for peers that are not route reflector clients)"))
          .put(
              PEER_GROUP,
              new PropertyDescriptor<>(
                  BgpPeerConfig::getGroup,
                  Schema.STRING,
                  "Name of the BGP peer group to which this peer belongs"))
          .put(
              IMPORT_POLICY,
              new PropertyDescriptor<>(
                  c ->
                      Optional.ofNullable(c.getIpv4UnicastAddressFamily())
                          .map(AddressFamily::getImportPolicySources)
                          .orElse(ImmutableSortedSet.of()),
                  Schema.set(Schema.STRING),
                  "Names of import policies to be applied to routes received by this peer"))
          .put(
              EXPORT_POLICY,
              new PropertyDescriptor<>(
                  c ->
                      Optional.ofNullable(c.getIpv4UnicastAddressFamily())
                          .map(AddressFamily::getExportPolicySources)
                          .orElse(ImmutableSortedSet.of()),
                  Schema.set(Schema.STRING),
                  "Names of export policies to be applied to routes exported by this peer"))
          .put(
              SEND_COMMUNITY,
              new PropertyDescriptor<>(
                  c ->
                      Optional.ofNullable(c.getIpv4UnicastAddressFamily())
                          .map(AddressFamily::getAddressFamilyCapabilities)
                          .map(AddressFamilyCapabilities::getSendCommunity)
                          .orElse(false),
                  Schema.BOOLEAN,
                  "Whether this peer propagates communities"))
          .put(
              CONFEDERATION,
              new PropertyDescriptor<>(
                  BgpPeerConfig::getConfederationAsn, Schema.LONG, "Confederation AS number"))
          .put(
              DESCRIPTION,
              new PropertyDescriptor<>(
                  BgpPeerConfig::getDescription, Schema.STRING, "Configured peer description"))
          .build();

  /** Returns the property descriptor for {@code property} */
  public static PropertyDescriptor<BgpPeerConfig> getPropertyDescriptor(String property) {
    checkArgument(JAVA_MAP.containsKey(property), "Property " + property + " does not exist");
    return JAVA_MAP.get(property);
  }

  /** A {@link BgpPeerPropertySpecifier} that matches all BGP properties. */
  public static final BgpPeerPropertySpecifier ALL =
      new BgpPeerPropertySpecifier(JAVA_MAP.keySet());

  private final List<String> _properties;

  /**
   * Create a bgp peer property specifier from provided expression. If the expression is null or
   * empty, a specifier with all properties is returned.
   */
  public static BgpPeerPropertySpecifier create(@Nullable String expression) {
    return new BgpPeerPropertySpecifier(
        SpecifierFactories.getEnumSetSpecifierOrDefault(
                expression,
                Grammar.BGP_PEER_PROPERTY_SPECIFIER,
                new ConstantEnumSetSpecifier<>(JAVA_MAP.keySet()))
            .resolve());
  }

  /** Returns a specifier that maps to all properties in {@code properties} */
  public BgpPeerPropertySpecifier(Set<String> properties) {
    Set<String> diffSet = Sets.difference(properties, JAVA_MAP.keySet());
    checkArgument(
        diffSet.isEmpty(),
        "Invalid properties supplied: %s. Valid properties are %s",
        diffSet,
        JAVA_MAP.keySet());
    _properties = properties.stream().sorted().collect(ImmutableList.toImmutableList());
  }

  /** Returns cluster ID of this peer */
  private static Object getClusterId(BgpPeerConfig peer) {
    return peer.getAllAddressFamilies().stream().noneMatch(AddressFamily::getRouteReflectorClient)
            || peer.getClusterId() == null
        ? null
        : Ip.create(peer.getClusterId());
  }

  @Override
  public List<String> getMatchingProperties() {
    return _properties;
  }

  private static Ip getLocalIp(@Nonnull BgpPeerConfig peer) {
    // Do not expose local IP of unnumbered peers
    return peer instanceof BgpUnnumberedPeerConfig ? null : peer.getLocalIp();
  }

  @VisibleForTesting
  static boolean getIsPassive(@Nonnull BgpPeerConfig peer) {
    if (peer instanceof BgpActivePeerConfig || peer instanceof BgpUnnumberedPeerConfig) {
      return false;
    }
    if (peer instanceof BgpPassivePeerConfig) {
      return true;
    }
    throw new IllegalArgumentException(String.format("Unrecognized peer type: %s", peer));
  }

  @Override
  public boolean equals(Object o) {
    if (!(o instanceof BgpPeerPropertySpecifier)) {
      return false;
    }
    return _properties.equals(((BgpPeerPropertySpecifier) o)._properties);
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(_properties);
  }
}


text:
package io.openthread.commissioner.service;

import androidx.annotation.NonNull;
import io.openthread.commissioner.ErrorCode;

public class ThreadCommissionerException extends Exception {

  private final ErrorCode code;

  @NonNull private final String message;

  public ThreadCommissionerException(ErrorCode code, String message) {
    this.code = code;
    this.message = message;
  }

  public ErrorCode getCode() {
    return code;
  }

  public String getMessage() {
    return message;
  }

  @Override
  public String toString() {
    return String.format("[ %s ]: %s", code.toString(), message);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2022 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     https://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<!-- Definitions of attributes to be exposed as public -->
<resources>
  <public name="materialSearchBarStyle" type="attr"/>
  <public name="materialSearchViewStyle" type="attr"/>
  <public name="materialSearchViewPrefixStyle" type="attr"/>
  <public name="defaultMarginsEnabled" type="attr"/>
  <public name="defaultScrollFlagsEnabled" type="attr"/>
  <public name="hideNavigationIcon" type="attr"/>
  <public name="forceDefaultNavigationOnClickListener" type="attr"/>
  <public name="tintNavigationIcon" type="attr"/>
  <public name="Widget.Material3.SearchBar" type="style"/>
  <public name="Widget.Material3.SearchBar.Outlined" type="style"/>
  <public name="Widget.Material3.SearchView" type="style"/>
  <public name="Widget.Material3.SearchView.Toolbar" type="style"/>
  <public name="TextAppearance.Material3.SearchBar" type="style"/>
  <public name="TextAppearance.Material3.SearchView" type="style"/>
  <public name="Widget.Material3.SearchView.Prefix" type="style"/>
  <public name="TextAppearance.Material3.SearchView.Prefix" type="style"/>
  <public name="ShapeAppearanceOverlay.Material3.SearchBar" type="style"/>
  <public name="ThemeOverlay.Material3.Search" type="style"/>
  <public name="Widget.Material3.Search.ActionButton.Overflow" type="style"/>
  <public name="Widget.Material3.Search.Toolbar.Button.Navigation" type="style"/>
</resources>


text:
'use strict';

import * as assert from 'assert';
import { IDisposable } from 'vs/base/common/lifecycle';
import { TPromise } from 'vs/base/common/winjs.base';
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
import { CommandService } from 'vs/platform/commands/common/commandService';
import { IExtensionService, ExtensionPointContribution, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { IExtensionPoint } from 'vs/platform/extensions/common/extensionsRegistry';
import { ContextKeyService } from 'vs/platform/contextkey/browser/contextKeyService';
import { SimpleConfigurationService } from 'vs/editor/standalone/browser/simpleServices';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';

class SimpleExtensionService implements IExtensionService {
	_serviceBrand: any;
	activateByEvent(activationEvent: string): TPromise<void> {
		return this.onReady().then(() => { });
	}
	onReady(): TPromise<boolean> {
		return TPromise.as(true);
	}
	readExtensionPointContributions<T>(extPoint: IExtensionPoint<T>): TPromise<ExtensionPointContribution<T>[]> {
		return TPromise.as([]);
	}
	getExtensionsStatus() {
		return undefined;
	}
	getExtensionsActivationTimes() {
		return undefined;
	}
	getExtensions(): TPromise<IExtensionDescription[]> {
		return TPromise.wrap([]);
	}
	restartExtensionHost(): void {
	}
	startExtensionHost(): void {
	}
	stopExtensionHost(): void {
	}
}

suite('CommandService', function () {

	let commandRegistration: IDisposable;

	setup(function () {
		commandRegistration = CommandsRegistry.registerCommand('foo', function () { });
	});

	teardown(function () {
		commandRegistration.dispose();
	});

	test('activateOnCommand', function () {

		let lastEvent: string;

		let service = new CommandService(new InstantiationService(), new class extends SimpleExtensionService {
			activateByEvent(activationEvent: string): TPromise<void> {
				lastEvent = activationEvent;
				return super.activateByEvent(activationEvent);
			}
		}, new ContextKeyService(new SimpleConfigurationService()));

		return service.executeCommand('foo').then(() => {
			assert.ok(lastEvent, 'onCommand:foo');
			return service.executeCommand('unknownCommandId');
		}).then(() => {
			assert.ok(false);
		}, () => {
			assert.ok(lastEvent, 'onCommand:unknownCommandId');
		});
	});

	test('fwd activation error', function () {

		let service = new CommandService(new InstantiationService(), new class extends SimpleExtensionService {
			activateByEvent(activationEvent: string): TPromise<void> {
				return TPromise.wrapError<void>(new Error('bad_activate'));
			}
		}, new ContextKeyService(new SimpleConfigurationService()));

		return service.executeCommand('foo').then(() => assert.ok(false), err => {
			assert.equal(err.message, 'bad_activate');
		});
	});

	test('!onReady, but executeCommand', function () {

		let callCounter = 0;
		let reg = CommandsRegistry.registerCommand('bar', () => callCounter += 1);

		let service = new CommandService(new InstantiationService(), new class extends SimpleExtensionService {
			onReady() {
				return new TPromise<boolean>(_resolve => { /*ignore*/ });
			}
		}, new ContextKeyService(new SimpleConfigurationService()));

		return service.executeCommand('bar').then(() => {
			reg.dispose();
			assert.equal(callCounter, 1);

		});
	});

	test('honor command-precondition', function () {
		let contextKeyService = new ContextKeyService(new SimpleConfigurationService());
		let commandService = new CommandService(
			new InstantiationService(),
			new SimpleExtensionService(),
			contextKeyService
		);

		let counter = 0;
		let reg = CommandsRegistry.registerCommand({
			id: 'bar',
			handler: () => { counter += 1; },
			precondition: ContextKeyExpr.has('foocontext')
		});

		return commandService.executeCommand('bar').then(() => {
			assert.throws(() => { });
		}, () => {
			contextKeyService.setContext('foocontext', true);
			return commandService.executeCommand('bar');
		}).then(() => {
			assert.equal(counter, 1);
			reg.dispose();
		});

	});
});