text:
using Orleans.Serialization.Buffers;
using Orleans.Serialization.Cloning;
using Orleans.Serialization.GeneratedCodeHelpers;
using Orleans.Serialization.WireProtocol;
using System;
using System.Runtime.CompilerServices;

namespace Orleans.Serialization.Codecs
{
    /// <summary>
    /// Serializer for <see cref="Tuple{T1}"/>.
    /// </summary>
    /// <typeparam name="T">The element type.</typeparam>
    [RegisterSerializer]
    public sealed class TupleCodec<T> : IFieldCodec<Tuple<T>>
    {
        private readonly Type CodecElementType = typeof(T);

        private readonly IFieldCodec<T> _valueCodec;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCodec{T}"/> class.
        /// </summary>
        /// <param name="valueCodec">The value codec.</param>
        public TupleCodec(IFieldCodec<T> valueCodec)
        {
            _valueCodec = OrleansGeneratedCodeHelper.UnwrapService(this, valueCodec);
        }

        /// <inheritdoc />
        void IFieldCodec<Tuple<T>>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, Tuple<T> value)
        {
            if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value))
            {
                return;
            }

            writer.WriteFieldHeader(fieldIdDelta, expectedType, value.GetType(), WireType.TagDelimited);

            _valueCodec.WriteField(ref writer, 1, CodecElementType, value.Item1);

            writer.WriteEndObject();
        }

        /// <inheritdoc />
        Tuple<T> IFieldCodec<Tuple<T>>.ReadValue<TInput>(ref Reader<TInput> reader, Field field)
        {
            if (field.WireType == WireType.Reference)
            {
                return ReferenceCodec.ReadReference<Tuple<T>, TInput>(ref reader, field);
            }

            if (field.WireType != WireType.TagDelimited)
            {
                ThrowUnsupportedWireTypeException();
            }

            var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session);
            var item1 = default(T);
            uint fieldId = 0;
            while (true)
            {
                var header = reader.ReadFieldHeader();
                if (header.IsEndBaseOrEndObject)
                {
                    break;
                }

                fieldId += header.FieldIdDelta;
                switch (fieldId)
                {
                    case 1:
                        item1 = _valueCodec.ReadValue(ref reader, header);
                        break;
                    default:
                        reader.ConsumeUnknownField(header);
                        break;
                }
            }

            var result = new Tuple<T>(item1);
            ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId);
            return result;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private static void ThrowUnsupportedWireTypeException() => throw new UnsupportedWireTypeException(
            $"Only a {nameof(WireType)} value of {WireType.TagDelimited} is supported for tuple fields.");
    }

    /// <summary>
    /// Copier for <see cref="Tuple{T1}"/>.
    /// </summary>
    /// <typeparam name="T">The element type.</typeparam>
    [RegisterCopier]
    public class TupleCopier<T> : IDeepCopier<Tuple<T>>
    {
        private readonly IDeepCopier<T> _copier;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCopier{T}"/> class.
        /// </summary>
        /// <param name="copier">The copier.</param>
        public TupleCopier(IDeepCopier<T> copier)
        {
            _copier = copier;
        }

        /// <inheritdoc />
        public Tuple<T> DeepCopy(Tuple<T> input, CopyContext context)
        {
            if (context.TryGetCopy(input, out Tuple<T> result))
            {
                return result;
            }

            if (input.GetType() != typeof(Tuple<T>))
            {
                return context.Copy(input);
            }

            result = new Tuple<T>(_copier.DeepCopy(input.Item1, context));
            context.RecordCopy(input, result);
            return result;
        }
    }

    /// <summary>
    /// Serializer for <see cref="Tuple{T1, T2}"/>.
    /// </summary>
    /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
    /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
    [RegisterSerializer]
    public class TupleCodec<T1, T2> : IFieldCodec<Tuple<T1, T2>>
    {
        private static readonly Type ElementType1 = typeof(T1);
        private static readonly Type ElementType2 = typeof(T2);

        private readonly IFieldCodec<T1> _item1Codec;
        private readonly IFieldCodec<T2> _item2Codec;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCodec{T1, T2}"/> class.
        /// </summary>
        /// <param name="item1Codec">The <typeparamref name="T1"/> codec.</param>
        /// <param name="item2Codec">The <typeparamref name="T2"/> codec.</param>
        public TupleCodec(IFieldCodec<T1> item1Codec, IFieldCodec<T2> item2Codec)
        {
            _item1Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item1Codec);
            _item2Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item2Codec);
        }

        /// <inheritdoc />
        void IFieldCodec<Tuple<T1, T2>>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, Tuple<T1, T2> value)
        {
            if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value))
            {
                return;
            }

            writer.WriteFieldHeader(fieldIdDelta, expectedType, value.GetType(), WireType.TagDelimited);

            _item1Codec.WriteField(ref writer, 1, ElementType1, value.Item1);
            _item2Codec.WriteField(ref writer, 1, ElementType2, value.Item2);

            writer.WriteEndObject();
        }

        /// <inheritdoc />
        Tuple<T1, T2> IFieldCodec<Tuple<T1, T2>>.ReadValue<TInput>(ref Reader<TInput> reader, Field field)
        {
            if (field.WireType == WireType.Reference)
            {
                return ReferenceCodec.ReadReference<Tuple<T1, T2>, TInput>(ref reader, field);
            }

            if (field.WireType != WireType.TagDelimited)
            {
                ThrowUnsupportedWireTypeException();
            }

            var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session);
            var item1 = default(T1);
            var item2 = default(T2);
            uint fieldId = 0;
            while (true)
            {
                var header = reader.ReadFieldHeader();
                if (header.IsEndBaseOrEndObject)
                {
                    break;
                }

                fieldId += header.FieldIdDelta;
                switch (fieldId)
                {
                    case 1:
                        item1 = _item1Codec.ReadValue(ref reader, header);
                        break;
                    case 2:
                        item2 = _item2Codec.ReadValue(ref reader, header);
                        break;
                    default:
                        reader.ConsumeUnknownField(header);
                        break;
                }
            }

            var result = new Tuple<T1, T2>(item1, item2);
            ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId);
            return result;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private static void ThrowUnsupportedWireTypeException() => throw new UnsupportedWireTypeException(
            $"Only a {nameof(WireType)} value of {WireType.TagDelimited} is supported for tuple fields.");
    }

    /// <summary>
    /// Copier for <see cref="Tuple{T1, T2}"/>
    /// </summary>
    /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
    /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
    [RegisterCopier]
    public class TupleCopier<T1, T2> : IDeepCopier<Tuple<T1, T2>>
    {
        private readonly IDeepCopier<T1> _copier1;
        private readonly IDeepCopier<T2> _copier2;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCopier{T1, T2}"/> class.
        /// </summary>
        /// <param name="copier1">The copier for <typeparamref name="T1"/>.</param>
        /// <param name="copier2">The copier for <typeparamref name="T2"/>.</param>
        public TupleCopier(IDeepCopier<T1> copier1, IDeepCopier<T2> copier2)
        {
            _copier1 = copier1;
            _copier2 = copier2;
        }

        public Tuple<T1, T2> DeepCopy(Tuple<T1, T2> input, CopyContext context)
        {
            if (context.TryGetCopy(input, out Tuple<T1, T2> result))
            {
                return result;
            }

            if (input.GetType() != typeof(Tuple<T1, T2>))
            {
                return context.Copy(input);
            }

            result = Tuple.Create(
                _copier1.DeepCopy(input.Item1, context),
                _copier2.DeepCopy(input.Item2, context));
            context.RecordCopy(input, result);
            return result;
        }
    }

    /// <summary>
    /// Serializer for <see cref="Tuple{T1, T2, T3}"/>.
    /// </summary>
    /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
    /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
    /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
    [RegisterSerializer]
    public class TupleCodec<T1, T2, T3> : IFieldCodec<Tuple<T1, T2, T3>>
    {
        private static readonly Type ElementType1 = typeof(T1);
        private static readonly Type ElementType2 = typeof(T2);
        private static readonly Type ElementType3 = typeof(T3);

        private readonly IFieldCodec<T1> _item1Codec;
        private readonly IFieldCodec<T2> _item2Codec;
        private readonly IFieldCodec<T3> _item3Codec;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCodec{T1, T2, T3}"/> class.
        /// </summary>
        /// <param name="item1Codec">The <typeparamref name="T1"/> codec.</param>
        /// <param name="item2Codec">The <typeparamref name="T2"/> codec.</param>
        /// <param name="item3Codec">The <typeparamref name="T3"/> codec.</param>
        public TupleCodec(
            IFieldCodec<T1> item1Codec,
            IFieldCodec<T2> item2Codec,
            IFieldCodec<T3> item3Codec)
        {
            _item1Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item1Codec);
            _item2Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item2Codec);
            _item3Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item3Codec);
        }

        /// <inheritdoc />
        void IFieldCodec<Tuple<T1, T2, T3>>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, Tuple<T1, T2, T3> value)
        {
            if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value))
            {
                return;
            }

            writer.WriteFieldHeader(fieldIdDelta, expectedType, value.GetType(), WireType.TagDelimited);

            _item1Codec.WriteField(ref writer, 1, ElementType1, value.Item1);
            _item2Codec.WriteField(ref writer, 1, ElementType2, value.Item2);
            _item3Codec.WriteField(ref writer, 1, ElementType3, value.Item3);

            writer.WriteEndObject();
        }

        /// <inheritdoc />
        Tuple<T1, T2, T3> IFieldCodec<Tuple<T1, T2, T3>>.ReadValue<TInput>(ref Reader<TInput> reader, Field field)
        {
            if (field.WireType == WireType.Reference)
            {
                return ReferenceCodec.ReadReference<Tuple<T1, T2, T3>, TInput>(ref reader, field);
            }

            if (field.WireType != WireType.TagDelimited)
            {
                ThrowUnsupportedWireTypeException();
            }

            var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session);
            var item1 = default(T1);
            var item2 = default(T2);
            var item3 = default(T3);
            uint fieldId = 0;
            while (true)
            {
                var header = reader.ReadFieldHeader();
                if (header.IsEndBaseOrEndObject)
                {
                    break;
                }

                fieldId += header.FieldIdDelta;
                switch (fieldId)
                {
                    case 1:
                        item1 = _item1Codec.ReadValue(ref reader, header);
                        break;
                    case 2:
                        item2 = _item2Codec.ReadValue(ref reader, header);
                        break;
                    case 3:
                        item3 = _item3Codec.ReadValue(ref reader, header);
                        break;
                    default:
                        reader.ConsumeUnknownField(header);
                        break;
                }
            }

            var result = new Tuple<T1, T2, T3>(item1, item2, item3);
            ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId);
            return result;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private static void ThrowUnsupportedWireTypeException() => throw new UnsupportedWireTypeException(
            $"Only a {nameof(WireType)} value of {WireType.TagDelimited} is supported for tuple fields.");
    }

    /// <summary>
    /// Copier for <see cref="Tuple{T1, T2, T3}"/>.
    /// </summary>
    /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
    /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
    /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
    [RegisterCopier]
    public class TupleCopier<T1, T2, T3> : IDeepCopier<Tuple<T1, T2, T3>>
    {
        private readonly IDeepCopier<T1> _copier1;
        private readonly IDeepCopier<T2> _copier2;
        private readonly IDeepCopier<T3> _copier3;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCopier{T1, T2, T3}"/> class.
        /// </summary>
        /// <param name="copier1">The <typeparamref name="T1"/> copier.</param>
        /// <param name="copier2">The <typeparamref name="T2"/> copier.</param>
        /// <param name="copier3">The <typeparamref name="T3"/> copier.</param>
        public TupleCopier(
            IDeepCopier<T1> copier1,
            IDeepCopier<T2> copier2,
            IDeepCopier<T3> copier3)
        {
            _copier1 = copier1;
            _copier2 = copier2;
            _copier3 = copier3;
        }

        /// <inheritdoc />
        public Tuple<T1, T2, T3> DeepCopy(Tuple<T1, T2, T3> input, CopyContext context)
        {
            if (context.TryGetCopy(input, out Tuple<T1, T2, T3> result))
            {
                return result;
            }

            if (input.GetType() != typeof(Tuple<T1, T2, T3>))
            {
                return context.Copy(input);
            }

            result = Tuple.Create(
                _copier1.DeepCopy(input.Item1, context),
                _copier2.DeepCopy(input.Item2, context),
                _copier3.DeepCopy(input.Item3, context));
            context.RecordCopy(input, result);
            return result;
        }
    }

    /// <summary>
    /// Serializer for <see cref="Tuple{T1, T2, T3, T4}"/>.
    /// </summary>
    /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
    /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
    /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
    /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
    [RegisterSerializer]
    public class TupleCodec<T1, T2, T3, T4> : IFieldCodec<Tuple<T1, T2, T3, T4>>
    {
        private static readonly Type ElementType1 = typeof(T1);
        private static readonly Type ElementType2 = typeof(T2);
        private static readonly Type ElementType3 = typeof(T3);
        private static readonly Type ElementType4 = typeof(T4);

        private readonly IFieldCodec<T1> _item1Codec;
        private readonly IFieldCodec<T2> _item2Codec;
        private readonly IFieldCodec<T3> _item3Codec;
        private readonly IFieldCodec<T4> _item4Codec;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCodec{T1, T2, T3, T4}"/> class.
        /// </summary>
        /// <param name="item1Codec">The <typeparamref name="T1"/> codec.</param>
        /// <param name="item2Codec">The <typeparamref name="T2"/> codec.</param>
        /// <param name="item3Codec">The <typeparamref name="T3"/> codec.</param>
        /// <param name="item4Codec">The <typeparamref name="T4"/> codec.</param>
        public TupleCodec(
            IFieldCodec<T1> item1Codec,
            IFieldCodec<T2> item2Codec,
            IFieldCodec<T3> item3Codec,
            IFieldCodec<T4> item4Codec)
        {
            _item1Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item1Codec);
            _item2Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item2Codec);
            _item3Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item3Codec);
            _item4Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item4Codec);
        }

        /// <inheritdoc />
        void IFieldCodec<Tuple<T1, T2, T3, T4>>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, Tuple<T1, T2, T3, T4> value)
        {
            if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value))
            {
                return;
            }

            writer.WriteFieldHeader(fieldIdDelta, expectedType, value.GetType(), WireType.TagDelimited);

            _item1Codec.WriteField(ref writer, 1, ElementType1, value.Item1);
            _item2Codec.WriteField(ref writer, 1, ElementType2, value.Item2);
            _item3Codec.WriteField(ref writer, 1, ElementType3, value.Item3);
            _item4Codec.WriteField(ref writer, 1, ElementType4, value.Item4);

            writer.WriteEndObject();
        }

        /// <inheritdoc />
        Tuple<T1, T2, T3, T4> IFieldCodec<Tuple<T1, T2, T3, T4>>.ReadValue<TInput>(ref Reader<TInput> reader, Field field)
        {
            if (field.WireType == WireType.Reference)
            {
                return ReferenceCodec.ReadReference<Tuple<T1, T2, T3, T4>, TInput>(ref reader, field);
            }

            if (field.WireType != WireType.TagDelimited)
            {
                ThrowUnsupportedWireTypeException();
            }

            var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session);
            var item1 = default(T1);
            var item2 = default(T2);
            var item3 = default(T3);
            var item4 = default(T4);
            uint fieldId = 0;
            while (true)
            {
                var header = reader.ReadFieldHeader();
                if (header.IsEndBaseOrEndObject)
                {
                    break;
                }

                fieldId += header.FieldIdDelta;
                switch (fieldId)
                {
                    case 1:
                        item1 = _item1Codec.ReadValue(ref reader, header);
                        break;
                    case 2:
                        item2 = _item2Codec.ReadValue(ref reader, header);
                        break;
                    case 3:
                        item3 = _item3Codec.ReadValue(ref reader, header);
                        break;
                    case 4:
                        item4 = _item4Codec.ReadValue(ref reader, header);
                        break;
                    default:
                        reader.ConsumeUnknownField(header);
                        break;
                }
            }

            var result = new Tuple<T1, T2, T3, T4>(item1, item2, item3, item4);
            ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId);
            return result;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private static void ThrowUnsupportedWireTypeException() => throw new UnsupportedWireTypeException(
            $"Only a {nameof(WireType)} value of {WireType.TagDelimited} is supported for tuple fields.");
    }

    /// <summary>
    /// Copier for <see cref="Tuple{T1, T2, T3, T4}"/>.
    /// </summary>
    /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
    /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
    /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
    /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
    [RegisterCopier]
    public class TupleCopier<T1, T2, T3, T4> : IDeepCopier<Tuple<T1, T2, T3, T4>>
    {
        private readonly IDeepCopier<T1> _copier1;
        private readonly IDeepCopier<T2> _copier2;
        private readonly IDeepCopier<T3> _copier3;
        private readonly IDeepCopier<T4> _copier4;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCopier{T1, T2, T3, T4}"/> class.
        /// </summary>
        /// <param name="copier1">The <typeparamref name="T1"/> copier.</param>
        /// <param name="copier2">The <typeparamref name="T2"/> copier.</param>
        /// <param name="copier3">The <typeparamref name="T3"/> copier.</param>
        /// <param name="copier4">The <typeparamref name="T4"/> copier.</param>
        public TupleCopier(
            IDeepCopier<T1> copier1,
            IDeepCopier<T2> copier2,
            IDeepCopier<T3> copier3,
            IDeepCopier<T4> copier4)
        {
            _copier1 = copier1;
            _copier2 = copier2;
            _copier3 = copier3;
            _copier4 = copier4;
        }

        /// <inheritdoc />
        public Tuple<T1, T2, T3, T4> DeepCopy(Tuple<T1, T2, T3, T4> input, CopyContext context)
        {
            if (context.TryGetCopy(input, out Tuple<T1, T2, T3, T4> result))
            {
                return result;
            }

            if (input.GetType() != typeof(Tuple<T1, T2, T3, T4>))
            {
                return context.Copy(input);
            }

            result = Tuple.Create(
                _copier1.DeepCopy(input.Item1, context),
                _copier2.DeepCopy(input.Item2, context),
                _copier3.DeepCopy(input.Item3, context),
                _copier4.DeepCopy(input.Item4, context));
            context.RecordCopy(input, result);
            return result;
        }
    }

    /// <summary>
    /// Serializer for <see cref="Tuple{T1, T2, T3, T4, T5}"/>.
    /// </summary>
    /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
    /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
    /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
    /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
    /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
    [RegisterSerializer]
    public class TupleCodec<T1, T2, T3, T4, T5> : IFieldCodec<Tuple<T1, T2, T3, T4, T5>>
    {
        private static readonly Type ElementType1 = typeof(T1);
        private static readonly Type ElementType2 = typeof(T2);
        private static readonly Type ElementType3 = typeof(T3);
        private static readonly Type ElementType4 = typeof(T4);
        private static readonly Type ElementType5 = typeof(T5);

        private readonly IFieldCodec<T1> _item1Codec;
        private readonly IFieldCodec<T2> _item2Codec;
        private readonly IFieldCodec<T3> _item3Codec;
        private readonly IFieldCodec<T4> _item4Codec;
        private readonly IFieldCodec<T5> _item5Codec;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCodec{T1, T2, T3, T4, T5}"/> class.
        /// </summary>
        /// <param name="item1Codec">The <typeparamref name="T1"/> codec.</param>
        /// <param name="item2Codec">The <typeparamref name="T2"/> codec.</param>
        /// <param name="item3Codec">The <typeparamref name="T3"/> codec.</param>
        /// <param name="item4Codec">The <typeparamref name="T4"/> codec.</param>
        /// <param name="item5Codec">The <typeparamref name="T5"/> codec.</param>
        public TupleCodec(
            IFieldCodec<T1> item1Codec,
            IFieldCodec<T2> item2Codec,
            IFieldCodec<T3> item3Codec,
            IFieldCodec<T4> item4Codec,
            IFieldCodec<T5> item5Codec)
        {
            _item1Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item1Codec);
            _item2Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item2Codec);
            _item3Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item3Codec);
            _item4Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item4Codec);
            _item5Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item5Codec);
        }

        /// <inheritdoc />
        void IFieldCodec<Tuple<T1, T2, T3, T4, T5>>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer,
            uint fieldIdDelta,
            Type expectedType,
            Tuple<T1, T2, T3, T4, T5> value)
        {
            if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value))
            {
                return;
            }

            writer.WriteFieldHeader(fieldIdDelta, expectedType, value.GetType(), WireType.TagDelimited);

            _item1Codec.WriteField(ref writer, 1, ElementType1, value.Item1);
            _item2Codec.WriteField(ref writer, 1, ElementType2, value.Item2);
            _item3Codec.WriteField(ref writer, 1, ElementType3, value.Item3);
            _item4Codec.WriteField(ref writer, 1, ElementType4, value.Item4);
            _item5Codec.WriteField(ref writer, 1, ElementType5, value.Item5);

            writer.WriteEndObject();
        }

        /// <inheritdoc />
        Tuple<T1, T2, T3, T4, T5> IFieldCodec<Tuple<T1, T2, T3, T4, T5>>.ReadValue<TInput>(ref Reader<TInput> reader, Field field)
        {
            if (field.WireType == WireType.Reference)
            {
                return ReferenceCodec.ReadReference<Tuple<T1, T2, T3, T4, T5>, TInput>(ref reader, field);
            }

            if (field.WireType != WireType.TagDelimited)
            {
                ThrowUnsupportedWireTypeException();
            }

            var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session);
            var item1 = default(T1);
            var item2 = default(T2);
            var item3 = default(T3);
            var item4 = default(T4);
            var item5 = default(T5);
            uint fieldId = 0;
            while (true)
            {
                var header = reader.ReadFieldHeader();
                if (header.IsEndBaseOrEndObject)
                {
                    break;
                }

                fieldId += header.FieldIdDelta;
                switch (fieldId)
                {
                    case 1:
                        item1 = _item1Codec.ReadValue(ref reader, header);
                        break;
                    case 2:
                        item2 = _item2Codec.ReadValue(ref reader, header);
                        break;
                    case 3:
                        item3 = _item3Codec.ReadValue(ref reader, header);
                        break;
                    case 4:
                        item4 = _item4Codec.ReadValue(ref reader, header);
                        break;
                    case 5:
                        item5 = _item5Codec.ReadValue(ref reader, header);
                        break;
                    default:
                        reader.ConsumeUnknownField(header);
                        break;
                }
            }

            var result = new Tuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5);
            ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId);
            return result;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private static void ThrowUnsupportedWireTypeException() => throw new UnsupportedWireTypeException(
            $"Only a {nameof(WireType)} value of {WireType.TagDelimited} is supported for tuple fields.");
    }

    /// <summary>
    /// Copier for <see cref="Tuple{T1, T2, T3, T4, T5}"/>.
    /// </summary>
    /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
    /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
    /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
    /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
    /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
    [RegisterCopier]
    public class TupleCopier<T1, T2, T3, T4, T5> : IDeepCopier<Tuple<T1, T2, T3, T4, T5>>
    {
        private readonly IDeepCopier<T1> _copier1;
        private readonly IDeepCopier<T2> _copier2;
        private readonly IDeepCopier<T3> _copier3;
        private readonly IDeepCopier<T4> _copier4;
        private readonly IDeepCopier<T5> _copier5;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCopier{T1, T2, T3, T4, T5}"/> class.
        /// </summary>
        /// <param name="copier1">The <typeparamref name="T1"/> copier.</param>
        /// <param name="copier2">The <typeparamref name="T2"/> copier.</param>
        /// <param name="copier3">The <typeparamref name="T3"/> copier.</param>
        /// <param name="copier4">The <typeparamref name="T4"/> copier.</param>
        /// <param name="copier5">The <typeparamref name="T5"/> copier.</param>
        public TupleCopier(
            IDeepCopier<T1> copier1,
            IDeepCopier<T2> copier2,
            IDeepCopier<T3> copier3,
            IDeepCopier<T4> copier4,
            IDeepCopier<T5> copier5)
        {
            _copier1 = copier1;
            _copier2 = copier2;
            _copier3 = copier3;
            _copier4 = copier4;
            _copier5 = copier5;
        }

        /// <inheritdoc />
        public Tuple<T1, T2, T3, T4, T5> DeepCopy(Tuple<T1, T2, T3, T4, T5> input, CopyContext context)
        {
            if (context.TryGetCopy(input, out Tuple<T1, T2, T3, T4, T5> result))
            {
                return result;
            }

            if (input.GetType() != typeof(Tuple<T1, T2, T3, T4, T5>))
            {
                return context.Copy(input);
            }

            result = Tuple.Create(
                _copier1.DeepCopy(input.Item1, context),
                _copier2.DeepCopy(input.Item2, context),
                _copier3.DeepCopy(input.Item3, context),
                _copier4.DeepCopy(input.Item4, context),
                _copier5.DeepCopy(input.Item5, context));
            context.RecordCopy(input, result);
            return result;
        }
    }

    /// <summary>
    /// Serializer for <see cref="Tuple{T1, T2, T3, T4, T5, T6}"/>.
    /// </summary>
    /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
    /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
    /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
    /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
    /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
    /// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
    [RegisterSerializer]
    public class TupleCodec<T1, T2, T3, T4, T5, T6> : IFieldCodec<Tuple<T1, T2, T3, T4, T5, T6>>
    {
        private static readonly Type ElementType1 = typeof(T1);
        private static readonly Type ElementType2 = typeof(T2);
        private static readonly Type ElementType3 = typeof(T3);
        private static readonly Type ElementType4 = typeof(T4);
        private static readonly Type ElementType5 = typeof(T5);
        private static readonly Type ElementType6 = typeof(T6);

        private readonly IFieldCodec<T1> _item1Codec;
        private readonly IFieldCodec<T2> _item2Codec;
        private readonly IFieldCodec<T3> _item3Codec;
        private readonly IFieldCodec<T4> _item4Codec;
        private readonly IFieldCodec<T5> _item5Codec;
        private readonly IFieldCodec<T6> _item6Codec;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCodec{T1, T2, T3, T4, T5, T6}"/> class.
        /// </summary>
        /// <param name="item1Codec">The <typeparamref name="T1"/> codec.</param>
        /// <param name="item2Codec">The <typeparamref name="T2"/> codec.</param>
        /// <param name="item3Codec">The <typeparamref name="T3"/> codec.</param>
        /// <param name="item4Codec">The <typeparamref name="T4"/> codec.</param>
        /// <param name="item5Codec">The <typeparamref name="T5"/> codec.</param>
        /// <param name="item6Codec">The <typeparamref name="T6"/> codec.</param>
        public TupleCodec(
            IFieldCodec<T1> item1Codec,
            IFieldCodec<T2> item2Codec,
            IFieldCodec<T3> item3Codec,
            IFieldCodec<T4> item4Codec,
            IFieldCodec<T5> item5Codec,
            IFieldCodec<T6> item6Codec)
        {
            _item1Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item1Codec);
            _item2Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item2Codec);
            _item3Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item3Codec);
            _item4Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item4Codec);
            _item5Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item5Codec);
            _item6Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item6Codec);
        }

        /// <inheritdoc />
        void IFieldCodec<Tuple<T1, T2, T3, T4, T5, T6>>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer,
            uint fieldIdDelta,
            Type expectedType,
            Tuple<T1, T2, T3, T4, T5, T6> value)
        {
            if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value))
            {
                return;
            }

            writer.WriteFieldHeader(fieldIdDelta, expectedType, value.GetType(), WireType.TagDelimited);

            _item1Codec.WriteField(ref writer, 1, ElementType1, value.Item1);
            _item2Codec.WriteField(ref writer, 1, ElementType2, value.Item2);
            _item3Codec.WriteField(ref writer, 1, ElementType3, value.Item3);
            _item4Codec.WriteField(ref writer, 1, ElementType4, value.Item4);
            _item5Codec.WriteField(ref writer, 1, ElementType5, value.Item5);
            _item6Codec.WriteField(ref writer, 1, ElementType6, value.Item6);

            writer.WriteEndObject();
        }

        /// <inheritdoc />
        Tuple<T1, T2, T3, T4, T5, T6> IFieldCodec<Tuple<T1, T2, T3, T4, T5, T6>>.ReadValue<TInput>(ref Reader<TInput> reader, Field field)
        {
            if (field.WireType == WireType.Reference)
            {
                return ReferenceCodec.ReadReference<Tuple<T1, T2, T3, T4, T5, T6>, TInput>(ref reader, field);
            }

            if (field.WireType != WireType.TagDelimited)
            {
                ThrowUnsupportedWireTypeException();
            }

            var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session);
            var item1 = default(T1);
            var item2 = default(T2);
            var item3 = default(T3);
            var item4 = default(T4);
            var item5 = default(T5);
            var item6 = default(T6);
            uint fieldId = 0;
            while (true)
            {
                var header = reader.ReadFieldHeader();
                if (header.IsEndBaseOrEndObject)
                {
                    break;
                }

                fieldId += header.FieldIdDelta;
                switch (fieldId)
                {
                    case 1:
                        item1 = _item1Codec.ReadValue(ref reader, header);
                        break;
                    case 2:
                        item2 = _item2Codec.ReadValue(ref reader, header);
                        break;
                    case 3:
                        item3 = _item3Codec.ReadValue(ref reader, header);
                        break;
                    case 4:
                        item4 = _item4Codec.ReadValue(ref reader, header);
                        break;
                    case 5:
                        item5 = _item5Codec.ReadValue(ref reader, header);
                        break;
                    case 6:
                        item6 = _item6Codec.ReadValue(ref reader, header);
                        break;
                    default:
                        reader.ConsumeUnknownField(header);
                        break;
                }
            }

            var result = new Tuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6);
            ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId);
            return result;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private static void ThrowUnsupportedWireTypeException() => throw new UnsupportedWireTypeException(
            $"Only a {nameof(WireType)} value of {WireType.TagDelimited} is supported for tuple fields.");
    }

    /// <summary>
    /// Copier for <see cref="Tuple{T1, T2, T3, T4, T5, T6}"/>.
    /// </summary>
    /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
    /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
    /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
    /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
    /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
    /// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
    [RegisterCopier]
    public class TupleCopier<T1, T2, T3, T4, T5, T6> : IDeepCopier<Tuple<T1, T2, T3, T4, T5, T6>>
    {
        private readonly IDeepCopier<T1> _copier1;
        private readonly IDeepCopier<T2> _copier2;
        private readonly IDeepCopier<T3> _copier3;
        private readonly IDeepCopier<T4> _copier4;
        private readonly IDeepCopier<T5> _copier5;
        private readonly IDeepCopier<T6> _copier6;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCopier{T1, T2, T3, T4, T5, T6}"/> class.
        /// </summary>
        /// <param name="copier1">The <typeparamref name="T1"/> copier.</param>
        /// <param name="copier2">The <typeparamref name="T2"/> copier.</param>
        /// <param name="copier3">The <typeparamref name="T3"/> copier.</param>
        /// <param name="copier4">The <typeparamref name="T4"/> copier.</param>
        /// <param name="copier5">The <typeparamref name="T5"/> copier.</param>
        /// <param name="copier6">The <typeparamref name="T6"/> copier.</param>
        public TupleCopier(
            IDeepCopier<T1> copier1,
            IDeepCopier<T2> copier2,
            IDeepCopier<T3> copier3,
            IDeepCopier<T4> copier4,
            IDeepCopier<T5> copier5,
            IDeepCopier<T6> copier6)
        {
            _copier1 = copier1;
            _copier2 = copier2;
            _copier3 = copier3;
            _copier4 = copier4;
            _copier5 = copier5;
            _copier6 = copier6;
        }

        /// <inheritdoc />
        public Tuple<T1, T2, T3, T4, T5, T6> DeepCopy(Tuple<T1, T2, T3, T4, T5, T6> input, CopyContext context)
        {
            if (context.TryGetCopy(input, out Tuple<T1, T2, T3, T4, T5, T6> result))
            {
                return result;
            }

            if (input.GetType() != typeof(Tuple<T1, T2, T3, T4, T5, T6>))
            {
                return context.Copy(input);
            }

            result = Tuple.Create(
                _copier1.DeepCopy(input.Item1, context),
                _copier2.DeepCopy(input.Item2, context),
                _copier3.DeepCopy(input.Item3, context),
                _copier4.DeepCopy(input.Item4, context),
                _copier5.DeepCopy(input.Item5, context),
                _copier6.DeepCopy(input.Item6, context));
            context.RecordCopy(input, result);
            return result;
        }
    }

    /// <summary>
    /// Serializer for <see cref="Tuple{T1, T2, T3, T4, T5, T6, T7}"/>.
    /// </summary>
    /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
    /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
    /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
    /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
    /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
    /// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
    /// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
    [RegisterSerializer]
    public class TupleCodec<T1, T2, T3, T4, T5, T6, T7> : IFieldCodec<Tuple<T1, T2, T3, T4, T5, T6, T7>>
    {
        private static readonly Type ElementType1 = typeof(T1);
        private static readonly Type ElementType2 = typeof(T2);
        private static readonly Type ElementType3 = typeof(T3);
        private static readonly Type ElementType4 = typeof(T4);
        private static readonly Type ElementType5 = typeof(T5);
        private static readonly Type ElementType6 = typeof(T6);
        private static readonly Type ElementType7 = typeof(T7);

        private readonly IFieldCodec<T1> _item1Codec;
        private readonly IFieldCodec<T2> _item2Codec;
        private readonly IFieldCodec<T3> _item3Codec;
        private readonly IFieldCodec<T4> _item4Codec;
        private readonly IFieldCodec<T5> _item5Codec;
        private readonly IFieldCodec<T6> _item6Codec;
        private readonly IFieldCodec<T7> _item7Codec;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCodec{T1, T2, T3, T4, T5, T6, T7}"/> class.
        /// </summary>
        /// <param name="item1Codec">The <typeparamref name="T1"/> codec.</param>
        /// <param name="item2Codec">The <typeparamref name="T2"/> codec.</param>
        /// <param name="item3Codec">The <typeparamref name="T3"/> codec.</param>
        /// <param name="item4Codec">The <typeparamref name="T4"/> codec.</param>
        /// <param name="item5Codec">The <typeparamref name="T5"/> codec.</param>
        /// <param name="item6Codec">The <typeparamref name="T6"/> codec.</param>
        /// <param name="item7Codec">The <typeparamref name="T7"/> codec.</param>
        public TupleCodec(
            IFieldCodec<T1> item1Codec,
            IFieldCodec<T2> item2Codec,
            IFieldCodec<T3> item3Codec,
            IFieldCodec<T4> item4Codec,
            IFieldCodec<T5> item5Codec,
            IFieldCodec<T6> item6Codec,
            IFieldCodec<T7> item7Codec)
        {
            _item1Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item1Codec);
            _item2Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item2Codec);
            _item3Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item3Codec);
            _item4Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item4Codec);
            _item5Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item5Codec);
            _item6Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item6Codec);
            _item7Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item7Codec);
        }

        /// <inheritdoc />
        void IFieldCodec<Tuple<T1, T2, T3, T4, T5, T6, T7>>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer,
            uint fieldIdDelta,
            Type expectedType,
            Tuple<T1, T2, T3, T4, T5, T6, T7> value)
        {
            if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value))
            {
                return;
            }

            writer.WriteFieldHeader(fieldIdDelta, expectedType, value.GetType(), WireType.TagDelimited);

            _item1Codec.WriteField(ref writer, 1, ElementType1, value.Item1);
            _item2Codec.WriteField(ref writer, 1, ElementType2, value.Item2);
            _item3Codec.WriteField(ref writer, 1, ElementType3, value.Item3);
            _item4Codec.WriteField(ref writer, 1, ElementType4, value.Item4);
            _item5Codec.WriteField(ref writer, 1, ElementType5, value.Item5);
            _item6Codec.WriteField(ref writer, 1, ElementType6, value.Item6);
            _item7Codec.WriteField(ref writer, 1, ElementType7, value.Item7);

            writer.WriteEndObject();
        }

        /// <inheritdoc />
        Tuple<T1, T2, T3, T4, T5, T6, T7> IFieldCodec<Tuple<T1, T2, T3, T4, T5, T6, T7>>.ReadValue<TInput>(ref Reader<TInput> reader, Field field)
        {
            if (field.WireType == WireType.Reference)
            {
                return ReferenceCodec.ReadReference<Tuple<T1, T2, T3, T4, T5, T6, T7>, TInput>(ref reader, field);
            }

            if (field.WireType != WireType.TagDelimited)
            {
                ThrowUnsupportedWireTypeException();
            }

            var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session);
            var item1 = default(T1);
            var item2 = default(T2);
            var item3 = default(T3);
            var item4 = default(T4);
            var item5 = default(T5);
            var item6 = default(T6);
            var item7 = default(T7);
            uint fieldId = 0;
            while (true)
            {
                var header = reader.ReadFieldHeader();
                if (header.IsEndBaseOrEndObject)
                {
                    break;
                }

                fieldId += header.FieldIdDelta;
                switch (fieldId)
                {
                    case 1:
                        item1 = _item1Codec.ReadValue(ref reader, header);
                        break;
                    case 2:
                        item2 = _item2Codec.ReadValue(ref reader, header);
                        break;
                    case 3:
                        item3 = _item3Codec.ReadValue(ref reader, header);
                        break;
                    case 4:
                        item4 = _item4Codec.ReadValue(ref reader, header);
                        break;
                    case 5:
                        item5 = _item5Codec.ReadValue(ref reader, header);
                        break;
                    case 6:
                        item6 = _item6Codec.ReadValue(ref reader, header);
                        break;
                    case 7:
                        item7 = _item7Codec.ReadValue(ref reader, header);
                        break;
                    default:
                        reader.ConsumeUnknownField(header);
                        break;
                }
            }

            var result = new Tuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7);
            ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId);
            return result;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private static void ThrowUnsupportedWireTypeException() => throw new UnsupportedWireTypeException(
            $"Only a {nameof(WireType)} value of {WireType.TagDelimited} is supported for tuple fields.");
    }

    /// <summary>
    /// Copier for <see cref="Tuple{T1, T2, T3, T4, T5, T6, T7}"/>.
    /// </summary>
    /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
    /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
    /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
    /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
    /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
    /// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
    /// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
    [RegisterCopier]
    public class TupleCopier<T1, T2, T3, T4, T5, T6, T7> : IDeepCopier<Tuple<T1, T2, T3, T4, T5, T6, T7>>
    {
        private readonly IDeepCopier<T1> _copier1;
        private readonly IDeepCopier<T2> _copier2;
        private readonly IDeepCopier<T3> _copier3;
        private readonly IDeepCopier<T4> _copier4;
        private readonly IDeepCopier<T5> _copier5;
        private readonly IDeepCopier<T6> _copier6;
        private readonly IDeepCopier<T7> _copier7;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCopier{T1, T2, T3, T4, T5, T6, T7}"/> class.
        /// </summary>
        /// <param name="copier1">The <typeparamref name="T1"/> copier.</param>
        /// <param name="copier2">The <typeparamref name="T2"/> copier.</param>
        /// <param name="copier3">The <typeparamref name="T3"/> copier.</param>
        /// <param name="copier4">The <typeparamref name="T4"/> copier.</param>
        /// <param name="copier5">The <typeparamref name="T5"/> copier.</param>
        /// <param name="copier6">The <typeparamref name="T6"/> copier.</param>
        /// <param name="copier7">The <typeparamref name="T7"/> copier.</param>
        public TupleCopier(
            IDeepCopier<T1> copier1,
            IDeepCopier<T2> copier2,
            IDeepCopier<T3> copier3,
            IDeepCopier<T4> copier4,
            IDeepCopier<T5> copier5,
            IDeepCopier<T6> copier6,
            IDeepCopier<T7> copier7)
        {
            _copier1 = copier1;
            _copier2 = copier2;
            _copier3 = copier3;
            _copier4 = copier4;
            _copier5 = copier5;
            _copier6 = copier6;
            _copier7 = copier7;
        }

        /// <inheritdoc />
        public Tuple<T1, T2, T3, T4, T5, T6, T7> DeepCopy(Tuple<T1, T2, T3, T4, T5, T6, T7> input, CopyContext context)
        {
            if (context.TryGetCopy(input, out Tuple<T1, T2, T3, T4, T5, T6, T7> result))
            {
                return result;
            }

            if (input.GetType() != typeof(Tuple<T1, T2, T3, T4, T5, T6, T7>))
            {
                return context.Copy(input);
            }

            result = Tuple.Create(
                _copier1.DeepCopy(input.Item1, context),
                _copier2.DeepCopy(input.Item2, context),
                _copier3.DeepCopy(input.Item3, context),
                _copier4.DeepCopy(input.Item4, context),
                _copier5.DeepCopy(input.Item5, context),
                _copier6.DeepCopy(input.Item6, context),
                _copier7.DeepCopy(input.Item7, context));
            context.RecordCopy(input, result);
            return result;
        }
    }

    /// <summary>
    /// Serializer for <see cref="Tuple{T1, T2, T3, T4, T5, T6, T7, T8}"/>.
    /// </summary>
    /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
    /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
    /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
    /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
    /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
    /// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
    /// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
    /// <typeparam name="T8">The type of the tuple's eighth component.</typeparam>
    [RegisterSerializer]
    public class TupleCodec<T1, T2, T3, T4, T5, T6, T7, T8> : IFieldCodec<Tuple<T1, T2, T3, T4, T5, T6, T7, T8>>
    {
        private static readonly Type ElementType1 = typeof(T1);
        private static readonly Type ElementType2 = typeof(T2);
        private static readonly Type ElementType3 = typeof(T3);
        private static readonly Type ElementType4 = typeof(T4);
        private static readonly Type ElementType5 = typeof(T5);
        private static readonly Type ElementType6 = typeof(T6);
        private static readonly Type ElementType7 = typeof(T7);
        private static readonly Type ElementType8 = typeof(T8);

        private readonly IFieldCodec<T1> _item1Codec;
        private readonly IFieldCodec<T2> _item2Codec;
        private readonly IFieldCodec<T3> _item3Codec;
        private readonly IFieldCodec<T4> _item4Codec;
        private readonly IFieldCodec<T5> _item5Codec;
        private readonly IFieldCodec<T6> _item6Codec;
        private readonly IFieldCodec<T7> _item7Codec;
        private readonly IFieldCodec<T8> _item8Codec;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCodec{T1, T2, T3, T4, T5, T6, T7, T8}"/> class.
        /// </summary>
        /// <param name="item1Codec">The <typeparamref name="T1"/> codec.</param>
        /// <param name="item2Codec">The <typeparamref name="T2"/> codec.</param>
        /// <param name="item3Codec">The <typeparamref name="T3"/> codec.</param>
        /// <param name="item4Codec">The <typeparamref name="T4"/> codec.</param>
        /// <param name="item5Codec">The <typeparamref name="T5"/> codec.</param>
        /// <param name="item6Codec">The <typeparamref name="T6"/> codec.</param>
        /// <param name="item7Codec">The <typeparamref name="T7"/> codec.</param>
        /// <param name="item8Codec">The <typeparamref name="T8"/> codec.</param>
        public TupleCodec(
            IFieldCodec<T1> item1Codec,
            IFieldCodec<T2> item2Codec,
            IFieldCodec<T3> item3Codec,
            IFieldCodec<T4> item4Codec,
            IFieldCodec<T5> item5Codec,
            IFieldCodec<T6> item6Codec,
            IFieldCodec<T7> item7Codec,
            IFieldCodec<T8> item8Codec)
        {
            _item1Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item1Codec);
            _item2Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item2Codec);
            _item3Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item3Codec);
            _item4Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item4Codec);
            _item5Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item5Codec);
            _item6Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item6Codec);
            _item7Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item7Codec);
            _item8Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item8Codec);
        }

        /// <inheritdoc />
        void IFieldCodec<Tuple<T1, T2, T3, T4, T5, T6, T7, T8>>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer,
            uint fieldIdDelta,
            Type expectedType,
            Tuple<T1, T2, T3, T4, T5, T6, T7, T8> value)
        {
            if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value))
            {
                return;
            }

            writer.WriteFieldHeader(fieldIdDelta, expectedType, value.GetType(), WireType.TagDelimited);

            _item1Codec.WriteField(ref writer, 1, ElementType1, value.Item1);
            _item2Codec.WriteField(ref writer, 1, ElementType2, value.Item2);
            _item3Codec.WriteField(ref writer, 1, ElementType3, value.Item3);
            _item4Codec.WriteField(ref writer, 1, ElementType4, value.Item4);
            _item5Codec.WriteField(ref writer, 1, ElementType5, value.Item5);
            _item6Codec.WriteField(ref writer, 1, ElementType6, value.Item6);
            _item7Codec.WriteField(ref writer, 1, ElementType7, value.Item7);
            _item8Codec.WriteField(ref writer, 1, ElementType8, value.Rest);

            writer.WriteEndObject();
        }

        /// <inheritdoc />
        Tuple<T1, T2, T3, T4, T5, T6, T7, T8> IFieldCodec<Tuple<T1, T2, T3, T4, T5, T6, T7, T8>>.ReadValue<TInput>(ref Reader<TInput> reader, Field field)
        {
            if (field.WireType == WireType.Reference)
            {
                return ReferenceCodec.ReadReference<Tuple<T1, T2, T3, T4, T5, T6, T7, T8>, TInput>(ref reader, field);
            }

            if (field.WireType != WireType.TagDelimited)
            {
                ThrowUnsupportedWireTypeException();
            }

            var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session);
            var item1 = default(T1);
            var item2 = default(T2);
            var item3 = default(T3);
            var item4 = default(T4);
            var item5 = default(T5);
            var item6 = default(T6);
            var item7 = default(T7);
            var item8 = default(T8);
            uint fieldId = 0;
            while (true)
            {
                var header = reader.ReadFieldHeader();
                if (header.IsEndBaseOrEndObject)
                {
                    break;
                }

                fieldId += header.FieldIdDelta;
                switch (fieldId)
                {
                    case 1:
                        item1 = _item1Codec.ReadValue(ref reader, header);
                        break;
                    case 2:
                        item2 = _item2Codec.ReadValue(ref reader, header);
                        break;
                    case 3:
                        item3 = _item3Codec.ReadValue(ref reader, header);
                        break;
                    case 4:
                        item4 = _item4Codec.ReadValue(ref reader, header);
                        break;
                    case 5:
                        item5 = _item5Codec.ReadValue(ref reader, header);
                        break;
                    case 6:
                        item6 = _item6Codec.ReadValue(ref reader, header);
                        break;
                    case 7:
                        item7 = _item7Codec.ReadValue(ref reader, header);
                        break;
                    case 8:
                        item8 = _item8Codec.ReadValue(ref reader, header);
                        break;
                    default:
                        reader.ConsumeUnknownField(header);
                        break;
                }
            }

            var result = new Tuple<T1, T2, T3, T4, T5, T6, T7, T8>(item1, item2, item3, item4, item5, item6, item7, item8);
            ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId);
            return result;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private static void ThrowUnsupportedWireTypeException() => throw new UnsupportedWireTypeException(
            $"Only a {nameof(WireType)} value of {WireType.TagDelimited} is supported for tuple fields.");
    }

    /// <summary>
    /// Copier for <see cref="Tuple{T1, T2, T3, T4, T5, T6, T7, T8}"/>.
    /// </summary>
    /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
    /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
    /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
    /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
    /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
    /// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
    /// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
    /// <typeparam name="T8">The type of the tuple's eighth component.</typeparam>
    [RegisterCopier]
    public class TupleCopier<T1, T2, T3, T4, T5, T6, T7, T8> : IDeepCopier<Tuple<T1, T2, T3, T4, T5, T6, T7, T8>>
    {
        private readonly IDeepCopier<T1> _copier1;
        private readonly IDeepCopier<T2> _copier2;
        private readonly IDeepCopier<T3> _copier3;
        private readonly IDeepCopier<T4> _copier4;
        private readonly IDeepCopier<T5> _copier5;
        private readonly IDeepCopier<T6> _copier6;
        private readonly IDeepCopier<T7> _copier7;
        private readonly IDeepCopier<T8> _copier8;

        /// <summary>
        /// Initializes a new instance of the <see cref="TupleCopier{T1, T2, T3, T4, T5, T6, T7, T8}"/> class.
        /// </summary>
        /// <param name="copier1">The <typeparamref name="T1"/> copier.</param>
        /// <param name="copier2">The <typeparamref name="T2"/> copier.</param>
        /// <param name="copier3">The <typeparamref name="T3"/> copier.</param>
        /// <param name="copier4">The <typeparamref name="T4"/> copier.</param>
        /// <param name="copier5">The <typeparamref name="T5"/> copier.</param>
        /// <param name="copier6">The <typeparamref name="T6"/> copier.</param>
        /// <param name="copier7">The <typeparamref name="T7"/> copier.</param>
        /// <param name="copier8">The <typeparamref name="T8"/> copier.</param>
        public TupleCopier(
            IDeepCopier<T1> copier1,
            IDeepCopier<T2> copier2,
            IDeepCopier<T3> copier3,
            IDeepCopier<T4> copier4,
            IDeepCopier<T5> copier5,
            IDeepCopier<T6> copier6,
            IDeepCopier<T7> copier7,
            IDeepCopier<T8> copier8)
        {
            _copier1 = copier1;
            _copier2 = copier2;
            _copier3 = copier3;
            _copier4 = copier4;
            _copier5 = copier5;
            _copier6 = copier6;
            _copier7 = copier7;
            _copier8 = copier8;
        }

        /// <inheritdoc />
        public Tuple<T1, T2, T3, T4, T5, T6, T7, T8> DeepCopy(Tuple<T1, T2, T3, T4, T5, T6, T7, T8> input, CopyContext context)
        {
            if (context.TryGetCopy(input, out Tuple<T1, T2, T3, T4, T5, T6, T7, T8> result))
            {
                return result;
            }

            if (input.GetType() != typeof(Tuple<T1, T2, T3, T4, T5, T6, T7, T8>))
            {
                return context.Copy(input);
            }

            result = new Tuple<T1, T2, T3, T4, T5, T6, T7, T8>(
                _copier1.DeepCopy(input.Item1, context),
                _copier2.DeepCopy(input.Item2, context),
                _copier3.DeepCopy(input.Item3, context),
                _copier4.DeepCopy(input.Item4, context),
                _copier5.DeepCopy(input.Item5, context),
                _copier6.DeepCopy(input.Item6, context),
                _copier7.DeepCopy(input.Item7, context),
                _copier8.DeepCopy(input.Rest, context));
            context.RecordCopy(input, result);
            return result;
        }
    }
}


