text:
using System;
using System.Collections.Generic;
using Xunit;

namespace System.Text.Tests
{
    public static partial class NegativeEncodingTests
    {
        public static IEnumerable<object[]> Encodings_TestData()
        {
            yield return new object[] { new UnicodeEncoding(false, false) };
            yield return new object[] { new UnicodeEncoding(true, false) };
            yield return new object[] { new UnicodeEncoding(true, true) };
            yield return new object[] { new UnicodeEncoding(true, true) };
            yield return new object[] { new UTF7Encoding(true) };
            yield return new object[] { new UTF7Encoding(false) };
            yield return new object[] { new UTF8Encoding(true, true) };
            yield return new object[] { new UTF8Encoding(false, true) };
            yield return new object[] { new UTF8Encoding(true, false) };
            yield return new object[] { new UTF8Encoding(false, false) };
            yield return new object[] { new ASCIIEncoding() };
            yield return new object[] { new UTF32Encoding(true, true, true) };
            yield return new object[] { new UTF32Encoding(true, true, false) };
            yield return new object[] { new UTF32Encoding(true, false, false) };
            yield return new object[] { new UTF32Encoding(true, false, true) };
            yield return new object[] { new UTF32Encoding(false, true, true) };
            yield return new object[] { new UTF32Encoding(false, true, false) };
            yield return new object[] { new UTF32Encoding(false, false, false) };
            yield return new object[] { new UTF32Encoding(false, false, true) };
            yield return new object[] { Encoding.GetEncoding("latin1") };
        }

        [Theory]
        [MemberData(nameof(Encodings_TestData))]
        public static unsafe void GetByteCount_Invalid(Encoding encoding)
        {
            // Chars is null
            Assert.Throws<ArgumentNullException>(encoding is ASCIIEncoding ? "chars" : "s", () => encoding.GetByteCount((string)null));
            AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetByteCount((char[])null));
            AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetByteCount((char[])null, 0, 0));