text:
#include "jam.h"

#include "xi/xi_mem.h"
#include "xi/xi_string.h"
#include "xi/xi_file.h"
#include "xi/xi_process.h"

#include <stdio.h>

static int VM_initing = TRUE;
extern void initialisePlatform();

static int xfprintf(int fd, const char *fmt, va_list ap) {
	xchar msg[1024];
	int mlen = 0;

	xi_mem_set(msg, 0, sizeof(msg));
	vsnprintf(msg, sizeof(msg), fmt, ap);
	mlen = xi_strlen(msg);
	xi_file_write(fd, msg, mlen);

	return mlen;
}

/* Setup default values for command line args */

void setDefaultInitArgs(InitArgs *args) {
	xi_mem_set(args, 0, sizeof(InitArgs));

	args->asyncgc = FALSE;

	args->verbosegc = FALSE;
	args->verbosedll = FALSE;
	args->verboseclass = FALSE;

	args->compact_specified = FALSE;

	args->classpath = NULL;
	args->bootpath = NULL;

	args->java_stack = DEFAULT_STACK;
	args->min_heap = DEFAULT_MIN_HEAP;
	args->max_heap = DEFAULT_MAX_HEAP;

	args->props_count = 0;

	args->vfprintf = xfprintf;
	args->abort = xi_proc_abort;
	args->exit = xi_proc_exit;
}