            // Index < 0
            AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetByteCount(new char[3], -1, 0));

            // Count < 0
            AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetByteCount(new char[3], 0, -1));

            // Index + count > chars.Length
            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 0, 4));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 1, 3));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 2, 2));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 3, 1));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 4, 0));

            char[] chars = new char[3];
            fixed (char* pChars = chars)
            {
                char* pCharsLocal = pChars;
                AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetByteCount(null, 0));
                AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetByteCount(pCharsLocal, -1));
            }
        }

        [Theory]
        [MemberData(nameof(Encodings_TestData))]
        public static unsafe void GetBytes_Invalid(Encoding encoding)
        {
            string expectedStringParamName = encoding is ASCIIEncoding ? "chars" : "s";

            // Source is null
            AssertExtensions.Throws<ArgumentNullException>("s", () => encoding.GetBytes((string)null));
            AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char[])null));
            AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char[])null, 0, 0));
            Assert.Throws<ArgumentNullException>(expectedStringParamName, () => encoding.GetBytes((string)null, 0, 0, new byte[1], 0));
            AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char[])null, 0, 0, new byte[1], 0));

            // Bytes is null
            AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetBytes("abc", 0, 3, null, 0));
            AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetBytes(new char[3], 0, 3, null, 0));

            // Char index < 0
            AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetBytes(new char[1], -1, 0));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetBytes("a", -1, 0, new byte[1], 0));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetBytes(new char[1], -1, 0, new byte[1], 0));

            // Char count < 0
            AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetBytes(new char[1], 0, -1));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetBytes("a", 0, -1, new byte[1], 0));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetBytes(new char[1], 0, -1, new byte[1], 0));

            // Char index + count > source.Length
            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 2, 0));
            Assert.Throws<ArgumentOutOfRangeException>(expectedStringParamName, () => encoding.GetBytes("a", 2, 0, new byte[1], 0));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 2, 0, new byte[1], 0));

            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 1, 1));
            Assert.Throws<ArgumentOutOfRangeException>(expectedStringParamName, () => encoding.GetBytes("a", 1, 1, new byte[1], 0));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 1, 1, new byte[1], 0));

            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 0, 2));
            Assert.Throws<ArgumentOutOfRangeException>(expectedStringParamName, () => encoding.GetBytes("a", 0, 2, new byte[1], 0));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 0, 2, new byte[1], 0));

            // Byte index < 0
            AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes("a", 0, 1, new byte[1], -1));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes(new char[1], 0, 1, new byte[1], -1));

            // Byte index > bytes.Length
            AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes("a", 0, 1, new byte[1], 2));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes(new char[1], 0, 1, new byte[1], 2));

            // Bytes does not have enough capacity to accomodate result
            AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("a", 0, 1, new byte[0], 0));
            AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("abc", 0, 3, new byte[1], 0));
            AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("\uD800\uDC00", 0, 2, new byte[1], 0));
            AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(new char[1], 0, 1, new byte[0], 0));
            AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(new char[3], 0, 3, new byte[1], 0));
            AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("\uD800\uDC00".ToCharArray(), 0, 2, new byte[1], 0));

            char[] chars = new char[3];
            byte[] bytes = new byte[3];
            byte[] smallBytes = new byte[1];
            fixed (char* pChars = chars)
            fixed (byte* pBytes = bytes)
            fixed (byte* pSmallBytes = smallBytes)
            {
                char* pCharsLocal = pChars;
                byte* pBytesLocal = pBytes;
                byte* pSmallBytesLocal = pSmallBytes;

                // Bytes or chars is null
                AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char*)null, 0, pBytesLocal, bytes.Length));
                AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetBytes(pCharsLocal, chars.Length, (byte*)null, bytes.Length));

                // CharCount or byteCount is negative
                AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetBytes(pCharsLocal, -1, pBytesLocal, bytes.Length));
                AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetBytes(pCharsLocal, chars.Length, pBytesLocal, -1));

                // Bytes does not have enough capacity to accomodate result
                AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(pCharsLocal, chars.Length, pSmallBytesLocal, smallBytes.Length));
            }
        }

        [Theory]
        [MemberData(nameof(Encodings_TestData))]
        public static unsafe void GetCharCount_Invalid(Encoding encoding)
        {
            // Bytes is null
            AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetCharCount(null));
            AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetCharCount(null, 0, 0));

            // Index or count < 0
            AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetCharCount(new byte[4], -1, 0));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetCharCount(new byte[4], 0, -1));

            // Index + count > bytes.Length
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 5, 0));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 4, 1));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 3, 2));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 2, 3));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 1, 4));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 0, 5));

            byte[] bytes = new byte[4];
            fixed (byte* pBytes = bytes)
            {
                byte* pBytesLocal = pBytes;
                AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetCharCount(null, 0));
                AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetCharCount(pBytesLocal, -1));
            }
        }

        [Theory]
        [MemberData(nameof(Encodings_TestData))]
        public static unsafe void GetChars_Invalid(Encoding encoding)
        {
            // Bytes is null
            AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars(null));
            AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars(null, 0, 0));
            AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars(null, 0, 0, new char[0], 0));

            // Chars is null
            AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetChars(new byte[4], 0, 4, null, 0));

            // Index < 0
            AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetChars(new byte[4], -1, 4));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetChars(new byte[4], -1, 4, new char[1], 0));

            // Count < 0
            AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetChars(new byte[4], 0, -1));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetChars(new byte[4], 0, -1, new char[1], 0));

            // Count > bytes.Length
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 0, 5));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 0, 5, new char[1], 0));

            // Index + count > bytes.Length
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 5, 0));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 5, 0, new char[1], 0));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 4, 1));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 4, 1, new char[1], 0));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 3, 2));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 3, 2, new char[1], 0));

            // CharIndex < 0 or >= chars.Length
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetChars(new byte[4], 0, 4, new char[1], -1));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetChars(new byte[4], 0, 4, new char[1], 2));

            // Chars does not have enough capacity to accomodate result
            AssertExtensions.Throws<ArgumentException>("chars", () => encoding.GetChars(new byte[4], 0, 4, new char[1], 1));

            byte[] bytes = new byte[encoding.GetMaxByteCount(2)];
            char[] chars = new char[4];
            char[] smallChars = new char[1];
            fixed (byte* pBytes = bytes)
            fixed (char* pChars = chars)
            fixed (char* pSmallChars = smallChars)
            {
                byte* pBytesLocal = pBytes;
                char* pCharsLocal = pChars;
                char* pSmallCharsLocal = pSmallChars;

                // Bytes or chars is null
                AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars((byte*)null, 0, pCharsLocal, chars.Length));
                AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetChars(pBytesLocal, bytes.Length, (char*)null, chars.Length));

                // ByteCount or charCount is negative
                AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetChars(pBytesLocal, -1, pCharsLocal, chars.Length));
                AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetChars(pBytesLocal, bytes.Length, pCharsLocal, -1));

                // Chars does not have enough capacity to accomodate result
                AssertExtensions.Throws<ArgumentException>("chars", () => encoding.GetChars(pBytesLocal, bytes.Length, pSmallCharsLocal, smallChars.Length));
            }
        }

        [Theory]
        [MemberData(nameof(Encodings_TestData))]
        public static void GetMaxByteCount_Invalid(Encoding encoding)
        {
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetMaxByteCount(-1));
            if (!encoding.IsSingleByte)
            {
                AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetMaxByteCount(int.MaxValue / 2));
            }
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetMaxByteCount(int.MaxValue));

            // Make sure that GetMaxByteCount respects the MaxCharCount property of EncoderFallback
            // However, Utf7Encoding ignores this
            if (!(encoding is UTF7Encoding))
            {
                Encoding customizedMaxCharCountEncoding = Encoding.GetEncoding(encoding.CodePage, new HighMaxCharCountEncoderFallback(), DecoderFallback.ReplacementFallback);
                AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => customizedMaxCharCountEncoding.GetMaxByteCount(2));
            }
        }

        [Theory]
        [MemberData(nameof(Encodings_TestData))]
        public static void GetMaxCharCount_Invalid(Encoding encoding)
        {
            AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetMaxCharCount(-1));

            // TODO: find a more generic way to find what byteCount is invalid
            if (encoding is UTF8Encoding)
            {
                AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetMaxCharCount(int.MaxValue));
            }

            // Make sure that GetMaxCharCount respects the MaxCharCount property of DecoderFallback
            // However, Utf7Encoding ignores this
            if (!(encoding is UTF7Encoding) && !(encoding is UTF32Encoding))
            {
                Encoding customizedMaxCharCountEncoding = Encoding.GetEncoding(encoding.CodePage, EncoderFallback.ReplacementFallback, new HighMaxCharCountDecoderFallback());
                AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => customizedMaxCharCountEncoding.GetMaxCharCount(2));
            }
        }

        [Theory]
        [MemberData(nameof(Encodings_TestData))]
        public static void GetString_Invalid(Encoding encoding)
        {
            // Bytes is null
            AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetString(null));
            AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetString(null, 0, 0));

            // Index or count < 0
            Assert.Throws<ArgumentOutOfRangeException>(encoding is ASCIIEncoding ? "byteIndex" : "index", () => encoding.GetString(new byte[1], -1, 0));
            Assert.Throws<ArgumentOutOfRangeException>(encoding is ASCIIEncoding ? "byteCount" : "count", () => encoding.GetString(new byte[1], 0, -1));

            // Index + count > bytes.Length
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetString(new byte[1], 2, 0));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetString(new byte[1], 1, 1));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetString(new byte[1], 0, 2));
        }

        public static unsafe void Encode_Invalid(Encoding encoding, string chars, int index, int count)
        {
            Assert.Equal(EncoderFallback.ExceptionFallback, encoding.EncoderFallback);

            char[] charsArray = chars.ToCharArray();
            byte[] bytes = new byte[encoding.GetMaxByteCount(count)];

            if (index == 0 && count == chars.Length)
            {
                Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(chars));
                Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(charsArray));

                Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(chars));
                Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(charsArray));
            }

            Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(charsArray, index, count));

            Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(charsArray, index, count));

            Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(chars, index, count, bytes, 0));
            Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(charsArray, index, count, bytes, 0));

            fixed (char* pChars = chars)
            fixed (byte* pBytes = bytes)
            {
                char* pCharsLocal = pChars;
                byte* pBytesLocal = pBytes;

                Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(pCharsLocal + index, count));
                Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(pCharsLocal + index, count, pBytesLocal, bytes.Length));
            }
        }

        public static unsafe void Decode_Invalid(Encoding encoding, byte[] bytes, int index, int count)
        {
            Assert.Equal(DecoderFallback.ExceptionFallback, encoding.DecoderFallback);

            char[] chars = new char[encoding.GetMaxCharCount(count)];

            if (index == 0 && count == bytes.Length)
            {
                Assert.Throws<DecoderFallbackException>(() => encoding.GetCharCount(bytes));

                Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(bytes));
                Assert.Throws<DecoderFallbackException>(() => encoding.GetString(bytes));
            }

            Assert.Throws<DecoderFallbackException>(() => encoding.GetCharCount(bytes, index, count));

            Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(bytes, index, count));
            Assert.Throws<DecoderFallbackException>(() => encoding.GetString(bytes, index, count));

            Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(bytes, index, count, chars, 0));

            fixed (byte* pBytes = bytes)
            fixed (char* pChars = chars)
            {
                byte* pBytesLocal = pBytes;
                char* pCharsLocal = pChars;

                Assert.Throws<DecoderFallbackException>(() => encoding.GetCharCount(pBytesLocal + index, count));

                Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(pBytesLocal + index, count, pCharsLocal, chars.Length));
                Assert.Throws<DecoderFallbackException>(() => encoding.GetString(pBytesLocal + index, count));
            }
        }

        public static IEnumerable<object[]> Encoders_TestData()
        {
            foreach (object[] encodingTestData in Encodings_TestData())
            {
                Encoding encoding = (Encoding)encodingTestData[0];
                yield return new object[] { encoding.GetEncoder(), true };
                yield return new object[] { encoding.GetEncoder(), false };
            }
        }

        [Theory]
        [MemberData(nameof(Encoders_TestData))]
        public static void Encoder_GetByteCount_Invalid(Encoder encoder, bool flush)
        {
            // Chars is null
            AssertExtensions.Throws<ArgumentNullException>("chars", () => encoder.GetByteCount(null, 0, 0, flush));

            // Index is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoder.GetByteCount(new char[4], -1, 0, flush));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetByteCount(new char[4], 5, 0, flush));

            // Count is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoder.GetByteCount(new char[4], 0, -1, flush));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetByteCount(new char[4], 0, 5, flush));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetByteCount(new char[4], 1, 4, flush));
        }

        [Theory]
        [MemberData(nameof(Encoders_TestData))]
        public static void Encoder_GetBytes_Invalid(Encoder encoder, bool flush)
        {
            // Chars is null
            AssertExtensions.Throws<ArgumentNullException>("chars", () => encoder.GetBytes(null, 0, 0, new byte[4], 0, flush));

            // CharIndex is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoder.GetBytes(new char[4], -1, 0, new byte[4], 0, flush));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetBytes(new char[4], 5, 0, new byte[4], 0, flush));

            // CharCount is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoder.GetBytes(new char[4], 0, -1, new byte[4], 0, flush));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetBytes(new char[4], 0, 5, new byte[4], 0, flush));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetBytes(new char[4], 1, 4, new byte[4], 0, flush));

            // Bytes is null
            AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoder.GetBytes(new char[1], 0, 1, null, 0, flush));

            // ByteIndex is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoder.GetBytes(new char[1], 0, 1, new byte[4], -1, flush));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoder.GetBytes(new char[1], 0, 1, new byte[4], 5, flush));

            // Bytes does not have enough space
            int byteCount = encoder.GetByteCount(new char[] { 'a' }, 0, 1, flush);
            AssertExtensions.Throws<ArgumentException>("bytes", () => encoder.GetBytes(new char[] { 'a' }, 0, 1, new byte[byteCount - 1], 0, flush));
        }

        [Theory]
        [MemberData(nameof(Encoders_TestData))]
        public static void Encoder_Convert_Invalid(Encoder encoder, bool flush)
        {
            int charsUsed = 0;
            int bytesUsed = 0;
            bool completed = false;

            Action verifyOutParams = () =>
            {
                Assert.Equal(0, charsUsed);
                Assert.Equal(0, bytesUsed);
                Assert.False(completed);
            };

            // Chars is null
            AssertExtensions.Throws<ArgumentNullException>("chars", () => encoder.Convert(null, 0, 0, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            // CharIndex is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoder.Convert(new char[4], -1, 0, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.Convert(new char[4], 5, 0, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            // CharCount is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoder.Convert(new char[4], 0, -1, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.Convert(new char[4], 0, 5, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.Convert(new char[4], 1, 4, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            // Bytes is null
            AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoder.Convert(new char[1], 0, 1, null, 0, 0, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            // ByteIndex is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoder.Convert(new char[1], 0, 0, new byte[4], -1, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoder.Convert(new char[1], 0, 0, new byte[4], 5, 0, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            // ByteCount is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoder.Convert(new char[1], 0, 0, new byte[4], 0, -1, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoder.Convert(new char[1], 0, 0, new byte[4], 0, 5, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoder.Convert(new char[1], 0, 0, new byte[4], 1, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            // Bytes does not have enough space
            int byteCount = encoder.GetByteCount(new char[] { 'a' }, 0, 1, flush);
            AssertExtensions.Throws<ArgumentException>("bytes", () => encoder.Convert(new char[] { 'a' }, 0, 1, new byte[byteCount - 1], 0, byteCount - 1, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();
        }

        public static IEnumerable<object[]> Decoders_TestData()
        {
            foreach (object[] encodingTestData in Encodings_TestData())
            {
                Encoding encoding = (Encoding)encodingTestData[0];
                yield return new object[] { encoding, encoding.GetDecoder(), true };
                yield return new object[] { encoding, encoding.GetDecoder(), false };
            }
        }

        [Theory]
        [MemberData(nameof(Decoders_TestData))]
        public static void Decoder_GetCharCount_Invalid(Encoding _, Decoder decoder, bool flush)
        {
            // Bytes is null
            AssertExtensions.Throws<ArgumentNullException>("bytes", () => decoder.GetCharCount(null, 0, 0, flush));

            // Index is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => decoder.GetCharCount(new byte[4], -1, 0, flush));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetCharCount(new byte[4], 5, 0, flush));

            // Count is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => decoder.GetCharCount(new byte[4], 0, -1, flush));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetCharCount(new byte[4], 0, 5, flush));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetCharCount(new byte[4], 1, 4, flush));
        }

        [Theory]
        [MemberData(nameof(Decoders_TestData))]
        public static void Decoder_GetChars_Invalid(Encoding _, Decoder decoder, bool flush)
        {
            // Bytes is null
            AssertExtensions.Throws<ArgumentNullException>("bytes", () => decoder.GetChars(null, 0, 0, new char[4], 0, flush));

            // ByteIndex is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => decoder.GetChars(new byte[4], -1, 0, new char[4], 0, flush));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetChars(new byte[4], 5, 0, new char[4], 0, flush));

            // ByteCount is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => decoder.GetChars(new byte[4], 0, -1, new char[4], 0, flush));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetChars(new byte[4], 0, 5, new char[4], 0, flush));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetChars(new byte
                [4], 1, 4, new char[4], 0, flush));

            // Chars is null
            AssertExtensions.Throws<ArgumentNullException>("chars", () => decoder.GetChars(new byte[1], 0, 1, null, 0, flush));

            // CharIndex is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => decoder.GetChars(new byte[1], 0, 1, new char[4], -1, flush));
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => decoder.GetChars(new byte[1], 0, 1, new char[4], 5, flush));

            // Chars does not have enough space
            int charCount = decoder.GetCharCount(new byte[4], 0, 4, flush);
            AssertExtensions.Throws<ArgumentException>("chars", () => decoder.GetChars(new byte[4], 0, 4, new char[charCount - 1], 0, flush));
        }

        [Theory]
        [MemberData(nameof(Decoders_TestData))]
        public static void Decoder_Convert_Invalid(Encoding encoding, Decoder decoder, bool flush)
        {
            int bytesUsed = 0;
            int charsUsed = 0;
            bool completed = false;

            Action verifyOutParams = () =>
            {
                Assert.Equal(0, bytesUsed);
                Assert.Equal(0, charsUsed);
                Assert.False(completed);
            };

            // Bytes is null
            AssertExtensions.Throws<ArgumentNullException>("bytes", () => decoder.Convert(null, 0, 0, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            // ByteIndex is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => decoder.Convert(new byte[4], -1, 0, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.Convert(new byte[4], 5, 0, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            // ByteCount is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => decoder.Convert(new byte[4], 0, -1, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.Convert(new byte[4], 0, 5, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.Convert(new byte[4], 1, 4, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            // Chars is null
            AssertExtensions.Throws<ArgumentNullException>("chars", () => decoder.Convert(new byte[1], 0, 1, null, 0, 0, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            // CharIndex is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => decoder.Convert(new byte[1], 0, 0, new char[4], -1, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => decoder.Convert(new byte[1], 0, 0, new char[4], 5, 0, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            // CharCount is invalid
            AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => decoder.Convert(new byte[1], 0, 0, new char[4], 0, -1, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => decoder.Convert(new byte[1], 0, 0, new char[4], 0, 5, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => decoder.Convert(new byte[1], 0, 0, new char[4], 1, 4, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();

            // Chars does not have enough space
            AssertExtensions.Throws<ArgumentException>("chars", () => decoder.Convert(new byte[4], 0, 4, new char[0], 0, 0, flush, out charsUsed, out bytesUsed, out completed));
            verifyOutParams();
        }
    }

    public class HighMaxCharCountEncoderFallback : EncoderFallback
    {
        public override int MaxCharCount => int.MaxValue;
        public override EncoderFallbackBuffer CreateFallbackBuffer() => ReplacementFallback.CreateFallbackBuffer();
    }

    public class HighMaxCharCountDecoderFallback : DecoderFallback
    {
        public override int MaxCharCount => int.MaxValue;
        public override DecoderFallbackBuffer CreateFallbackBuffer() => ReplacementFallback.CreateFallbackBuffer();
    }
}


text:
import { AnnotationEditorType } from "pdfjs-lib";
import { GrabToPan } from "./grab_to_pan.js";
import { PresentationModeState } from "./ui_utils.js";

const CursorTool = {
  SELECT: 0, // The default value.
  HAND: 1,
  ZOOM: 2,
};

/**
 * @typedef {Object} PDFCursorToolsOptions
 * @property {HTMLDivElement} container - The document container.
 * @property {EventBus} eventBus - The application event bus.
 * @property {number} [cursorToolOnLoad] - The cursor tool that will be enabled
 *   on load; the constants from {CursorTool} should be used. The default value
 *   is `CursorTool.SELECT`.
 */

class PDFCursorTools {
  /**
   * @param {PDFCursorToolsOptions} options
   */
  constructor({ container, eventBus, cursorToolOnLoad = CursorTool.SELECT }) {
    this.container = container;
    this.eventBus = eventBus;

    this.active = CursorTool.SELECT;
    this.previouslyActive = null;

    this.handTool = new GrabToPan({
      element: this.container,
    });

    this.#addEventListeners();

    // Defer the initial `switchTool` call, to give other viewer components
    // time to initialize *and* register 'cursortoolchanged' event listeners.
    Promise.resolve().then(() => {
      this.switchTool(cursorToolOnLoad);
    });
  }

  /**
   * @type {number} One of the values in {CursorTool}.
   */
  get activeTool() {
    return this.active;
  }

  /**
   * @param {number} tool - The cursor mode that should be switched to,
   *                        must be one of the values in {CursorTool}.
   */
  switchTool(tool) {
    if (this.previouslyActive !== null) {
      // Cursor tools cannot be used in PresentationMode/AnnotationEditor.
      return;
    }
    if (tool === this.active) {
      return; // The requested tool is already active.
    }

    const disableActiveTool = () => {
      switch (this.active) {
        case CursorTool.SELECT:
          break;
        case CursorTool.HAND:
          this.handTool.deactivate();
          break;
        case CursorTool.ZOOM:
        /* falls through */
      }
    };

    // Enable the new cursor tool.
    switch (tool) {
      case CursorTool.SELECT:
        disableActiveTool();
        break;
      case CursorTool.HAND:
        disableActiveTool();
        this.handTool.activate();
        break;
      case CursorTool.ZOOM:
      /* falls through */
      default:
        console.error(`switchTool: "${tool}" is an unsupported value.`);
        return;
    }
    // Update the active tool *after* it has been validated above,
    // in order to prevent setting it to an invalid state.
    this.active = tool;

    this.#dispatchEvent();
  }

  #dispatchEvent() {
    this.eventBus.dispatch("cursortoolchanged", {
      source: this,
      tool: this.active,
    });
  }

  #addEventListeners() {
    this.eventBus._on("switchcursortool", evt => {
      this.switchTool(evt.tool);
    });

    let annotationEditorMode = AnnotationEditorType.NONE,
      presentationModeState = PresentationModeState.NORMAL;

    const disableActive = () => {
      const previouslyActive = this.active;

      this.switchTool(CursorTool.SELECT);
      this.previouslyActive ??= previouslyActive; // Keep track of the first one.
    };
    const enableActive = () => {
      const previouslyActive = this.previouslyActive;

      if (
        previouslyActive !== null &&
        annotationEditorMode === AnnotationEditorType.NONE &&
        presentationModeState === PresentationModeState.NORMAL
      ) {
        this.previouslyActive = null;
        this.switchTool(previouslyActive);
      }
    };

    this.eventBus._on("secondarytoolbarreset", evt => {
      if (this.previouslyActive !== null) {
        annotationEditorMode = AnnotationEditorType.NONE;
        presentationModeState = PresentationModeState.NORMAL;

        enableActive();
      }
    });

    this.eventBus._on("annotationeditormodechanged", ({ mode }) => {
      annotationEditorMode = mode;

      if (mode === AnnotationEditorType.NONE) {
        enableActive();
      } else {
        disableActive();
      }
    });

    this.eventBus._on("presentationmodechanged", ({ state }) => {
      presentationModeState = state;

      if (state === PresentationModeState.NORMAL) {
        enableActive();
      } else if (state === PresentationModeState.FULLSCREEN) {
        disableActive();
      }
    });
  }
}

export { CursorTool, PDFCursorTools };

redpajama_set_name: RedPajamaGithub


text:
package net.apkc.quary.node;

import net.apkc.quary.definitions.index.IndexDefinition;
import net.apkc.quary.docs.QuaryDocument;
import net.apkc.quary.reactor.Parameters;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.VersionedProtocol;

/**
 * Interface for Quary nodes. All Quary nodes must implement this interface.
 *
 * @author Andreas P. Koenzen <akc at apkc.net>
 * @version 0.1
 */
public interface NodeInterface extends VersionedProtocol
{

    public static long versionID = 1L;

    /**
     * Shutdown the node.
     */
    public void shutdown();

    /**
     * Close the indexer in the node. The node may still be up, but it'll be
     * out of service.
     *
     * @param definitionID The ID of the index.
     * @param node         The node to close.
     *
     * @return 0 if the operation was completed without errors, >0 otherwise.
     */
    public int close(String definitionID, Node node);

    /**
     * Returns the version of the node.
     *
     * @return A long number with the version of the node.
     */
    public long version();

    /**
     * Utility method to check if a node is up and running.
     *
     * @return TRUE if the node is up, FALSE otherwise.
     */
    public boolean isUp();

    /**
     * This method initializes the kernel index writer.
     *
     *

     * It must be called just before the write() method.

     *
     * @param conf         The configuration file.
     * @param definitionID The ID of the index.
     * @param node         The node where the writer is at.
     *
     * @return 0 if the operation was completed without errors, >0 otherwise.
     */
    public int openWriter(Configuration conf, String definitionID, Node node);

    /**
     * Creates the kernel index. Via local or remote interface.
     *
     * @param key         Key that identifies the document.
     * @param doc         The AIME's document to be processed and indexed.
     * @param def         The definition object to use.
     * @param elapsedTime The elapsed time since the indexing process started.
     */
    public void write(Text key, QuaryDocument doc, IndexDefinition def, long elapsedTime);

    /**
     * Performs a search in a IndexServer instance.
     *
     * @param conf   Configuration file.
     * @param def    The definition object to use.
     * @param node   The node where the writer is at.
     * @param params The object containing the search parameters.
     *
     * @return The response in XML format, but encapsulated in an Hadoop Text
     *         object.
     */
    public Text search(Configuration conf, IndexDefinition def, Node node, Parameters params);

    /**
     * This method checks if the only reader to the kernel is open, and if it is
     * then return TRUE, FALSE otherwise.
     *
     *

     * But first this method will try to open the reader to the kernel, by
     * calling the method openReader().

     *
     * @param reOpenReaders If the reader/s should be re-open after an index
     *                      update operation. TRUE will re-open all readers, and
     *                      FALSE will leave everything as is.
     * @param definitionID  The ID of the index.
     * @param node          The node in which to operate.
     *
     * @return TRUE if the reader is open, FALSE otherwise.
     */
    public boolean areSearchersOpen(boolean reOpenReaders, String definitionID, Node node);

    /**
     * This method cleans/deletes up all the files in the kernel index.
     *
     * @param definitionID The ID of the index.
     * @param node         The node in which to operate.
     *
     * @return TRUE if the files had been deleted, FALSE otherwise.
     */
    public boolean cleanIndex(String definitionID, Node node);
}


text:
Please be aware that I'm struggling to maintain this plugin.  Even after considerable effort, I have been unable to produce a reliable development environment.

While I will work to rectify this, neither Android or Cordova/ Phonegap development represent a priority to me.  Neither present me with paid income or particularly excite me enough to put aside other projects.

I will make attempts to be more active in responding to questions – and apologies for any previous delays.

Please keep the above in mind before actively using this plugin.

# Background Service Plugin Core (bgs-core)

## Quick summary
This repository provides the core functionality for the Background Service Plugin for Cordova.  The functionality is not a complete plugin - it is intended to be extended by developers to create their own background service.

An example background service is provided in the https://github.com/Red-Folder/bgs-sample repository.

## Getting started
To understand how to create your own background service it is advised that you read the following articles:

* [Using the MyService Sample] (https://github.com/Red-Folder/bgs-core/wiki/Using-the-MyService-Sample)
* [Build your own Background Service] (https://github.com/Red-Folder/bgs-core/wiki/Build-your-own-Background-Service)
* [Build your own plugin] (https://github.com/Red-Folder/bgs-core/wiki/Build-your-own-plugin)

Further documentation can be found at https://github.com/Red-Folder/bgs-core/wiki

## Questions and Support
If you have problems, then please log an issue against the bgs-core repository (https://github.com/Red-Folder/bgs-core/issues).

As the plugin is updated (for new features or fixes) I will tweet via @FolderRed and blog http://red-folder.blogspot.co.uk/

## Older version
This version of the plugin is intended to work with Cordova 3.0.0+

The older version of the plugin is available at https://github.com/Red-Folder/Cordova-Plugin-BackgroundService.  Please note however that this older repository is unlikely to be maintained going forwards.  It is advised that you move to Cordova 3.x.x as soon as possible.

## Spread the love

If you find the Background Service Plugin useful then spread the love.

All the work I do on the Plugin is done in my spare time - time I would otherwise be spending taking my wife out for a nice meal or helping my lad find vinyl records (he's currently very much into The Smiths, Fleetwood Mac and Kate Bush).

The Plugin is free and will always remain free. I will continue to develop, maintain and distribute the Plugin under the MIT License.

https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=E64TCFQ3NLHZ8

## Licence
Copyright 2013 Red Folder Consultancy Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


text:
package edu.asu.qstore4s.search.elements.factory.impl;

import org.springframework.stereotype.Service;

import edu.asu.qstore4s.search.elements.ISearchExpression;
import edu.asu.qstore4s.search.elements.factory.ISearchExpressionFactory;
import edu.asu.qstore4s.search.elements.impl.SearchExpression;

@Service
public class SearchExpressionFactory implements ISearchExpressionFactory {

	@Override
	public ISearchExpression createSearchExpression(String expression)
	{
		ISearchExpression expressionObject = new SearchExpression();
		expressionObject.setExpression(expression);
		return expressionObject;
	}
}


text:
using System;
using System.Linq;

namespace Excel.TestDoubles
{
    public class Excel2013Facade
    {
        public Excel2013Facade()
        {
            Application = new ApplicationTestDouble(new Version(14, 0));
        }

        public ApplicationTestDouble Application { get; private set; }

        public Tuple<WorkbookTestDouble, WindowTestDouble> NewWorksheet()
        {
            if (Application.Workbooks.Count == 0)
            {
                var windowTestDouble = Application.Windows.OfType<WindowTestDouble>().Single();
                var workbookTestDouble = new WorkbookTestDouble(Application, windowTestDouble);
                ((WorkbooksTestDouble)Application.Workbooks).Add(workbookTestDouble);
                Application.RaiseNewWorkbook(workbookTestDouble);
                Application.RaiseWorkbookOpen(workbookTestDouble);

                return Tuple.Create(workbookTestDouble, windowTestDouble);
            }

            throw new NotImplementedException();
        }
    }
}


text:
package facetoday.spring.web.dao;

import java.sql.SQLException;
import java.util.List;

import facetoday.spring.web.vo.MemberVo;
import facetoday.spring.web.vo.SongListVo;
import facetoday.spring.web.vo.SongVo;

public interface SongDao {

	List<SongVo> selectAll() throws SQLException;

	/**
	 * 날씨에 해당하는 날씨 검색
	 * 작성자 : 박찬희
	 * @param weather
	 * @param singer
	 * @param title
	 * @return
	 * @throws SQLException
	 */

	List<SongVo> songSelectByWeather(String weather) throws SQLException;
	List<SongVo> songSelectByState(MemberVo vo) throws SQLException;

	boolean createList(SongListVo vo) throws SQLException;
	boolean userList(SongListVo vo) throws SQLException;
	List<SongListVo> userlistAll(MemberVo vo) throws SQLException;
	boolean deleteList(int list_num) throws SQLException;
}


text:
Introduction

Add a dropdown list to any button. Make sure that the data-activates attribute matches the id in the <ul> tag.

You can add a divider with the <li class="divider"></li> tag.

        Drop Me!

one

two

three

  <!-- Dropdown Trigger -->
  <a class='dropdown-button btn' href='#' data-activates='dropdown1'>Drop Me!</a>

  <!-- Dropdown Structure -->
  <ul id='dropdown1' class='dropdown-content'>
    <li><a href="/dropdown#!">one</a></li>
    <li><a href="/dropdown#!">two</a></li>
    <li class="divider"></li>
    <li><a href="/dropdown#!">three</a></li>
  </ul>

Options

                Option Name
                Description

              induration
              The duration of the transition enter in milliseconds. Default: 300

              outduration
              The duration of the transition out in milliseconds. Default: 225

              constrainwidth
              If true, constrainWidth to the size of the dropdown activator. Default: true

              hover
              If true, the dropdown will open on hover. Default: false

              gutter
              This defines the spacing from the aligned edge. Default: 0

              beloworigin
              If true, the dropdown will show below the activator. Default: false

              alignment
              Defines the edge the menu is aligned to. Default: 'left'

              stoppropagation
              If true, stops the event propagating from the dropdown origin click handler. Default: false

To use these inline you have to add them as data attributes. If you want more dynamic control, you can define them using the jQuery plugin below.

  <a class='dropdown-button btn' data-beloworigin="true" href='#' data-activates='dropdown1'>Drop Me!</a>

jQuery Plugin Initialization

Initialization for dropdowns is only necessary if you create them dynamically.

  $('.dropdown-button').dropdown({
      inDuration: 300,
      outDuration: 225,
      constrain_width: false, // Does not change width of dropdown to that of the activator
      hover: true, // Activate on hover
      gutter: 0, // Spacing from edge
      belowOrigin: false, // Displays dropdown below the button
      alignment: 'left' // Displays dropdown with edge aligned to the left of button
    }
  );

Introduction

Options

Initialization


text:
package com.amazonaws.services.sns.model;

import javax.annotation.Generated;

/**
 * <p>
 * The request was rejected because the specified customer master key (CMK) isn't enabled.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class KMSDisabledException extends com.amazonaws.services.sns.model.AmazonSNSException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new KMSDisabledException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public KMSDisabledException(String message) {
        super(message);
    }

}


text:
package my.ostrea.blog;

import my.ostrea.blog.controllers.BaseController;
import my.ostrea.blog.models.Article;
import my.ostrea.blog.models.ArticleRepository;
import my.ostrea.blog.models.MyUser;
import my.ostrea.blog.models.UserRepository;
import my.ostrea.blog.utils.TestUtil;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.util.Iterator;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = BlogApplication.class)
@WebAppConfiguration
public class BlogApplicationTests {
    private static final String USERNAME_FOR_TESTS = "test";

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ArticleRepository articleRepository;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .apply(springSecurity())
                .build();
    }

    @Test
    public void accessingStartPageAsAnonymousShouldReturnViewNamedIndexAndModelWithZeroAttributes()
            throws Exception {
        mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(view().name("index"))
                .andExpect(model().attributeDoesNotExist("articles"));
    }

	@Test
    @WithUserDetails("test")
	public void accessingStartPageAsLoggedUserShouldReturnViewNamedIndexAndModelWithOneAttribute() throws Exception {
        mockMvc.perform(
                get("/"))
                .andExpect(status().isOk())
                .andExpect(view().name("index"))
                .andExpect(model().attributeExists("articles"));
    }

    @Test
    public void accessingUsernamePageAsAnonymousShouldRedirectToLoginPage()
            throws Exception {
        mockMvc.perform(get("/" + USERNAME_FOR_TESTS))
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrlPattern("**/login"));
    }

    @Test
    @WithMockUser("userForTests")
    public void accessingUsernamePageAsLoggedUserIfUsernameIsNotLoggedUsernameShouldShowIndexViewWithModelWithOneAttr()
            throws Exception {
        mockMvc.perform(get("/" + USERNAME_FOR_TESTS))
                .andExpect(status().isOk())
                .andExpect(view().name("index"))
                .andExpect(model().attributeExists("articles"));
    }

    @Test
    @WithMockUser("userForTests")
    public void accessingNotExistingUsernamePageAsLoggedUserShouldShowIndexViewWithModelWithZeroAttr()
            throws Exception {
        mockMvc.perform(get("/not_existing_user"))
                .andExpect(status().isOk())
                .andExpect(view().name("index"))
                .andExpect(model().attributeDoesNotExist("articles"));
    }

    @Test
    @WithUserDetails(USERNAME_FOR_TESTS)
    public void accessingYourOwnUsernamePageAsLoggedUserShouldRedirectToIndex()
            throws Exception {
        mockMvc.perform(get("/" + USERNAME_FOR_TESTS))
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl("/"));
    }

    @Test
    @WithMockUser("userForTests")
    public void deletingNotExistingArticleShouldReturnNotFound() throws Exception {
        mockMvc.perform(get("/delete_article?article_id=-1"))
                .andExpect(status().isNotFound());
    }

    @Test
    @WithMockUser("userForTests")
    public void deletingOtherPersonArticleShouldReturnForbidden() throws Exception {
        MyUser author = userRepository.findByUsername(USERNAME_FOR_TESTS).get();
        Article article = new Article("test", "test", author);
        Article savedArticle = articleRepository.save(article);

        mockMvc.perform(get("/delete_article?article_id=" + savedArticle.getId()))
                .andExpect(status().isForbidden());

        articleRepository.delete(savedArticle);
    }

    @Test
    @WithUserDetails(USERNAME_FOR_TESTS)
    public void deletingExistingArticleShouldRedirectToUsersPage() throws Exception {
        MyUser author = userRepository.findByUsername(USERNAME_FOR_TESTS).get();
        Article article = new Article("test", "test", author);
        Article savedArticle = articleRepository.save(article);

        mockMvc.perform(get("/delete_article?article_id=" + savedArticle.getId()))
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl(USERNAME_FOR_TESTS));

        articleRepository.delete(savedArticle);
    }

    @Test
    public void accessingCreateArticlePageAsAnonymousShouldRedirectToLoginPage()
            throws Exception {
        mockMvc.perform(get("/create_article"))
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrlPattern("**/login"));
    }

    @Test
    @WithUserDetails(USERNAME_FOR_TESTS)
    public void createArticleWithTitleGreaterThan255ShouldReturnViewWithTitleError() throws Exception {
        mockMvc.perform(post("/create_article")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("title", TestUtil.createStringWithLength(256))
                .param("content", "")
                .with(csrf()))
                .andExpect(status().isOk())
                .andExpect(view().name("create_article"))
                .andExpect(model().attributeExists("titleError"))
                .andExpect(model().attributeDoesNotExist("contentError"));
    }

    @Test
    @WithUserDetails(USERNAME_FOR_TESTS)
    public void createArticleWithContentGreaterThan255ShouldReturnViewWithContentError() throws Exception {
        mockMvc.perform(post("/create_article")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("title", "")
                .param("content", TestUtil.createStringWithLength(256))
                .with(csrf()))
                .andExpect(status().isOk())
                .andExpect(view().name("create_article"))
                .andExpect(model().attributeExists("contentError"))
                .andExpect(model().attributeDoesNotExist("titleError"));
    }

    @Test
    @WithUserDetails(USERNAME_FOR_TESTS)
    public void createArticleWithContentAndTitleGreaterThan255ShouldReturnViewWithContentAndTitleErrors()
            throws Exception {
        mockMvc.perform(post("/create_article")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("title", TestUtil.createStringWithLength(256))
                .param("content", TestUtil.createStringWithLength(256))
                .with(csrf()))
                .andExpect(status().isOk())
                .andExpect(view().name("create_article"))
                .andExpect(model().attributeExists("titleError"))
                .andExpect(model().attributeExists("contentError"));
    }
}


text:
package org.apache.jena.shacl.tests.std;

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

import org.apache.jena.shacl.testing.ShaclTest;
import org.apache.jena.shacl.testing.ShaclTestItem;
import org.apache.jena.shacl.testing.ShaclTests;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class TestShaclSparqlWG {

    @Parameters(name = "{0}")
    public static Collection<Object[]> data() throws Exception {
        String manifest = "src/test/files/std/sparql/manifest.ttl";

        // The W3C WG tests for  SPARQL-based Constraints is made up of:
        //String manifest = "src/test/files/std/sparql/property/manifest.ttl";
        //String manifest = "src/test/files/std/sparql/pre-binding/manifest.ttl";
        //String manifest = "src/test/files/std/sparql/node/manifest.ttl";
        //String manifest = "src/test/files/std/sparql/component/manifest.ttl";

        List<String> omitManifests = new ArrayList<>();
        return ShaclTests.junitParameters(manifest, omitManifests);
    }

    private ShaclTestItem test;

    public TestShaclSparqlWG(String name,  ShaclTestItem test) {
        this.test = test;
    }

    @Test
    public void test() { ShaclTest.shaclTest(test); }
}


text:
**NOTE**: This client can connect to JetServer but the coding, documenation etc are still work in progress.
This is a client project for [jetserver](https://github.com/menacher/java-game-server/tree/master/jetserver) library. An example main class is provided in src/main/flex org.menacheri package.

About the Client
================
Execute Main.as from IDE and it will connect to remote jetserver and start receiving events. Assumption is that JetServer is running and Main.as is using accurate hostname and port number.

Usage as game client
====================
The general usage steps could be as outlined below.
1.  Create a loginHelper.
2.  Create a session factory using this login helper instance.
3.  Create as many sessions as required using this factory. Generally only one is required for a client.
4.  Check the code in Main.as for more information on how to add an event listener to session to receive events.
5.  Main.as has code on how to write back to JetServer. Mostly it is done using session.sendToServer(JetEvent).


text:
using HWApp.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace hwapp.tests
{
    public sealed class GreeterVSTests
    {
        [TestClass]
        public sealed class TheGreaterMethod
        {
            [TestMethod]
            public void Should_Not_Fail_Test()
            {
                Assert.AreNotEqual("true", Environment.GetEnvironmentVariable("hwapp_fail_test"));
            }

            [TestMethod]
            public void Should_Greet_World()
            {
                // Given
                var name = "World";
                var expect = "Hello World!";

                // When
                var result = Greeter.GetGreeting(name);

                // Then
                Assert.AreEqual(expect, result);
            }

            [TestMethod]
            public void Should_Throw_On_Null_Name()
            {
                // Given
                string name = null;

                // When
                try
                {
                    Greeter.GetGreeting(name);
                }
                catch (Exception result)
                {
                    // Then
                    Assert.IsNotNull(result);
                    Assert.IsInstanceOfType(result, typeof(ArgumentNullException));
                    Assert.AreEqual($"Value cannot be null. (Parameter 'name')", result.Message);
                }
            }
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Linio\Component\Input\Transformer;

interface TransformerInterface
{
    public function transform($value);
}


text:
namespace ash {

UserOnlineSigninNotifier::UserOnlineSigninNotifier(
    const user_manager::UserList& users)
    : users_(users),
      online_login_refresh_timer_(std::make_unique<base::OneShotTimer>()) {}

UserOnlineSigninNotifier::~UserOnlineSigninNotifier() = default;

void UserOnlineSigninNotifier::CheckForPolicyEnforcedOnlineSignin() {
  base::TimeDelta min_delta = base::TimeDelta::Max();
  user_manager::KnownUser known_user(g_browser_process->local_state());
  for (auto* user : users_) {
    const absl::optional<base::TimeDelta> offline_signin_limit =
        known_user.GetOfflineSigninLimit(user->GetAccountId());
    if (!offline_signin_limit) {
      continue;
    }

    const base::Time last_online_signin =
        known_user.GetLastOnlineSignin(user->GetAccountId());
    base::TimeDelta time_to_next_online_signin = login::TimeToOnlineSignIn(
        last_online_signin, offline_signin_limit.value());
    if (time_to_next_online_signin.is_positive() &&
        time_to_next_online_signin < min_delta) {
      min_delta = time_to_next_online_signin;
    }
    if (time_to_next_online_signin <= base::TimeDelta() &&
        !user->force_online_signin()) {
      user_manager::UserManager::Get()->SaveForceOnlineSignin(
          user->GetAccountId(), true);
      NotifyObservers(user->GetAccountId());
    }
  }
  if (min_delta < base::TimeDelta::Max()) {
    // Schedule update task at the next policy timeout expiry.
    online_login_refresh_timer_->Start(
        FROM_HERE, min_delta,
        base::BindOnce(
            &UserOnlineSigninNotifier::CheckForPolicyEnforcedOnlineSignin,
            weak_ptr_factory_.GetWeakPtr()));
  }
}

void UserOnlineSigninNotifier::AddObserver(Observer* observer) {
  observer_list_.AddObserver(observer);
}

void UserOnlineSigninNotifier::RemoveObserver(Observer* observer) {
  observer_list_.RemoveObserver(observer);
}

void UserOnlineSigninNotifier::NotifyObservers(const AccountId& account_id) {
  for (auto& observer : observer_list_) {
    observer.OnOnlineSigninEnforced(account_id);
  }
}

}  // namespace ash


text:
package org.markysoft.vani.core.locating;

import java.util.List;

import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;

/**
 * Base class for all ElementLocator implementations. It replace the selenium's
 * structure to support additionally types and not only {@link WebElement}.
 *
 * @author Thomas
 *
 * @param <T>
 *            target type (eg.: WebElement)
 */
public interface VaniElementLocator<T> {
	/**
	 * This method will look only for one match and return it.
	 *
	 * @return returns found match or throws an exception when no matching is
	 *         available
	 * @throws NoSuchElementException
	 *             will be thrown if no matching can be found
	 */
	T findElement() throws NoSuchElementException;

	/**
	 * This method will look for multiple matches and returns it as a list.
	 *
	 * @return returns all matches as list or empty list if no matches are
	 *         available.
	 */
	List<T> findElements();

}


text:
package com.example.kaoru.multicheckboxdemo;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.Toast;

/**
 * Created by kaoru on 2015/06/27.
 */
public class MyAdapter extends BaseAdapter {
    private final MyModel mMyModel;

    public MyAdapter(MyModel myModel) {
        mMyModel = myModel;
    }

    @Override
    public int getCount() {
        return mMyModel.getCount();
    }

    @Override
    public MyModel.Entity getItem(int position) {
        return mMyModel.getItem(position);
    }

    @Override
    public long getItemId(int position) {
        return getItem(position).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_layout, parent, false);
        }

        if (convertView instanceof ListItemLayout) {
            configureView((ListItemLayout) convertView, getItem(position));
        }

        return convertView;
    }

    private void configureView(ListItemLayout layout, MyModel.Entity item) {
        layout.setText(item.getMessage());
        layout.setChecked(mMyModel.isChecked(item));
        layout.setOnCheckedChangeListener(new CheckBoxOnCheckedChangeListener(mMyModel, item));
    }

    private static class CheckBoxOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
        private final MyModel mMyModel;
        private final MyModel.Entity mItem;

        private CheckBoxOnCheckedChangeListener(MyModel myModel, MyModel.Entity item) {
            mMyModel = myModel;
            mItem = item;
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked && mMyModel.isCheckable(mItem)) {
                cancelCheckedStateChanges(buttonView);
                return;
            }

            mMyModel.setChecked(mItem, isChecked);
        }

        private void cancelCheckedStateChanges(final CompoundButton buttonView) {
            buttonView.post(new Runnable() {
                @Override
                public void run() {
                    Context context = buttonView.getContext();
                    buttonView.setChecked(false);
                    Toast.makeText(context, context.getString(R.string.error_message_of_checkbox, MyModel.getMaxCheckedCount()), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}


text:
package org.topology.bgp_ls.config.nodes;

import java.net.InetSocketAddress;

/**
 * Configuration for generic network server
 *
 * @author Rainer Bieniek (Rainer.Bieniek@web.de)
 *
 */
public interface ServerConfiguration {

    /**
     * Sets the port for the server
     */
    public void setPort (int port);

    /**
     * return the port for this server
     * @return
     */
    public int getPort();

	/**
	 * get the listen address with the port number
	 * @return
	 */
	public InetSocketAddress getListenAddress();

	/**
	 *
	 * @return
	 */
	@Override
	public boolean equals(Object other);

	/**
	 *
	 * @return
	 */
	@Override
	public int hashCode();
}


text:
package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	// Generate lists
	slice1 := generateSlice(5)
	slice2 := generateSlice(5)

	// Sort the lists
	slice1 = mergeSort(slice1)
	slice2 = mergeSort(slice2)

	// Print the lists
	fmt.Println("\nLists before merge:")
	fmt.Println("slice1: ", slice1)
	fmt.Println("slice2: ", slice2)

	fmt.Println("\nLists after merge:")
	fmt.Println(merge(slice1, slice2))

} // main

// Generates a list of 'size', filled with random numbers
func generateSlice(size int) []int {

	slice := make([]int, size, size)
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < size; i++ {
		slice[i] = rand.Intn(99999) - rand.Intn(99999)
	}
	return slice
} // generateSlice

// Runs MergeSort algorithm on a single list
func mergeSort(slice []int) []int {

	if len(slice) < 2 {
		return slice
	}
	mid := (len(slice)) / 2
	return merge(mergeSort(slice[:mid]), mergeSort(slice[mid:]))
} // mergeSort

// Merges left and right lists into newly created list
func merge(left, right []int) []int {

	// Set the 'size' of the resulting 'slice' after merging
	size, i, j := len(left)+len(right), 0, 0
	slice := make([]int, size, size)

	for k := 0; k < size; k++ {
		// If there are remaining elements of the 'right list' to put in the resulting 'slice', put them in.
		if i > len(left)-1 && j <= len(right)-1 {
			slice[k] = right[j]
			j++
			// If there are remaining elements of the 'left list' to put in the resulting 'slice', put them in.
		} else if j > len(right)-1 && i <= len(left)-1 {
			slice[k] = left[i]
			i++
			// If 'left list' element is smaller than 'right list' element, goes into the resulting 'slice'
		} else if left[i] < right[j] {
			slice[k] = left[i]
			i++
		} else {
			// If 'right list' element is smaller than 'left list' element, goes into the resulting 'slice'
			slice[k] = right[j]
			j++
		} // if - else if - else if - else

	} // for

	return slice
} // merge


text:
package com.mintminter.simplewidget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class SimpleButton extends LinearLayout {
    private Context mContext;

    private int nIconId = -1;
    private int nTextAppearanceId = -1;
    private String sText;
    private int nIconTintColor = Color.BLACK;
    private int nIconSize = 0;

    private LinearLayout mContainer;
    private ImageView mIcon;
    private TextView mText;

    public SimpleButton(Context context, AttributeSet attrs){
        super(context, attrs);

        mContext = context;
        TypedArray styledAttrs = context.obtainStyledAttributes(attrs,
                R.styleable.SimpleButton);
        nIconId = styledAttrs.getResourceId(R.styleable.SimpleButton_sb_icon, nIconId);
        nIconTintColor = styledAttrs.getColor(R.styleable.SimpleButton_sb_icon_tint, nIconTintColor);
        nIconSize = (int) styledAttrs.getDimension(R.styleable.SimpleButton_sb_icon_size, nIconSize);
        nTextAppearanceId = styledAttrs.getResourceId(R.styleable.SimpleButton_sb_text_appearance, nTextAppearanceId);
        sText = styledAttrs.getString(R.styleable.SimpleButton_sb_text);
        styledAttrs.recycle();

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.layout_simplebutton, this, true);

        mContainer = (LinearLayout) findViewById(R.id.simplebutton_container);
        mIcon = (ImageView) findViewById(R.id.simplebutton_icon);
        mText = (TextView) findViewById(R.id.simplebutton_text);

        if(nIconSize > 0){
            ViewGroup.LayoutParams iconLP = mIcon.getLayoutParams();
            iconLP.height = nIconSize;
            iconLP.width = nIconSize;
            mIcon.setLayoutParams(iconLP);

        }

        if(nIconId > 0){
            mIcon.setVisibility(VISIBLE);
            mIcon.setImageResource(nIconId);
        }else{
            mIcon.setVisibility(GONE);
        }

        mIcon.setColorFilter(nIconTintColor);

        if(!TextUtils.isEmpty(sText)){
            mText.setVisibility(VISIBLE);
            mText.setText(sText);
        }else{
            mText.setVisibility(GONE);
        }

        if(nTextAppearanceId > 0){
            mText.setTextAppearance(mContext, nTextAppearanceId);
        }

    }

    public void setText(String text){
        if(!TextUtils.isEmpty(text)){
            mText.setText(text);
            mText.setVisibility(VISIBLE);
        }else{
            mText.setVisibility(GONE);
        }

    }

    public void setText(Spanned text){
        if(text != null && !TextUtils.isEmpty(text.toString())) {
            mText.setText(text);
            mText.setVisibility(VISIBLE);
        }else{
            mText.setVisibility(GONE);
        }
    }
}


text:
<?php
namespace Jte;

use Jte\LogicProcessor\EvalLogicProcessor;
use Jte\Other\BlockDesigner;
use Jte\Parser\BlockSignatureParser;
use Jte\Parser\MarkupParser;
use Jte\Parser\SectionParser;
use Jte\Source\FileSource;
use Jte\TemplateDataSource\ParserTemplateDataSource;

class RendererTest extends \PHPUnit_Framework_TestCase
{
    public function testBasicRender()
    {
        $blockDesigner = new BlockDesigner();

        $logic = "replace('body')->with(param('body content')); replace('footer')->with(block('footer content', ['content' => 'footer_content']));";
        $logic2 = "replace('footer_place_holder')->with(param('content'));";
        $data = [
            'blocks' => [
                'main' =>
                    $blockDesigner->produceBlockNode('main', null, $logic, [
                        $blockDesigner->produceTextNode(''),
                        $blockDesigner->produceBlockNode('placeholder', null, null, [
                            $blockDesigner->produceTextNode(''),
                            $blockDesigner->produceTextNode(''),
                            $blockDesigner->produceBlockNode('body', null, null, [
                                $blockDesigner->produceTextNode('body text'),
                            ]),
                            $blockDesigner->produceBlockNode('footer', null, null, [
                                $blockDesigner->produceTextNode('no footer'),
                            ]),
                            $blockDesigner->produceTextNode(''),
                        ]),
                        $blockDesigner->produceTextNode(''),
                    ]),
                'footer content' =>
                    $blockDesigner->produceBlockNode('footer content', null, $logic2, [
                        $blockDesigner->produceBlockNode('footer_place_holder', null, null, [])
                    ])
            ]
        ];

        $templateFactory = $this->getMock('\StdClass', ['getTemplate']);

        $template = new Template('', $data);
        $templateFactory->expects($this->at(0))->method('getTemplate')->will($this->returnValue($template));
        $renderer = new Renderer($templateFactory, new EvalLogicProcessor());

        $text = $renderer->render('', 'main', ['body content' => 'another body content']);

        $this->assertContains('another body content', $text);
        $this->assertContains('', $text);
        $this->assertContains('footer_content', $text);
    }

    public function testExtends()
    {
        $blockDesigner = new BlockDesigner();

        $baseData = [
            'blocks' => [
                'main' =>
                    $blockDesigner->produceBlockNode('main', null, null, [
                        $blockDesigner->produceBlockNode('base', null, null, [
                            $blockDesigner->produceTextNode('base_value'),
                        ])
                    ]),
            ]
        ];

        $childData = [
            'boot' => "extend('base');",
            'blocks' => [
                'main' =>
                    $blockDesigner->produceBlockNode('main', null, "replace('child')->with(block('block1', ['param1' => 'param1value']));", [
                        $blockDesigner->produceBlockNode('base', null, null, [
                            $blockDesigner->produceTextNode('child_value1'),
                            $blockDesigner->produceBlockNode('parent'),
                        ]),
                        $blockDesigner->produceBlockNode('child', null, null, [
                            $blockDesigner->produceTextNode('undef'),
                        ])
                    ]),
                'block1' =>
                    $blockDesigner->produceBlockNode('block1', null, null, [
                        $blockDesigner->produceTextNode('defined1'),
                        $blockDesigner->produceBlockNode(null, 'param1'),
                    ]),
            ]
        ];

        $childChildData = [
            'boot' => "extend('child');",
            'blocks' => [
                'main' =>
                    $blockDesigner->produceBlockNode('main', null, "replace('child')->with('defined2');", [
                        $blockDesigner->produceBlockNode('base', null, null, [
                            $blockDesigner->produceBlockNode('parent'),
                            $blockDesigner->produceTextNode('child_value2'),
                            $blockDesigner->produceBlockNode('context_save', 'context_save', null, [
                                $blockDesigner->produceTextNode('undef3'),
                            ])
                        ]),
                        $blockDesigner->produceBlockNode('child', null, null, [
                            $blockDesigner->produceTextNode('undef2'),
                        ])
                    ]),

            ]
        ];

        $templateFactory = $this->getMock('\StdClass', ['getTemplate']);

        $childChildTemplate = new Template('', $childChildData);
        $childTemplate = new Template('', $childData);
        $baseTemplate = new Template('', $baseData);

        $templateFactory->expects($this->at(0))->method('getTemplate')->will($this->returnValue($childChildTemplate));
        $templateFactory->expects($this->at(1))->method('getTemplate')->will($this->returnValue($childTemplate));
        $templateFactory->expects($this->at(2))->method('getTemplate')->will($this->returnValue($baseTemplate));

        $renderer = new Renderer($templateFactory, new EvalLogicProcessor());

        $text = $renderer->render('', 'main', ['context_save' => 'defined3']);

        $this->assertContains('child_value1', $text);
        $this->assertContains('child_value2', $text);
        $this->assertContains('defined1', $text);
        $this->assertContains('defined2', $text);
        $this->assertContains('defined3', $text);
        $this->assertContains('base_value', $text);
        $this->assertContains('param1value', $text);
        $this->assertGreaterThan(strpos($text, 'child_value1'), strpos($text, 'base_value'));
        $this->assertGreaterThan(strpos($text, 'child_value1'), strpos($text, 'child_value2'));
    }

    public function testWhitespace()
    {
        $templateParser = new ParserTemplateDataSource(new FileSource(__DIR__ . '/Templates'), new SectionParser(), new MarkupParser(new BlockSignatureParser()));
        $template = new Template('', $templateParser->getTemplateData('whitespace1.jte'));

        $templateFactory = $this->getMock('\StdClass', ['getTemplate']);
        $templateFactory->expects($this->any())->method('getTemplate')->will($this->returnValue($template));
        $renderer = new Renderer($templateFactory, new EvalLogicProcessor());

        $result = $renderer->render($template, 'test1');
        $this->assertEquals('    hello!', $result);

        $result = $renderer->render($template, 'test2');
        $this->assertEquals("    hello1!\n    hello2!", $result);

        $result = $renderer->render($template, 'test3');
        $this->assertEquals("    hello1!\n    hello2!", $result);

        $result = $renderer->render($template, 'test4');
        $this->assertEquals("        hello1!\n    hello2!\n    hello2!", $result);

        $result = $renderer->render($template, 'test5');
        $this->assertEquals("        hello1!\n    hello2!\n    hello2!", $result);

        $result = $renderer->render($template, 'test6');
        $this->assertEquals("    hello1!\n    hello2!", $result);

        $result = $renderer->render($template, 'test7');
        $this->assertEquals("    hello1!\nhello1!\nhello1!\n    hello2!", $result);

        $result = $renderer->render($template, 'test8');
        $this->assertEquals("    hello1! hello1! hello1!\n    hello2!", $result);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:zdy="http://schemas.android.com/apk/res/com.example.mobilesafe"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        style="@style/TitleStyle"
        android:text="高级工具" />

    <TextView
        android:id="@+id/tv_address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:background="@drawable/button_zdy"
        android:drawableLeft="@android:drawable/ic_menu_camera"
        android:drawablePadding="10dp"
        android:textColor="@color/black"
        android:clickable="true"
        android:onClick="numberAddress"
        android:textSize="20sp"
        android:text="归属地查询" />

    <TextView
        android:id="@+id/tv_applock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:background="@drawable/button_zdy"
        android:drawablePadding="10dp"
        android:textColor="@color/black"
        android:clickable="true"
        android:onClick="applock"
        android:textSize="20sp"
        android:text="程序锁" />

</LinearLayout>