int VMInitialising() {
	return VM_initing;
}

void initVM(InitArgs *args) {
	xint32 verbose = args->verboseclass | args->verbosedll | args->verbosegc;
	/* Perform platform dependent initialisation */
	//initialisePlatform();

	/* Initialise the VM modules -- ordering is important! */
	if (verbose) log_trace(XDLOG, "Init Hooks....\n");
	initialiseHooks(args);
	if (verbose) log_trace(XDLOG, "Init Properties....\n");
	initialiseProperties(args);
	if (verbose) log_trace(XDLOG, "Init Alloc....\n");
	initialiseAlloc(args);
	if (verbose) log_trace(XDLOG, "Init DLL....\n");
	initialiseDll(args);
	if (verbose) log_trace(XDLOG, "Init UTF8....\n");
	initialiseUtf8();
	if (verbose) log_trace(XDLOG, "Init ThreadStage1....\n");
	initialiseThreadStage1(args);
	if (verbose) log_trace(XDLOG, "Init Symbol....\n");
	initialiseSymbol();
	if (verbose) log_trace(XDLOG, "Init Class....\n");
	initialiseClass(args);
	if (verbose) log_trace(XDLOG, "Init Monitor....\n");
	initialiseMonitor();
	if (verbose) log_trace(XDLOG, "Init String....\n");
	initialiseString();
	if (verbose) log_trace(XDLOG, "Init Exception....\n");
	initialiseException();
	if (verbose) log_trace(XDLOG, "Init Natives....\n");
	initialiseNatives();
	if (verbose) log_trace(XDLOG, "Init JNI....\n");
	initialiseJNI();
	if (verbose) log_trace(XDLOG, "Init Interpreter....\n");
	initialiseInterpreter(args);
	if (verbose) log_trace(XDLOG, "Init ThreadStage2....\n");
	initialiseThreadStage2(args);
	if (verbose) log_trace(XDLOG, "Init gc....\n");
	initialiseGC(args);

	VM_initing = FALSE;
}

unsigned long parseMemValue(char *str) {
	char *end;
	unsigned long n = xi_strtoi(str, &end, 0);

	switch (end[0]) {
	case '\0':
		break;
	case 'M':
	case 'm':
		n *= MB;
		break;
	case 'K':
	case 'k':
		n *= KB;
		break;
	default:
		n = 0;
	}

	return n;
}

redpajama_set_name: RedPajamaGithub


text:
class String
  def every_other_char
    to_return = ''                         # each_char passes each char in str to the given block,
    each_char.with_index do |char, index|  # with_index iterates the given block for each element with an index
      to_return << char if index.even?     # append char with even index - 0, 2, 4...
    end
    to_return                              # call the var, otherwise it will just return the given string, with no changes
  end
  # puts "abcde".every_other_char          # test
end


text:
from abc import ABC, abstractmethod
from Utils.RandomGenerator import RandomGenerator

class AbstractHeuristic(ABC):

    """
        Abstract class that defines some methods that should have
        all the heuristics made
    """

    @abstractmethod
    def __init__(self,randomGenerator=None):
        if randomGenerator is None:
            randomGenerator = RandomGenerator()

        self.randomGenerator = randomGenerator

    @abstractmethod
    def calculate(self, dataset=None, solution=None, exploredataset=None):

        """

        :param dataset: full search space represented as an object of the class DataSet
        :param solution: one dimensional array with the base solution to use
        :param exploredataset: explored soluutions using the current solution as base
        :return: a solution one dimensional array
        """

    def calculateCost(self, dataset, solution):

        """

        :param dataset: full search space represented as an object of the class DataSet
        :param solution: one dimensional array with the base solution to use
        :return: an int with the value of the cost
        """

        cost = 0
        i = 0

        cost += dataset.getValueXY(0, solution[0]-1)

        #print("\t\t\ŧVALOR: ",dataset.getValueXY(0, solution[0]-1))

        for i in range(0, len(solution)-1):
            if solution[i] < solution[i+1]:
                x = solution[i]
                y = solution[i + 1]
            else:
                x = solution[i + 1]
                y = solution[i]

            cost += dataset.getValueXY(x, y-1)
            #print("\t\t\ŧVALOR (",x,",",y-1,"):  =", dataset.getValueXY(x,y-1))

        cost += dataset.getValueXY(0,solution[-1]-1)
        #print("\t\t\ŧVALOR: (",0,",",solution[-1]-1,")", dataset.getValueXY(0,solution[-1]-1))

        return cost

    def calculateCostDifference(self, dataset, i, j, solution, newCost):
        if j + 1 != i:
            if i > 0:
                newCost -= dataset.getValueAdapt(solution[i - 1], solution[i])
                newCost += dataset.getValueAdapt(solution[i - 1], solution[j])
            else:
                newCost -= dataset.getValueAdapt(solution[i], 0)
                newCost += dataset.getValueAdapt(solution[j], 0)
        if i < len(solution) - 1:
            newCost -= dataset.getValueAdapt(solution[i], solution[i + 1])
            newCost += dataset.getValueAdapt(solution[j], solution[i + 1])
        else:
            newCost -= dataset.getValueAdapt(solution[i], 0)
            newCost += dataset.getValueAdapt(solution[j], 0)
        if j > 0:
            newCost -= dataset.getValueAdapt(solution[j - 1], solution[j])
            newCost += dataset.getValueAdapt(solution[j - 1], solution[i])
        else:
            newCost -= dataset.getValueAdapt(solution[j], 0)
            newCost += dataset.getValueAdapt(solution[i], 0)
        if j + 1 != i:
            if j < len(solution) - 1:
                newCost -= dataset.getValueAdapt(solution[j], solution[j + 1])
                newCost += dataset.getValueAdapt(solution[i], solution[j + 1])
            else:
                newCost -= dataset.getValueAdapt(solution[j], 0)
                newCost += dataset.getValueAdapt(solution[i], 0)
        return newCost

    """
        Generates a random solution.It's usually used at start to generate a base solution
    """
    def generateRandomSolution(self, dataset):

        """

        :param dataset: full search space represented as an object of the class DataSet
        :return:
        """

        length = len(dataset.value[-1])
        solution = []

        """
            For each position of the solution array we generate a random number
            and if it is already in the array, we sum 1 (module length of the array) to the element until we
            found a number that isn't in the array
        """
        for i in range(length):
            value = self.randomGenerator.getRandomInt(1, length)

            while value in solution:
                value = (value + 1) % (length + 1)

                if value == 0:
                    value = 1

            solution.append(value)

        return solution

    def generateGreedySolution(self,dataset):

        """

        :param dataset:
        :return:
        """

        length = len(dataset.value[-1])
        solution = [0]
        used = 0
        first = True

        while used < length:

            for i in range(0,len(dataset.value)+1):

                if i not in solution:

                    if first:
                        first = False
                        min = i

                    elif dataset.getValueAdapt(solution[used],i) < dataset.getValueAdapt(solution[used],min):
                        min = i

            first = True
            solution.append(min)

            used+=1

        solution.pop(0)

        return solution

    def generateGreedySolutionWithRandomFirstElement(self,dataset):

        """

        :param dataset:
        :return:
        """

        length = len(dataset.value[-1])
        solution = [0]
        used = 0

        #TODO: check if len should be len(dataset.value) or len(dataset.value)-1
        min = self.randomGenerator.getRandomInt(0 ,length)+1

        solution.append(min)
        used += 1

        first = True

        while used < length:

            for i in range(0, len(dataset.value) + 1):

                if i not in solution:

                    if first:
                        first = False
                        min = i

                    elif dataset.getValueAdapt(solution[used], i) < dataset.getValueAdapt(solution[used], min):
                        min = i

            first = True
            solution.append(min)

            used += 1

        solution.pop(0)

        return solution

    def generateGreedySolutionWithMemory(self,dataset,longTimeMemory,nu,dmax,dmin,maxFrequency):

        """

        :param dataset:
        :return:
        """

        length = len(dataset.value[-1])
        solution = [0]
        used = 0
        first = True

        distance = dmax-dmin

        while used < length:

            for i in range(0,len(dataset.value)+1):

                if i not in solution and i != used:

                    if first:
                        first = False
                        min = i

                    currentCost = dataset.getValueAdapt(solution[used],i) + nu * distance * (longTimeMemory.getValueAdapt(solution[used], i) / maxFrequency)
                    minCost = dataset.getValueAdapt(solution[used],min) + nu * distance * (longTimeMemory.getValueAdapt(solution[used], min) / maxFrequency)

                    if currentCost < minCost :
                        min = i

            first = True
            solution.append(min)

            used+=1

        solution.pop(0)

        return solution


text:
package googl

import (
	"bytes"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/bitly/go-simplejson"
)

// GoogleShorten as string type, so we can put our target url in construction method
type GoogleShorten struct {
	Target     string
	BaseURL    string
	Version    string
	ShortenURL string
}

// NewGoogleShorten acts as constructor to create initial values
func (gs *GoogleShorten) NewGoogleShorten(key, target, version string) GoogleShorten {
	gs.Target = target
	gs.Version = version
	gs.BaseURL = "https://www.googleapis.com/urlshortener/v" + version + "/url?key=" + key

	return *gs
}

// ShortIt create shorten url send request to google api
func (gs *GoogleShorten) ShortIt() error {

	jsonParam := []byte(fmt.Sprintf(`{"longUrl": "%v"}`, gs.Target))
	req, err := http.NewRequest("POST", gs.BaseURL, bytes.NewBuffer(jsonParam))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	content, err := simplejson.NewJson(body)
	if err != nil {
		return err
	}

	jsonError := content.Get("error").Interface()
	if jsonError != nil {
		errorMap := jsonError.(map[string]interface{})
		errorStr := errorMap["message"]
		return errors.New(errorStr.(string))
	}

	gs.ShortenURL = content.Get("id").MustString()
	return nil
}

// String used return the value put in the construction type
func (gs *GoogleShorten) String() string {
	return gs.ShortenURL
}

func catchTheError(err error) {
	log.Fatalf("We have an error : %v", err)
}

// ShortIt is a main function to shorten given url
func ShortIt(key, url string) (string, error) {

	shortener := GoogleShorten{}
	googl := shortener.NewGoogleShorten(key, url, "1")
	err := googl.ShortIt()
	if err != nil {
		return "", err
	}

	return googl.String(), nil
}


text:
'use strict';

var fs = require('fs');
var template = fs.readFileSync(__dirname + '/dashboard.html', 'utf8');
var series = require('camunda-bpm-sdk-js').utils.series;

function prioritySort(a, b) {
  return a.priority > b.priority ? 1 : (a.priority < b.priority ? -1 : 0);
}

function valuesSort(a, b) {
  return a.value > b.value ? 1 : (a.value < b.value ? -1 : 0);
}

function replaceAll(str, obj) {
  Object.keys(obj).forEach(function(searched) {
    var replaced = obj[searched];
    str = str.split('{{' + searched + '}}').join(replaced);
  });
  return str;
}

function color(i, t) {
  var hue = (360 / t) * i;
  hue += 230;
  hue = hue > 360 ? hue-360 : hue;
  return 'hsl(' + hue + ', 70%, 41%)';
}

function valuesTreshold(l, t) {
  return l > 12 ? (Math.floor(t / l) * 0.5) : 0;
}

var Controller = [
  '$scope',
  'camAPI',
  'localConf',
  'Views',
  'hasPlugin',
  'page',
  'Data',
  'dataDepend',
  function(
  $scope,
  camAPI,
  localConf,
  Views,
  hasPlugin,
  page,
  Data,
  dataDepend
) {
    $scope.hasMetricsPlugin = hasPlugin('cockpit.dashboard.metrics', 'executed-activity-instances');
    $scope.hasProcessSearch = hasPlugin('cockpit.processes.dashboard', 'search-process-instances');
    $scope.hasCaseSearch = hasPlugin('cockpit.cases.dashboard', 'case-instances-search');
    $scope.hasTaskSearch = hasPlugin('cockpit.tasks.dashboard', 'search-tasks');

    $scope.mainPlugins = [];
    $scope.miscPlugins = [];

  // old plugins are still shown on the dashboard
    $scope.dashboardVars = { read: [ 'processData' ] };
    $scope.deprecateDashboardProviders = Views.getProviders({ component: 'cockpit.dashboard'});

  // reset breadcrumbs
    page.breadcrumbsClear();
    $scope.$root.showBreadcrumbs = false;
    page.titleSet('Dashboard');

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

    $scope.values = {
      procInst: [],
      procIncid: []
    };

    $scope.data = {
      actual: {}
    };

    $scope.linkBase = {
      processInstances: '/process-definition/{{id}}',
      processIncidents: '/process-definition/{{id}}',
      tasks: '/process-instance/{{processInstanceId}}/runtime?tab=user-tasks-tab'
    };

    if ($scope.hasProcessSearch) {
      $scope.linkBase.processInstances = '/processes?searchQuery=%5B%7B%22type%22:%22PIunfinished%22,%22operator%22:%22eq%22,%22value%22:%22%22,%22name%22:%22%22%7D,%7B%22type%22:%22PIprocessDefinitionKey%22,%22operator%22:%22eq%22,%22value%22:%22{{key}}%22,%22name%22:%22%22%7D%5D';
      $scope.linkBase.processIncidents = '/processes?searchQuery=%5B%7B%22type%22:%22PIwithIncidents%22,%22operator%22:%22eq%22,%22value%22:%22%22,%22name%22:%22%22%7D,%7B%22type%22:%22PIincidentStatus%22,%22operator%22:%22eq%22,%22value%22:%22open%22,%22name%22:%22%22%7D,%7B%22type%22:%22PIprocessDefinitionKey%22,%22operator%22:%22eq%22,%22value%22:%22{{key}}%22,%22name%22:%22%22%7D%5D';
    }

    function prepareValues(values, total, url) {
      var treshold = valuesTreshold(values.length, total);

      var belowTreshold = {
        value: 0,
        label: 'Others',
        names: [],
        url: url
      };

      values.forEach(function(item) {
        if (item.value && item.value < treshold) {
          belowTreshold.value += item.value;
          belowTreshold.names.push(item.label);
        }
      });

      values = values
        .filter(function(item) {
          return item.value && item.value >= treshold;
        })
        .sort(valuesSort);

      if (treshold) {
        values.unshift(belowTreshold);
      }

      return values.map(function(item, i) {
        item.color = color(i, values.length);
        return item;
      });
    }

    var caseDefResource = camAPI.resource('case-definition');
    var decisionDefResource = camAPI.resource('decision-definition');
    var deploymentResource = camAPI.resource('deployment');
    var processDefinitionService = camAPI.resource('process-definition');

    $scope.processData = dataDepend.create($scope);
    var processData = $scope.processData.newChild($scope);
    Data.instantiateProviders('cockpit.dashboard.data', {$scope: $scope, processData : processData});

    function aggregateInstances(processDefinitionStatistics) {
      var values = [];
      var totalInstances = 0;

      processDefinitionStatistics.forEach(function(statistic) {
        var processDefId = statistic.definition.id;
        var foundIds = $scope.processDefinitionData.filter(function(pd) {
          return pd.id === processDefId;
        });

        var foundObject = foundIds[0];
        if(foundObject && statistic.instances) {
          values.push({
            value: statistic.instances,
            label: foundObject.name || foundObject.id,
            url: replaceAll($scope.linkBase.processInstances, foundObject)
          });

          totalInstances += statistic.instances;
        }
      });

      $scope.values.procInst = prepareValues(values, totalInstances, '/processes');

      $scope.data.actual.runningProcessInstances = totalInstances;
    }

    function aggregateIncidents(processDefinitionStatistics) {
      var values = [];
      var totalIncidents = 0;

      processDefinitionStatistics.forEach(function(statistic) {
        var definitionIncidents = 0;
        statistic.incidents.forEach(function(info) {
          definitionIncidents += info.incidentCount;
        });

        values.push({
          value: definitionIncidents,
          label: statistic.definition.name || statistic.definition.id,
          url: replaceAll($scope.linkBase.processIncidents, statistic.definition)
        });

        totalIncidents += definitionIncidents;
      });

      $scope.values.procIncid = prepareValues(values, totalIncidents, '/processes');

      $scope.data.actual.openIncidents = totalIncidents;
    }

    var taskResource = camAPI.resource('task');
    $scope.$watch('actualActive', function() {
      if (!$scope.actualActive) { return; }

      $scope.loadingActual = true;
      series({
        processes: function(next) {
          processDefinitionService.list({
            latest: true
          }, function(err, data) {
            if (err) {
              return next(err);
            }

            $scope.processDefinitionData = data.items;

            processData.observe('processDefinitionStatistics', function(processDefinitionStatistics) {
              aggregateInstances(processDefinitionStatistics);
              aggregateIncidents(processDefinitionStatistics);
            });

            next();
          });
        },
        tasks: function(next) {
          taskResource.count({}, function(err, total) {
            if (err) { return next(); }

            $scope.data.actual.tasks = total;

            series({
              assignedToUser: function(done) {
                taskResource.count({
                  unfinished: true,
                  assigned: true
                }, function(err, value) {
                  done(err, {
                    label: 'Assigned to a user',
                    url: '/tasks?searchQuery=%5B%7B%22type%22:%22unfinished%22,%22operator%22:%22eq%22,%22value%22:%22%22,%22name%22:%22%22%7D,%7B%22type%22:%22assigned%22,%22operator%22:%22eq%22,%22value%22:%22%22,%22name%22:%22%22%7D%5D',
                    value: value
                  });
                });
              },
              assignedToGroup: function(done) {
                taskResource.count({
                  unfinished: true,
                  unassigned: true,
                  withCandidateGroups: true
                }, function(err, value) {
                  done(err, {
                    label: 'Assigned to 1 or more groups',
                    url: '/tasks?searchQuery=%5B%7B%22type%22:%22unfinished%22,%22operator%22:%22eq%22,%22value%22:%22%22,%22name%22:%22%22%7D,%7B%22type%22:%22withCandidateGroups%22,%22operator%22:%22eq%22,%22value%22:%22%22,%22name%22:%22%22%7D,%7B%22type%22:%22unassigned%22,%22operator%22:%22eq%22,%22value%22:%22%22,%22name%22:%22%22%7D%5D',
                    value: value
                  });
                });
              },
              unassigned: function(done) {
                taskResource.count({
                  unfinished: true,
                  unassigned: true,
                  withoutCandidateGroups: true
                }, function(err, value) {
                  done(err, {
                    label: 'Unassigned',
                    url: '/tasks?searchQuery=%5B%7B%22type%22:%22unfinished%22,%22operator%22:%22eq%22,%22value%22:%22%22,%22name%22:%22%22%7D,%7B%22type%22:%22withoutCandidateGroups%22,%22operator%22:%22eq%22,%22value%22:%22%22,%22name%22:%22%22%7D,%7B%22type%22:%22unassigned%22,%22operator%22:%22eq%22,%22value%22:%22%22,%22name%22:%22%22%7D%5D',
                    value: value
                  });
                });
              }
            }, function(err, results) {
              if (err) { return next(err); }

              var values = [];
              Object.keys(results).forEach(function(key) {
                values.push(results[key]);
              });

              $scope.values.tasks = prepareValues(values, total, '/tasks');

              next(null, total);
            });
          });
        }
      }, function() {
        $scope.loadingActual = false;
      });
    });

    function fetchDeployed(cb) {
      // 5: GET /process-definition/count?latestVersion=true
      // 6: GET /decision-definition/count?latestVersion=true
      // 7: GET /case-definition/count?latestVersion=true
      // 8: GET /deployment/count
      series({
        processDefinitions: function(next) {
          processDefinitionService.count({
            latestVersion: true
          }, next);
        },
        decisionDefinitions: function(next) {
          decisionDefResource.count({
            latestVersion: true
          }, next);
        },
        caseDefinitions: function(next) {
          caseDefResource.count({
            latestVersion: true
          }, next);
        },
        deploymentDefinitions: function(next) {
          deploymentResource.count({}, next);
        }
      }, function(err, results) {
        if (err) { throw err; }
        cb(err, results);
      });
    }

    $scope.$watch('deployedActive', function() {
      if (!$scope.deployedActive || $scope.data.deployed) { return; }

      $scope.loadingDeployed = true;
      fetchDeployed(function(err, results) {
        $scope.loadingDeployed = false;
        if (err) { throw err; }

        $scope.data.deployed = results;
      });
    });

  // ----------------------------------------------------------------------------------------
    [
      'actual',
      'metrics',
      'deployed',
      'deprecate'
    ].forEach(function(name) {
      $scope[name + 'Active'] = localConf.get('dashboardSection:' + name, true);
    });
    $scope.toggleSection = function(name) {
      $scope[name + 'Active'] = !$scope[name + 'Active'];
      localConf.set('dashboardSection:' + name, $scope[name + 'Active']);
    };

    $scope.metricsPeriod = localConf.get('dashboardMetricsPeriod', 'day');
    $scope.setMetricsPeriod = function(period) {
      $scope.metricsPeriod = period;
      localConf.set('dashboardMetricsPeriod', period);
    };

    if ($scope.hasMetricsPlugin) {
      $scope.metricsVars = { read: [ 'metricsPeriod' ] };
      $scope.metricsPlugins = Views.getProviders({
        component: 'cockpit.dashboard.metrics'
      }).sort(prioritySort);
    }
  }];

var RouteConfig = [ '$routeProvider', function($routeProvider) {
  $routeProvider.when('/dashboard', {
    template: template,
    controller: Controller,
    authentication: 'required',
    reloadOnSearch: false
  });
}];

module.exports = RouteConfig;


text:
package com.android.metal_archives;

/**
 * Created by BEJ2PLY on 9/14/2017.
 */
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

public class SearchResultAdapter extends RecyclerView.Adapter<SearchResultAdapter.ViewHolder> {
    private List<String> bands;
    private List<String> details;
    private Context mContext;

    public SearchResultAdapter(List<String> NameDataset, List<String> DetailsDataset, Context context) {
        bands = NameDataset;
        details = DetailsDataset;
        this.mContext = context;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView txtHeader;
        public TextView txtFooter;
        public View layout;

        public ViewHolder(View v) {
            super(v);
            layout = v;
            txtHeader = (TextView) v.findViewById(R.id.name);
            txtFooter = (TextView) v.findViewById(R.id.details);
        }
    }

    public void add(int position, String item) {
        bands.add(position, item);
        notifyItemInserted(position);
    }

    public void remove(int position) {
        bands.remove(position);
        notifyItemRemoved(position);
    }

    @Override
    public SearchResultAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.search_result_item, parent, false);
        // set the view's size, margins, paddings and layout parameters
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        final String name = bands.get(position);
        final String detail = details.get(position);
        holder.txtHeader.setText(name);

        holder.txtHeader.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mContext instanceof SearchableActivity){
                    ((SearchableActivity)mContext).onRecycleViewSelected(position);
                }

            }
        });

        holder.txtFooter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mContext instanceof SearchableActivity){
                    ((SearchableActivity)mContext).onRecycleViewSelected(position);
                }
            }
        });

        holder.txtFooter.setText(detail);
    }

    @Override
    public int getItemCount() {
        return bands.size();
    }

}


text:
package entity;

import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue(value = "credit_card")
public class CreditCard extends BasicBillingDetails{
    private String cardType;
    private String expirationMonth;
    private Integer expirationYear;

    public CreditCard() {}

    @Column(name = "card_type")
    public String getCardType() {
        return cardType;
    }

    public void setCardType(String cardType) {
        this.cardType = cardType;
    }

    @Column(name = "expiration_month")
    public String getExpirationMonth() {
        return expirationMonth;
    }

    public void setExpirationMonth(String expirationMonth) {
        this.expirationMonth = expirationMonth;
    }

    @Column(name = "expiration_year")
    public Integer getExpirationYear() {
        return expirationYear;
    }

    public void setExpirationYear(Integer expirationYear) {
        this.expirationYear = expirationYear;
    }
}


text:
class AzPurchasesController < ApplicationController

  filter_access_to :all

  layout "main"

  # GET /az_purchases
  # GET /az_purchases.xml
  def index
    @az_purchases = AzPurchase.paginate(:page => params[:page], :order => 'created_at desc')

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @az_purchases }
    end
  end

  # GET /az_purchases/1
  # GET /az_purchases/1.xml
  def show
    @az_purchase = AzPurchase.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @az_purchase }
    end
  end

  # GET /az_purchases/new
  # GET /az_purchases/new.xml
#  def new
#    @az_purchase = AzPurchase.new
#
#    respond_to do |format|
#      format.html # new.html.erb
#      format.xml  { render :xml => @az_purchase }
#    end
#  end

  # GET /az_purchases/1/edit
#  def edit
#    @az_purchase = AzPurchase.find(params[:id])
#  end
#
#  # POST /az_purchases
#  # POST /az_purchases.xml
#  def create
#    @az_purchase = AzPurchase.new(params[:az_purchase])
#
#    respond_to do |format|
#      if @az_purchase.save
#        format.html { redirect_to(@az_purchase, :notice => 'AzPurchase was successfully created.') }
#        format.xml  { render :xml => @az_purchase, :status => :created, :location => @az_purchase }
#      else
#        format.html { render :action => "new" }
#        format.xml  { render :xml => @az_purchase.errors, :status => :unprocessable_entity }
#      end
#    end
#  end
#
#  # PUT /az_purchases/1
#  # PUT /az_purchases/1.xml
#  def update
#    @az_purchase = AzPurchase.find(params[:id])
#
#    respond_to do |format|
#      if @az_purchase.update_attributes(params[:az_purchase])
#        format.html { redirect_to(@az_purchase, :notice => 'AzPurchase was successfully updated.') }
#        format.xml  { head :ok }
#      else
#        format.html { render :action => "edit" }
#        format.xml  { render :xml => @az_purchase.errors, :status => :unprocessable_entity }
#      end
#    end
#  end

  # DELETE /az_purchases/1
  # DELETE /az_purchases/1.xml
  def destroy
    @az_purchase = AzPurchase.find(params[:id])
    @az_purchase.destroy

    respond_to do |format|
      format.html { redirect_to(az_purchases_url) }
      format.xml  { head :ok }
    end
  end
end