text:
using System.Collections.Generic;
using System.Drawing;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices.Tests.Common;
using Xunit;

#pragma warning disable 618

namespace System.Runtime.InteropServices.Tests
{
    [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "GetNativeVariantForObject() not supported on UWP")]
    public partial class GetNativeVariantForObjectTests
    {
        public static IEnumerable<object[]> GetNativeVariantForObject_RoundtrippingPrimitives_TestData()
        {
            yield return new object[] { null, VarEnum.VT_EMPTY, IntPtr.Zero };

            yield return new object[] { (sbyte)10, VarEnum.VT_I1, (IntPtr)10 };
            yield return new object[] { (short)10, VarEnum.VT_I2, (IntPtr)10 };
            yield return new object[] { 10, VarEnum.VT_I4, (IntPtr)10 };
            yield return new object[] { (long)10, VarEnum.VT_I8, (IntPtr)10 };
            yield return new object[] { (byte)10, VarEnum.VT_UI1, (IntPtr)10 };
            yield return new object[] { (ushort)10, VarEnum.VT_UI2, (IntPtr)10 };
            yield return new object[] { (uint)10, VarEnum.VT_UI4, (IntPtr)10 };
            yield return new object[] { (ulong)10, VarEnum.VT_UI8, (IntPtr)10 };

            yield return new object[] { true, VarEnum.VT_BOOL, (IntPtr)ushort.MaxValue };
            yield return new object[] { false, VarEnum.VT_BOOL, IntPtr.Zero };

            yield return new object[] { 10m, VarEnum.VT_DECIMAL, (IntPtr)10 };

            // Well known types.
            DateTime dateTime = new DateTime(1899, 12, 30).AddDays(20);
            yield return new object[] { dateTime, VarEnum.VT_DATE, (IntPtr)(-1) };

            yield return new object[] { DBNull.Value, VarEnum.VT_NULL, IntPtr.Zero };
            yield return new object[] { DBNull.Value, VarEnum.VT_NULL, IntPtr.Zero };

            // Arrays.
            yield return new object[] { new sbyte[] { 10, 11, 12 }, (VarEnum)8208, (IntPtr)(-1) };
            yield return new object[] { new short[] { 10, 11, 12 }, (VarEnum)8194, (IntPtr)(-1) };
            yield return new object[] { new int[] { 10, 11, 12 }, (VarEnum)8195, (IntPtr)(-1) };
            yield return new object[] { new long[] { 10, 11, 12 }, (VarEnum)8212, (IntPtr)(-1) };
            yield return new object[] { new byte[] { 10, 11, 12 }, (VarEnum)8209, (IntPtr)(-1) };
            yield return new object[] { new ushort[] { 10, 11, 12 }, (VarEnum)8210, (IntPtr)(-1) };
            yield return new object[] { new uint[] { 10, 11, 12 }, (VarEnum)8211, (IntPtr)(-1) };
            yield return new object[] { new ulong[] { 10, 11, 12 }, (VarEnum)8213, (IntPtr)(-1) };

            yield return new object[] { new bool[] { true, false }, (VarEnum)8203, (IntPtr)(-1) };

            yield return new object[] { new float[] { 10, 11, 12 }, (VarEnum)8196, (IntPtr)(-1) };
            yield return new object[] { new double[] { 10, 11, 12 }, (VarEnum)8197, (IntPtr)(-1) };
            yield return new object[] { new decimal[] { 10m, 11m, 12m }, (VarEnum)8206, (IntPtr)(-1) };

            yield return new object[] { new object[] { 10, 11, 12 }, (VarEnum)8204, (IntPtr)(-1) };
            yield return new object[] { new string[] { "a", "b", "c" }, (VarEnum)8200, (IntPtr)(-1) };

            yield return new object[] { new TimeSpan[] { new TimeSpan(10) }, (VarEnum)8228, (IntPtr)(-1) };
            yield return new object[] { new int[,] { { 10 }, { 11 }, { 12 } }, (VarEnum)8195, (IntPtr)(-1) };

            // Objects.
            var nonGenericClass = new NonGenericClass();
            yield return new object[] { nonGenericClass, VarEnum.VT_DISPATCH, (IntPtr)(-1) };

            var valueType = new StructWithValue { Value = 10 };
            yield return new object[] { valueType, VarEnum.VT_RECORD, (IntPtr)(-1) };

            var genericClass = new GenericClass<string>();
            yield return new object[] { new object[] { nonGenericClass, genericClass, null }, (VarEnum)8204, (IntPtr)(-1) };

            yield return new object[] { new object[] { valueType, null }, (VarEnum)8204, (IntPtr)(-1) };

            // Delegate.
            MethodInfo method = typeof(GetNativeVariantForObjectTests).GetMethod(nameof(NonGenericMethod));
            Delegate d = method.CreateDelegate(typeof(NonGenericDelegate));
            yield return new object[] { d, VarEnum.VT_DISPATCH, (IntPtr)(-1) };
        }

        [Theory]
        [MemberData(nameof(GetNativeVariantForObject_RoundtrippingPrimitives_TestData))]
        [PlatformSpecific(TestPlatforms.Windows)]
        [ActiveIssue(31077, ~TargetFrameworkMonikers.NetFramework)]
        public void GetNativeVariantForObject_RoundtrippingPrimitives_Success(object primitive, VarEnum expectedVarType, IntPtr expectedValue)
        {
            GetNativeVariantForObject_ValidObject_Success(primitive, expectedVarType, expectedValue, primitive);
        }

        [Fact]
        [PlatformSpecific(TestPlatforms.Windows)]
        public void GetNativeVariantForObject_TypeMissing_Success()
        {
            // This cannot be in the test data as XUnit uses MethodInfo.Invoke to call test methods and
            // Type.Missing is handled specially for parameters with default values.
            GetNativeVariantForObject_RoundtrippingPrimitives_Success(Type.Missing, VarEnum.VT_ERROR, (IntPtr)(-1));
        }

        public static IEnumerable<object[]> GetNativeVariantForObject_NonRoundtrippingPrimitives_TestData()
        {
            // GetNativeVariantForObject supports char, but internally recognizes it the same as ushort
            // because the native variant type uses mscorlib type VarEnum to store what type it contains.
            // To get back the original char, use GetObjectForNativeVariant<ushort> and cast to char.
            yield return new object[] { 'a', VarEnum.VT_UI2, (IntPtr)'a', (ushort)97 };
            yield return new object[] { new char[] { 'a', 'b', 'c' }, (VarEnum)8210, (IntPtr)(-1), new ushort[] { 'a', 'b', 'c' } };

            // IntPtr/UIntPtr objects are converted to int/uint respectively.
            yield return new object[] { (IntPtr)10, VarEnum.VT_INT, (IntPtr)10, 10 };
            yield return new object[] { (UIntPtr)10, VarEnum.VT_UINT, (IntPtr)10, (uint)10 };

            yield return new object[] { new IntPtr[] { (IntPtr)10, (IntPtr)11, (IntPtr)12 }, (VarEnum)8212, (IntPtr)(-1), new long[] { 10, 11, 12 } };
            yield return new object[] { new UIntPtr[] { (UIntPtr)10, (UIntPtr)11, (UIntPtr)12 }, (VarEnum)8213, (IntPtr)(-1), new ulong[] { 10, 11, 12 } };

            // DateTime is converted to VT_DATE which is offset from December 30, 1899.
            DateTime earlyDateTime = new DateTime(1899, 12, 30);
            yield return new object[] { earlyDateTime, VarEnum.VT_DATE, IntPtr.Zero, new DateTime(1899, 12, 30) };

            // Wrappers.
            yield return new object[] { new UnknownWrapper(10), VarEnum.VT_UNKNOWN, IntPtr.Zero, null };
            if (!PlatformDetection.IsNetCore)
            {
                yield return new object[] { new DispatchWrapper(10), VarEnum.VT_DISPATCH, IntPtr.Zero, null };
            }
            else
            {
                Assert.Throws<PlatformNotSupportedException>(() => new DispatchWrapper(10));
            }
            yield return new object[] { new ErrorWrapper(10), VarEnum.VT_ERROR, (IntPtr)10, 10 };
            yield return new object[] { new CurrencyWrapper(10), VarEnum.VT_CY, (IntPtr)100000, 10m };
            yield return new object[] { new BStrWrapper("a"), VarEnum.VT_BSTR, (IntPtr)(-1), "a" };
            yield return new object[] { new BStrWrapper(null), VarEnum.VT_BSTR, IntPtr.Zero, null };

            yield return new object[] { new UnknownWrapper[] { new UnknownWrapper(null), new UnknownWrapper(10) }, (VarEnum)8205, (IntPtr)(-1), new object[] { null, 10 }  };
            if (!PlatformDetection.IsNetCore)
            {
                yield return new object[] { new DispatchWrapper[] { new DispatchWrapper(null), new DispatchWrapper(10) }, (VarEnum)8201, (IntPtr)(-1), new object[] { null, 10 } };
            }
            else
            {
                Assert.Throws<PlatformNotSupportedException>(() => new DispatchWrapper(10));
            }
            yield return new object[] { new ErrorWrapper[] { new ErrorWrapper(10) }, (VarEnum)8202, (IntPtr)(-1), new uint[] { 10 } };
            yield return new object[] { new CurrencyWrapper[] { new CurrencyWrapper(10) }, (VarEnum)8198, (IntPtr)(-1), new decimal[] { 10 } };
            yield return new object[] { new BStrWrapper[] { new BStrWrapper("a"), new BStrWrapper(null), new BStrWrapper("c") }, (VarEnum)8200, (IntPtr)(-1), new string[] { "a", null, "c" } };

            // Objects.
            var nonGenericClass = new NonGenericClass();
            yield return new object[] { new NonGenericClass[] { nonGenericClass, null }, (VarEnum)8201, (IntPtr)(-1), new object[] { nonGenericClass, null } };

            var genericClass = new GenericClass<string>();
            yield return new object[] { new GenericClass<string>[] { genericClass, null }, (VarEnum)8205, (IntPtr)(-1), new object[] { genericClass, null } };

            var nonGenericStruct = new NonGenericStruct();
            yield return new object[] { new NonGenericStruct[] { nonGenericStruct }, (VarEnum)8228, (IntPtr)(-1), new NonGenericStruct[] { nonGenericStruct } };

            var classWithInterface = new ClassWithInterface();
            var structWithInterface = new StructWithInterface();
            yield return new object[] { new ClassWithInterface[] { classWithInterface, null }, (VarEnum)8201, (IntPtr)(-1), new object[] { classWithInterface, null } };
            yield return new object[] { new StructWithInterface[] { structWithInterface }, (VarEnum)8228, (IntPtr)(-1), new StructWithInterface[] { structWithInterface } };
            yield return new object[] { new NonGenericInterface[] { classWithInterface, structWithInterface, null }, (VarEnum)8201, (IntPtr)(-1), new object[] { classWithInterface, structWithInterface, null } };

            // Enums.
            yield return new object[] { SByteEnum.Value2, VarEnum.VT_I1, (IntPtr)1, (sbyte)1 };
            yield return new object[] { Int16Enum.Value2, VarEnum.VT_I2, (IntPtr)1, (short)1 };
            yield return new object[] { Int32Enum.Value2, VarEnum.VT_I4, (IntPtr)1, 1 };
            yield return new object[] { Int64Enum.Value2, VarEnum.VT_I8, (IntPtr)1, (long)1 };
            yield return new object[] { ByteEnum.Value2, VarEnum.VT_UI1, (IntPtr)1, (byte)1 };
            yield return new object[] { UInt16Enum.Value2, VarEnum.VT_UI2, (IntPtr)1, (ushort)1 };
            yield return new object[] { UInt32Enum.Value2, VarEnum.VT_UI4, (IntPtr)1, (uint)1 };
            yield return new object[] { UInt64Enum.Value2, VarEnum.VT_UI8, (IntPtr)1, (ulong)1 };

            yield return new object[] { new SByteEnum[] { SByteEnum.Value2 }, (VarEnum)8208, (IntPtr)(-1), new sbyte[] { 1 } };
            yield return new object[] { new Int16Enum[] { Int16Enum.Value2 }, (VarEnum)8194, (IntPtr)(-1), new short[] { 1 } };
            yield return new object[] { new Int32Enum[] { Int32Enum.Value2 }, (VarEnum)8195, (IntPtr)(-1), new int[] { 1 } };
            yield return new object[] { new Int64Enum[] { Int64Enum.Value2 }, (VarEnum)8212, (IntPtr)(-1), new long[] { 1 } };
            yield return new object[] { new ByteEnum[] { ByteEnum.Value2 }, (VarEnum)8209, (IntPtr)(-1), new byte[] { 1 } };
            yield return new object[] { new UInt16Enum[] { UInt16Enum.Value2 }, (VarEnum)8210, (IntPtr)(-1), new ushort[] { 1 } };
            yield return new object[] { new UInt32Enum[] { UInt32Enum.Value2 }, (VarEnum)8211, (IntPtr)(-1), new uint[] { 1 } };
            yield return new object[] { new UInt64Enum[] { UInt64Enum.Value2 }, (VarEnum)8213, (IntPtr)(-1), new ulong[] { 1 } };

            // Color is converted to uint.
            yield return new object[] { Color.FromArgb(10), VarEnum.VT_UI4, (IntPtr)655360, (uint)655360 };
        }

        [Theory]
        [MemberData(nameof(GetNativeVariantForObject_NonRoundtrippingPrimitives_TestData))]
        [PlatformSpecific(TestPlatforms.Windows)]
        [ActiveIssue(31077, ~TargetFrameworkMonikers.NetFramework)]
        public void GetNativeVariantForObject_ValidObject_Success(object primitive, VarEnum expectedVarType, IntPtr expectedValue, object expectedRoundtripValue)
        {
            var v = new Variant();
            IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v));
            try
            {
                Marshal.GetNativeVariantForObject(primitive, pNative);

                Variant result = Marshal.PtrToStructure<Variant>(pNative);
                Assert.Equal(expectedVarType, (VarEnum)result.vt);
                if (expectedValue != (IntPtr)(-1))
                {
                    Assert.Equal(expectedValue, result.bstrVal);
                }
                else
                {
                    Assert.NotEqual((IntPtr)(-1), result.bstrVal);
                    Assert.NotEqual(IntPtr.Zero, result.bstrVal);
                }

                // Make sure it roundtrips.
                Assert.Equal(expectedRoundtripValue, Marshal.GetObjectForNativeVariant(pNative));
            }
            finally
            {
                Marshal.FreeHGlobal(pNative);
            }
        }

        [Theory]
        [InlineData("")]
        [InlineData("99")]
        [PlatformSpecific(TestPlatforms.Windows)]
        public void GetNativeVariantForObject_String_Success(string obj)
        {
            var v = new Variant();
            IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v));
            try
            {
                Marshal.GetNativeVariantForObject(obj, pNative);

                Variant result = Marshal.PtrToStructure<Variant>(pNative);
                try
                {
                    Assert.Equal(VarEnum.VT_BSTR, (VarEnum)result.vt);
                    Assert.Equal(obj, Marshal.PtrToStringBSTR(result.bstrVal));

                    object o = Marshal.GetObjectForNativeVariant(pNative);
                    Assert.Equal(obj, o);
                }
                finally
                {
                    Marshal.FreeBSTR(result.bstrVal);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(pNative);
            }
        }

        [Theory]
        [InlineData(3.14)]
        [PlatformSpecific(TestPlatforms.Windows)]
        public unsafe void GetNativeVariantForObject_Double_Success(double obj)
        {
            var v = new Variant();
            IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v));
            try
            {
                Marshal.GetNativeVariantForObject(obj, pNative);

                Variant result = Marshal.PtrToStructure<Variant>(pNative);
                Assert.Equal(VarEnum.VT_R8, (VarEnum)result.vt);
                Assert.Equal(*((IntPtr*)&obj), result.bstrVal);

                object o = Marshal.GetObjectForNativeVariant(pNative);
                Assert.Equal(obj, o);
            }
            finally
            {
                Marshal.FreeHGlobal(pNative);
            }
        }

        [Theory]
        [InlineData(3.14f)]
        [PlatformSpecific(TestPlatforms.Windows)]
        public unsafe void GetNativeVariantForObject_Float_Success(float obj)
        {
            var v = new Variant();
            IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v));
            try
            {
                Marshal.GetNativeVariantForObject(obj, pNative);

                Variant result = Marshal.PtrToStructure<Variant>(pNative);
                Assert.Equal(VarEnum.VT_R4, (VarEnum)result.vt);
                Assert.Equal(*((IntPtr*)&obj), result.bstrVal);

                object o = Marshal.GetObjectForNativeVariant(pNative);
                Assert.Equal(obj, o);
            }
            finally
            {
                Marshal.FreeHGlobal(pNative);
            }
        }

        [Fact]
        [PlatformSpecific(TestPlatforms.AnyUnix)]
        public void GetNativeVariantForObject_Unix_ThrowsPlatformNotSupportedException()
        {
            Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetNativeVariantForObject(new object(), IntPtr.Zero));
            Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetNativeVariantForObject(1, IntPtr.Zero));
        }

        [Fact]
        [PlatformSpecific(TestPlatforms.Windows)]
        public void GetNativeVariantForObject_ZeroPointer_ThrowsArgumentNullException()
        {
            AssertExtensions.Throws<ArgumentNullException>("pDstNativeVariant", () => Marshal.GetNativeVariantForObject(new object(), IntPtr.Zero));
            AssertExtensions.Throws<ArgumentNullException>("pDstNativeVariant", () => Marshal.GetNativeVariantForObject<int>(1, IntPtr.Zero));
        }

        public static IEnumerable<object[]> GetNativeVariantForObject_GenericObject_TestData()
        {
            yield return new object[] { new GenericClass<string>() };
            yield return new object[] { new GenericStruct<string>() };
        }

        [Theory]
        [MemberData(nameof(GetNativeVariantForObject_GenericObject_TestData))]
        [PlatformSpecific(TestPlatforms.Windows)]
        public void GetNativeVariantForObject_GenericObject_ThrowsArgumentException(object obj)
        {
            AssertExtensions.Throws<ArgumentException>("obj", () => Marshal.GetNativeVariantForObject(obj, (IntPtr)1));
            AssertExtensions.Throws<ArgumentException>("obj", () => Marshal.GetNativeVariantForObject<object>(obj, (IntPtr)1));
        }

        public static IEnumerable<object[]> GetNativeVariant_NotInteropCompatible_TestData()
        {
            yield return new object[] { new TimeSpan(10) };

            yield return new object[] { new object[] { new GenericStruct<string>() } };

            yield return new object[] { new GenericStruct<string>[0]};
            yield return new object[] { new GenericStruct<string>[] { new GenericStruct<string>() } };

            yield return new object[] { new Color[0] };
            yield return new object[] { new Color[] { Color.FromArgb(10) } };
        }

        [Theory]
        [MemberData(nameof(GetNativeVariant_NotInteropCompatible_TestData))]
        [PlatformSpecific(TestPlatforms.Windows)]
        [ActiveIssue(31077, ~TargetFrameworkMonikers.NetFramework)]
        public void GetNativeVariant_NotInteropCompatible_ThrowsArgumentException(object obj)
        {
            var v = new Variant();
            IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v));
            try
            {
                AssertExtensions.Throws<ArgumentException>(null, () => Marshal.GetNativeVariantForObject(obj, pNative));
                AssertExtensions.Throws<ArgumentException>(null, () => Marshal.GetNativeVariantForObject<object>(obj, pNative));
            }
            finally
            {
                Marshal.FreeHGlobal(pNative);
            }
        }

        [Fact]
        [PlatformSpecific(TestPlatforms.Windows)]
        public void GetNativeVariant_InvalidArray_ThrowsSafeArrayTypeMismatchException()
        {
            var v = new Variant();
            IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v));
            try
            {
                Assert.Throws<SafeArrayTypeMismatchException>(() => Marshal.GetNativeVariantForObject(new int[][] { }, pNative));
                Assert.Throws<SafeArrayTypeMismatchException>(() => Marshal.GetNativeVariantForObject<object>(new int[][] { }, pNative));
            }
            finally
            {
                Marshal.FreeHGlobal(pNative);
            }
        }

        public static IEnumerable<object[]> GetNativeVariant_VariantWrapper_TestData()
        {
            yield return new object[] { new VariantWrapper(null) };
            yield return new object[] { new VariantWrapper[] { new VariantWrapper(null) } };
        }

        [Theory]
        [MemberData(nameof(GetNativeVariant_VariantWrapper_TestData))]
        [PlatformSpecific(TestPlatforms.Windows)]
        public void GetNativeVariant_VariantWrapper_ThrowsArgumentException(object obj)
        {
            var v = new Variant();
            IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v));
            try
            {
                AssertExtensions.Throws<ArgumentException>(null, () => Marshal.GetNativeVariantForObject(obj, pNative));
                AssertExtensions.Throws<ArgumentException>(null, () => Marshal.GetNativeVariantForObject<object>(obj, pNative));
            }
            finally
            {
                Marshal.FreeHGlobal(pNative);
            }
        }

        public static IEnumerable<object[]> GetNativeVariant_HandleObject_TestData()
        {
            yield return new object[] { new FakeSafeHandle() };
            yield return new object[] { new FakeCriticalHandle() };

            yield return new object[] { new FakeSafeHandle[] { new FakeSafeHandle() } };
            yield return new object[] { new FakeCriticalHandle[] { new FakeCriticalHandle() } };
        }

        [Theory]
        [MemberData(nameof(GetNativeVariant_HandleObject_TestData))]
        [PlatformSpecific(TestPlatforms.Windows)]
        public void GetNativeVariant_HandleObject_ThrowsArgumentException(object obj)
        {
            var v = new Variant();
            IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v));
            try
            {
                AssertExtensions.Throws<ArgumentException>(null, () => Marshal.GetNativeVariantForObject(obj, pNative));
                AssertExtensions.Throws<ArgumentException>(null, () => Marshal.GetNativeVariantForObject<object>(obj, pNative));
            }
            finally
            {
                Marshal.FreeHGlobal(pNative);
            }
        }

        [Fact]
        [PlatformSpecific(TestPlatforms.Windows)]
        public static void GetNativeVariantForObject_CantCastToObject_ThrowsInvalidCastException()
        {
            // While GetNativeVariantForObject supports taking chars, GetObjectForNativeVariant will
            // never return a char. The internal type is ushort, as mentioned above. This behavior
            // is the same on ProjectN and Desktop CLR.
            var v = new Variant();
            IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v));
            try
            {
                Marshal.GetNativeVariantForObject<char>('a', pNative);
                Assert.Throws<InvalidCastException>(() => Marshal.GetObjectForNativeVariant<char>(pNative));
            }
            finally
            {
                Marshal.FreeHGlobal(pNative);
            }
        }

#if !netstandard // TODO: Enable for netstandard2.1
        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetNative))]
        [PlatformSpecific(TestPlatforms.Windows)]
        public void GetNativeVariantForObject_ObjectNotCollectible_ThrowsNotSupportedException()
        {
            AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.RunAndCollect);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module");
            TypeBuilder typeBuilder = moduleBuilder.DefineType("Type");
            Type type = typeBuilder.CreateType();

            object o = Activator.CreateInstance(type);

            var v = new Variant();
            IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v));
            try
            {
                Assert.Throws<NotSupportedException>(() => Marshal.GetNativeVariantForObject(o, pNative));
            }
            finally
            {
                Marshal.FreeHGlobal(pNative);
            }
        }
#endif

        public struct StructWithValue
        {
            public int Value;
        }

        public class ClassWithInterface : NonGenericInterface { }
        public struct StructWithInterface : NonGenericInterface { }

        public enum SByteEnum : sbyte { Value1, Value2 }
        public enum Int16Enum : short { Value1, Value2 }
        public enum Int32Enum : int { Value1, Value2 }
        public enum Int64Enum : long { Value1, Value2 }

        public enum ByteEnum : byte { Value1, Value2 }
        public enum UInt16Enum : ushort { Value1, Value2 }
        public enum UInt32Enum : uint { Value1, Value2 }
        public enum UInt64Enum : ulong { Value1, Value2 }

        public static void NonGenericMethod(int i) { }
        public delegate void NonGenericDelegate(int i);

        public class FakeSafeHandle : SafeHandle
        {
            public FakeSafeHandle() : base(IntPtr.Zero, false) { }

            public override bool IsInvalid => throw new NotImplementedException();

            protected override bool ReleaseHandle() => throw new NotImplementedException();

            protected override void Dispose(bool disposing) { }
        }

        public class FakeCriticalHandle : CriticalHandle
        {
            public FakeCriticalHandle() : base(IntPtr.Zero) { }

            public override bool IsInvalid => true;

            protected override bool ReleaseHandle() => throw new NotImplementedException();

            protected override void Dispose(bool disposing) { }
        }
    }
}

#pragma warning restore 618


text:
import Debug from 'debug';
import App from './app';

var attachElement = document.body;

var state = {
    table: {
        title: 'React Test',
        users: [
            {
                id: 1,
                firstName: "Mark",
                lastName: "Otto",
                userName: "@mdo",
                isChecked: false
            },
            {
                id: 2,
                firstName: "Jacob",
                lastName: "Thornton",
                userName: "@fat",
                isChecked: false
            },
            {
                id: 3,
                firstName: "Larry",
                lastName: "the Bird",
                userName: "@twitter",
                isChecked: false
            }
        ]
    }
};

var app;

Debug.enable('myApp*');

// Create new app and attach to element
app = new App({
    state: state
});

app.renderToDOM(attachElement);

redpajama_set_name: RedPajamaGithub


text:
CREATE USER 'test'@'localhost' IDENTIFIED BY '12345';
CREATE DATABASE wikiDatabase;
GRANT ALL PRIVILEGES ON wikiDatabase.* TO 'test'@'localhost';


text:
/* jshint esnext:true */
/*
 *
 *  Weather extension for GNOME Shell preferences
 *  - Creates a widget to set the preferences of the weather extension
 *
 * Copyright (C) 2012 - 2015
 *     Canek Peláez <canek@ciencias.unam.mx>,
 *     Christian METZLER <neroth@xeked.com>,
 *     Jens Lody <jens@jenslody.de>,
 *
 * This file is part of gnome-shell-extension-openweather.
 *
 * gnome-shell-extension-openweather is free software: you can
 * redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * gnome-shell-extension-openweather is distributed in the hope that it
 * will be useful, but WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gnome-shell-extension-openweather.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 */
const Gtk = imports.gi.Gtk;
const GObject = imports.gi.GObject;
const Gettext = imports.gettext.domain('gnome-shell-extension-openweather');
const _ = Gettext.gettext;
const Soup = imports.gi.Soup;

const Lang = imports.lang;
const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();
const Config = imports.misc.config;
const Convenience = Me.imports.convenience;

const EXTENSIONDIR = Me.dir.get_path();

const OPENWEATHER_SETTINGS_SCHEMA = 'org.gnome.shell.extensions.openweather';
const OPENWEATHER_PROVIDER_KEY = 'weather-provider';
const OPENWEATHER_UNIT_KEY = 'unit';
const OPENWEATHER_PRESSURE_UNIT_KEY = 'pressure-unit';
const OPENWEATHER_WIND_SPEED_UNIT_KEY = 'wind-speed-unit';
const OPENWEATHER_WIND_DIRECTION_KEY = 'wind-direction';
const OPENWEATHER_CITY_KEY = 'city';
const OPENWEATHER_ACTUAL_CITY_KEY = 'actual-city';
const OPENWEATHER_TRANSLATE_CONDITION_KEY = 'translate-condition';
const OPENWEATHER_USE_SYMBOLIC_ICONS_KEY = 'use-symbolic-icons';
const OPENWEATHER_USE_TEXT_ON_BUTTONS_KEY = 'use-text-on-buttons';
const OPENWEATHER_SHOW_TEXT_IN_PANEL_KEY = 'show-text-in-panel';
const OPENWEATHER_POSITION_IN_PANEL_KEY = 'position-in-panel';
const OPENWEATHER_SHOW_COMMENT_IN_PANEL_KEY = 'show-comment-in-panel';
const OPENWEATHER_SHOW_COMMENT_IN_FORECAST_KEY = 'show-comment-in-forecast';
const OPENWEATHER_REFRESH_INTERVAL_CURRENT = 'refresh-interval-current';
const OPENWEATHER_REFRESH_INTERVAL_FORECAST = 'refresh-interval-forecast';
const OPENWEATHER_CENTER_FORECAST_KEY = 'center-forecast';
const OPENWEATHER_DAYS_FORECAST = 'days-forecast';
const OPENWEATHER_DECIMAL_PLACES = 'decimal-places';
const OPENWEATHER_OWM_API_KEY = 'appid';
const OPENWEATHER_FC_API_KEY = 'appid-fc';

//URL
const OPENWEATHER_URL_BASE = 'https://open.mapquestapi.com/nominatim/v1/';
const OPENWEATHER_URL_FIND = OPENWEATHER_URL_BASE + 'search.php';
const OPENWEATHER_URL_REVERSE = OPENWEATHER_URL_BASE + 'reverse.php';

let _httpSession;

let mCities = null;

const WeatherPrefsWidget = new GObject.Class({
    Name: 'OpenWeatherExtension.Prefs.Widget',
    GTypeName: 'OpenWeatherExtensionPrefsWidget',
    Extends: Gtk.Box,

    _init: function(params) {
        this.parent(params);

        this.initWindow();

        this.refreshUI();

        this.add(this.MainWidget);
    },

    Window: new Gtk.Builder(),

    initWindow: function() {
        mCities = null;

        this.Window.add_from_file(EXTENSIONDIR + "/weather-settings.ui");

        this.MainWidget = this.Window.get_object("main-widget");
        this.treeview = this.Window.get_object("tree-treeview");
        this.liststore = this.Window.get_object("tree-liststore");
        this.editWidget = this.Window.get_object("edit-widget");
        this.editName = this.Window.get_object("edit-name");
        this.editCoord = this.Window.get_object("edit-coord");
        this.searchWidget = this.Window.get_object("search-widget");
        this.searchMenu = this.Window.get_object("search-menu");
        this.searchName = this.Window.get_object("search-name");

        this.searchName.connect("icon-release", Lang.bind(this, this.clearEntry));
        this.editName.connect("icon-release", Lang.bind(this, this.clearEntry));
        this.editCoord.connect("icon-release", Lang.bind(this, this.clearEntry));

        this.Window.get_object("tree-toolbutton-add").connect("clicked", Lang.bind(this, function() {
            this.searchWidget.show_all();
        }));

        this.Window.get_object("tree-toolbutton-remove").connect("clicked", Lang.bind(this, this.removeCity));

        this.Window.get_object("tree-toolbutton-edit").connect("clicked", Lang.bind(this, this.editCity));

        this.Window.get_object("treeview-selection").connect("changed", Lang.bind(this, function(selection) {
            this.selectionChanged(selection);
        }));

        this.Window.get_object("button-edit-cancel").connect("clicked", Lang.bind(this, this.editCancel));

        this.Window.get_object("button-edit-save").connect("clicked", Lang.bind(this, this.editSave));

        this.Window.get_object("button-search-cancel").connect("clicked", Lang.bind(this, function() {
            this.searchWidget.hide();
        }));

        this.Window.get_object("button-search-save").connect("clicked", Lang.bind(this, this.searchSave));

        this.Window.get_object("button-search-find").connect("clicked", Lang.bind(this, function() {

            let location = this.searchName.get_text().trim();
            if (location === "")
                return 0;
            let params = {
                format: 'json',
                addressdetails: '1',
                q: location
            };
            this.loadJsonAsync(OPENWEATHER_URL_FIND, params, Lang.bind(this, function() {
                if (!arguments[0])
                    return 0;
                let newCity = arguments[0];

                if (Number(newCity.length) < 1)
                    return 0;

                this.clearSearchMenu();

                var m = {};
                for (var i in newCity) {

                    let cityText = newCity[i].display_name;
                    let cityCoord = "[" + newCity[i].lat + "," + newCity[i].lon + "]";

                    let item = new Gtk.MenuItem({
                        label: cityText + " " + cityCoord
                    });
                    item.connect("activate", Lang.bind(this, this.onActivateItem));
                    this.searchMenu.append(item);
                }
                this.searchMenu.show_all();
                this.searchMenu.popup(null, null, Lang.bind(this, this.placeSearchMenu), 0, this.searchName);
                return 0;
            }));
            return 0;
        }));

        let column = new Gtk.TreeViewColumn();
        this.treeview.append_column(column);

        let renderer = new Gtk.CellRendererText();
        column.pack_start(renderer, null);

        column.set_cell_data_func(renderer, function() {
            arguments[1].markup = arguments[2].get_value(arguments[3], 0);
        });

        let theObjects = this.Window.get_objects();
        for (let i in theObjects) {
            let name = theObjects[i].get_name ? theObjects[i].get_name() : 'dummy';
            if (this[name] !== undefined) {
                if (theObjects[i].class_path()[1].indexOf('GtkEntry') != -1)
                    this.initEntry(theObjects[i]);
                else if (theObjects[i].class_path()[1].indexOf('GtkComboBoxText') != -1)
                    this.initComboBox(theObjects[i]);
                else if (theObjects[i].class_path()[1].indexOf('GtkSwitch') != -1)
                    this.initSwitch(theObjects[i]);
                this.configWidgets.push([theObjects[i], name]);
            }
        }
    },

    clearEntry: function() {
        arguments[0].set_text("");
    },

    onActivateItem: function() {
        this.searchName.set_text(arguments[0].get_label());
    },

    placeSearchMenu: function() {
        let[gx, gy, gw, gh] = this.searchName.get_window().get_geometry();
        let[px, py] = this.searchName.get_window().get_position();
        return [gx + px, gy + py + this.searchName.get_allocated_height()];
    },

    clearSearchMenu: function() {
        let children = this.searchMenu.get_children();
        for (let i in children) {
            this.searchMenu.remove(children[i]);
        }
    },

    initEntry: function(theEntry) {
        let name = theEntry.get_name();
        theEntry.text = this[name];
        if (this[name].length != 32)
            theEntry.set_icon_from_icon_name(Gtk.PositionType.LEFT, 'dialog-warning');

        theEntry.connect("notify::text", Lang.bind(this, function() {
            let key = arguments[0].text;
            this[name] = key;
            if (key.length == 32)
                theEntry.set_icon_from_icon_name(Gtk.PositionType.LEFT, '');
            else
                theEntry.set_icon_from_icon_name(Gtk.PositionType.LEFT, 'dialog-warning');
        }));
    },

    initComboBox: function(theComboBox) {
        let name = theComboBox.get_name();
        theComboBox.connect("changed", Lang.bind(this, function() {
            this[name] = arguments[0].active;
        }));
    },

    initSwitch: function(theSwitch) {
        let name = theSwitch.get_name();
        theSwitch.connect("notify::active", Lang.bind(this, function() {
            this[name] = arguments[0].active;
        }));
    },

    refreshUI: function() {
        this.MainWidget = this.Window.get_object("main-widget");
        this.treeview = this.Window.get_object("tree-treeview");
        this.liststore = this.Window.get_object("tree-liststore");

        this.Window.get_object("tree-toolbutton-remove").sensitive = Boolean(this.city.length);
        this.Window.get_object("tree-toolbutton-edit").sensitive = Boolean(this.city.length);

        if (mCities != this.city) {
            if (this.liststore !== undefined)
                this.liststore.clear();

            if (this.city.length > 0) {
                let city = String(this.city).split(" && ");

                if (city && typeof city == "string")
                    city = [city];

                let current = this.liststore.get_iter_first();

                for (let i in city) {
                    current = this.liststore.append();
                    this.liststore.set_value(current, 0, this.extractLocation(city[i]));
                }
            }

            mCities = this.city;
        }

        this.changeSelection();

        let config = this.configWidgets;
        for (let i in config) {
            if (config[i][0].active != this[config[i][1]])
                config[i][0].active = this[config[i][1]];
        }
    },

    configWidgets: [],

    selectionChanged: function(select) {
        let a = select.get_selected_rows(this.liststore)[0][0];

        if (a !== undefined)
            if (this.actual_city != parseInt(a.to_string()))
                this.actual_city = parseInt(a.to_string());
    },

    removeCity: function() {
        let city = this.city.split(" && ");
        if (!city.length)
            return 0;
        let ac = this.actual_city;
        let textDialog = _("Remove %s ?").format(this.extractLocation(city[ac]));
        let dialog = new Gtk.Dialog({
            title: ""
        });
        let label = new Gtk.Label({
            label: textDialog
        });
        label.margin_bottom = 12;

        dialog.set_border_width(12);
        dialog.set_modal(1);
        dialog.set_resizable(0);
        //dialog.set_transient_for(***** Need parent Window *****);

        dialog.add_button(Gtk.STOCK_NO, 0);
        let d = dialog.add_button(Gtk.STOCK_YES, 1);

        d.set_can_default(true);
        dialog.set_default(d);

        let dialog_area = dialog.get_content_area();
        dialog_area.pack_start(label, 0, 0, 0);
        dialog.connect("response", Lang.bind(this, function(w, response_id) {
            if (response_id) {
                if (city.length === 0)
                    city = [];

                if (city.length > 0 && typeof city != "object")
                    city = [city];

                if (city.length > 0)
                    city.splice(ac, 1);

                if (city.length > 1)
                    this.city = city.join(" && ");
                else if (city[0])
                    this.city = city[0];
                else
                    this.city = "";
            }
            dialog.hide();
            return 0;
        }));

        dialog.show_all();
        return 0;
    },

    editCity: function() {
        let city = this.city.split(" && ");
        if (!city.length)
            return 0;
        let ac = this.actual_city;
        this.editName.set_text(this.extractLocation(city[ac]));
        this.editCoord.set_text(this.extractCoord(city[ac]));
        this.editWidget.show_all();
        return 0;
    },

    searchSave: function() {
        let cityText = this.searchName.get_text().split(/\[/)[0];
        let coord = this.searchName.get_text().split(/\[/)[1].split(/\]/)[0];

        if (this.city)
            this.city = this.city + " && " + coord + ">" + cityText;
        else
            this.city = coord + ">" + cityText;

        this.searchWidget.hide();
        return 0;
    },

    editSave: function() {
        let theCity = this.city.split(" && ");

        if (theCity.length === 0)
            return 0;
        if (theCity.length > 0 && typeof theCity != "object")
            theCity = [theCity];

        let ac = this.actual_city;
        let location = this.editName.get_text();
        let coord = this.editCoord.get_text();
        theCity[ac] = coord + ">" + location;

        if (theCity.length > 1)
            this.city = theCity.join(" && ");
        else if (theCity[0])
            this.city = theCity[0];

        this.editWidget.hide();

        this.actual_city = ac;

        return 0;
    },

    editCancel: function() {
        this.editName.set_text("");
        this.editCoord.set_text("");
        this.editWidget.hide();
    },

    changeSelection: function() {
        let path = this.actual_city;
        if (arguments[0])
            path = arguments[0];
        path = Gtk.TreePath.new_from_string(String(path));
        this.treeview.get_selection().select_path(path);
    },

    loadJsonAsync: function(url, params, fun, id) {
        if (_httpSession === undefined) {
            _httpSession = new Soup.Session();
        }

        let here = this;

        let message = Soup.form_request_new_from_hash('GET', url, params);

        if (this.asyncSession === undefined)
            this.asyncSession = {};

        if (this.asyncSession[id] !== undefined && this.asyncSession[id]) {
            _httpSession.abort();
            this.asyncSession[id] = 0;
        }

        this.asyncSession[id] = 1;
        _httpSession.queue_message(message, function(_httpSession, message) {
            here.asyncSession[id] = 0;
            if (!message.response_body.data) {
                fun.call(here, 0);
                return 0;
            }

            try {
                let jp = JSON.parse(message.response_body.data);
                fun.call(here, jp);
            } catch (e) {
                fun.call(here, 0);
                return 0;
            }
            return 0;
        });
    },

    loadConfig: function() {
        this.Settings = Convenience.getSettings(OPENWEATHER_SETTINGS_SCHEMA);
        this.Settings.connect("changed", Lang.bind(this, function() {
            this.refreshUI();
        }));
    },

    get weather_provider() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_enum(OPENWEATHER_PROVIDER_KEY);
    },

    set weather_provider(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_enum(OPENWEATHER_PROVIDER_KEY, v);
    },

    get units() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_enum(OPENWEATHER_UNIT_KEY);
    },

    set units(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_enum(OPENWEATHER_UNIT_KEY, v);
    },

    get pressure_unit() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_enum(OPENWEATHER_PRESSURE_UNIT_KEY);
    },

    set pressure_unit(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_enum(OPENWEATHER_PRESSURE_UNIT_KEY, v);
    },

    get wind_speed_unit() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_enum(OPENWEATHER_WIND_SPEED_UNIT_KEY);
    },

    set wind_speed_unit(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_enum(OPENWEATHER_WIND_SPEED_UNIT_KEY, v);
    },

    get wind_direction() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_boolean(OPENWEATHER_WIND_DIRECTION_KEY);
    },

    set wind_direction(v) {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.set_boolean(OPENWEATHER_WIND_DIRECTION_KEY, v);
    },

    get city() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_string(OPENWEATHER_CITY_KEY);
    },

    set city(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_string(OPENWEATHER_CITY_KEY, v);
    },

    get actual_city() {
        if (!this.Settings)
            this.loadConfig();
        let a = this.Settings.get_int(OPENWEATHER_ACTUAL_CITY_KEY);
        let citys = this.city.split(" && ");

        if (citys && typeof citys == "string")
            citys = [citys];

        let l = citys.length - 1;

        if (a < 0)
            a = 0;

        if (l < 0)
            l = 0;

        if (a > l)
            a = l;

        return a;
    },

    set actual_city(a) {
        if (!this.Settings)
            this.loadConfig();
        let citys = this.city.split(" && ");

        if (citys && typeof citys == "string")
            citys = [citys];

        let l = citys.length - 1;

        if (a < 0)
            a = 0;

        if (l < 0)
            l = 0;

        if (a > l)
            a = l;

        this.Settings.set_int(OPENWEATHER_ACTUAL_CITY_KEY, a);
    },

    get translate_condition() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_boolean(OPENWEATHER_TRANSLATE_CONDITION_KEY);
    },

    set translate_condition(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_boolean(OPENWEATHER_TRANSLATE_CONDITION_KEY, v);
    },

    get icon_type() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_boolean(OPENWEATHER_USE_SYMBOLIC_ICONS_KEY);
    },

    set icon_type(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_boolean(OPENWEATHER_USE_SYMBOLIC_ICONS_KEY, v);
    },

    get use_text_on_buttons() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_boolean(OPENWEATHER_USE_TEXT_ON_BUTTONS_KEY);
    },

    set use_text_on_buttons(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_boolean(OPENWEATHER_USE_TEXT_ON_BUTTONS_KEY, v);
    },

    get text_in_panel() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_boolean(OPENWEATHER_SHOW_TEXT_IN_PANEL_KEY);
    },

    set text_in_panel(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_boolean(OPENWEATHER_SHOW_TEXT_IN_PANEL_KEY, v);
    },

    get position_in_panel() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_enum(OPENWEATHER_POSITION_IN_PANEL_KEY);
    },

    set position_in_panel(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_enum(OPENWEATHER_POSITION_IN_PANEL_KEY, v);
    },

    get comment_in_panel() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_boolean(OPENWEATHER_SHOW_COMMENT_IN_PANEL_KEY);
    },

    set comment_in_panel(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_boolean(OPENWEATHER_SHOW_COMMENT_IN_PANEL_KEY, v);
    },

    get comment_in_forecast() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_boolean(OPENWEATHER_SHOW_COMMENT_IN_FORECAST_KEY);
    },

    set comment_in_forecast(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_boolean(OPENWEATHER_SHOW_COMMENT_IN_FORECAST_KEY, v);
    },

    get refresh_interval_current() {
        if (!this.Settings)
            this.loadConfig();
        let v = this.Settings.get_int(OPENWEATHER_REFRESH_INTERVAL_CURRENT);
        return ((v >= 600) ? v : 600);
    },

    set refresh_interval_current(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_int(OPENWEATHER_REFRESH_INTERVAL_CURRENT, ((v >= 600) ? v : 600));
    },

    get refresh_interval_forecast() {
        if (!this.Settings)
            this.loadConfig();
        let v = this.Settings.get_int(OPENWEATHER_REFRESH_INTERVAL_FORECAST);
        return ((v >= 600) ? v : 600);
    },

    set refresh_interval_forecast(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_int(OPENWEATHER_REFRESH_INTERVAL_FORECAST, ((v >= 600) ? v : 600));
    },

    get center_forecast() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_boolean(OPENWEATHER_CENTER_FORECAST_KEY);
    },

    set center_forecast(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_boolean(OPENWEATHER_CENTER_FORECAST_KEY, v);
    },

    get days_forecast() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_int(OPENWEATHER_DAYS_FORECAST) - 2;
    },

    set days_forecast(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_int(OPENWEATHER_DAYS_FORECAST, v + 2);
    },

    get decimal_places() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_int(OPENWEATHER_DECIMAL_PLACES);
    },

    set decimal_places(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_int(OPENWEATHER_DECIMAL_PLACES, v);
    },

    get appid() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_string(OPENWEATHER_OWM_API_KEY);
    },

    set appid(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_string(OPENWEATHER_OWM_API_KEY, v);
    },

    get appid_fc() {
        if (!this.Settings)
            this.loadConfig();
        return this.Settings.get_string(OPENWEATHER_FC_API_KEY);
    },

    set appid_fc(v) {
        if (!this.Settings)
            this.loadConfig();
        this.Settings.set_string(OPENWEATHER_FC_API_KEY, v);
    },

    extractLocation: function(a) {
        if (a.search(">") == -1)
            return _("Invalid city");
        return a.split(">")[1];
    },

    extractCoord: function(a) {
        if (a.search(">") == -1)
            return 0;
        return a.split(">")[0];
    }
});

function init() {
    Convenience.initTranslations('gnome-shell-extension-openweather');
}

function buildPrefsWidget() {
    let widget = new WeatherPrefsWidget();
    widget.show_all();
    return widget;
}


text:
package org.geolocate.webservices.svcv2;

import java.util.ArrayList;
import java.util.List;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;

/**
 *
Java class for Georef_Result_Set complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="Georef_Result_Set">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="EngineVersion" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="NumResults" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="ExecutionTimems" type="{http://www.w3.org/2001/XMLSchema}double"/>
 *         <element name="ResultSet" type="{http://geo-locate.org/webservices/}Georef_Result" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Georef_Result_Set", propOrder = {
    "engineVersion",
    "numResults",
    "executionTimems",
    "resultSet"
})
public class GeorefResultSet {

    @XmlElement(name = "EngineVersion")
    protected String engineVersion;
    @XmlElement(name = "NumResults")
    protected int numResults;
    @XmlElement(name = "ExecutionTimems")
    protected double executionTimems;
    @XmlElement(name = "ResultSet")
    protected List<GeorefResult> resultSet;

    /**
     * Gets the value of the engineVersion property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getEngineVersion() {
        return engineVersion;
    }

    /**
     * Sets the value of the engineVersion property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setEngineVersion(String value) {
        this.engineVersion = value;
    }

    /**
     * Gets the value of the numResults property.
     *
     */
    public int getNumResults() {
        return numResults;
    }

    /**
     * Sets the value of the numResults property.
     *
     */
    public void setNumResults(int value) {
        this.numResults = value;
    }

    /**
     * Gets the value of the executionTimems property.
     *
     */
    public double getExecutionTimems() {
        return executionTimems;
    }

    /**
     * Sets the value of the executionTimems property.
     *
     */
    public void setExecutionTimems(double value) {
        this.executionTimems = value;
    }

    /**
     * Gets the value of the resultSet property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the Jakarta XML Binding object.
     * This is why there is not a set method for the resultSet property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getResultSet().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link GeorefResult }
     *
     *
     */
    public List<GeorefResult> getResultSet() {
        if (resultSet == null) {
            resultSet = new ArrayList<GeorefResult>();
        }
        return this.resultSet;
    }

}


text:
var express = require("express");
var bodyParser = require('body-parser');
var cheeseToastie = require("../index.js");

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Start the CheeseToastie API
console.log(__dirname);
cheeseToastie.start(__dirname, app);

// Start the server
var server = app.listen('3000', function () {
  console.log("Started cheese toastie test app 🧀 🍞");
});


text:
package org.apache.hc.core5.http.nio.entity;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.StandardCharsets;
import java.util.Set;

import org.apache.hc.core5.annotation.Contract;
import org.apache.hc.core5.annotation.ThreadingBehavior;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.nio.AsyncEntityProducer;
import org.apache.hc.core5.http.nio.DataStreamChannel;
import org.apache.hc.core5.http.nio.StreamChannel;
import org.apache.hc.core5.util.Args;

/**
 * Abstract text entity content producer.
 *
 * @since 5.0
 */
@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL)
public abstract class AbstractCharAsyncEntityProducer implements AsyncEntityProducer {

    private static final CharBuffer EMPTY = CharBuffer.wrap(new char[0]);

    enum State { ACTIVE, FLUSHING, END_STREAM }

    private final ByteBuffer bytebuf;
    private final int fragmentSizeHint;
    private final ContentType contentType;
    private final CharsetEncoder charsetEncoder;

    private volatile State state;

    public AbstractCharAsyncEntityProducer(
            final int bufferSize,
            final int fragmentSizeHint,
            final ContentType contentType) {
        Args.positive(bufferSize, "Buffer size");
        this.fragmentSizeHint = fragmentSizeHint >= 0 ? fragmentSizeHint : 0;
        this.bytebuf = ByteBuffer.allocate(bufferSize);
        this.contentType = contentType;
        Charset charset = contentType != null ? contentType.getCharset() : null;
        if (charset == null) {
            charset = StandardCharsets.US_ASCII;
        }
        this.charsetEncoder = charset.newEncoder();
        this.state = State.ACTIVE;
    }

    private void flush(final StreamChannel<ByteBuffer> channel) throws IOException {
        if (bytebuf.position() > 0) {
            bytebuf.flip();
            channel.write(bytebuf);
            bytebuf.compact();
        }
    }

    final int writeData(final StreamChannel<ByteBuffer> channel, final CharBuffer src) throws IOException {

        final int chunk = src.remaining();
        if (chunk == 0) {
            return 0;
        }

        final int p = src.position();
        final CoderResult result = charsetEncoder.encode(src, bytebuf, false);
        if (result.isError()) {
            result.throwException();
        }

        if (!bytebuf.hasRemaining() || bytebuf.position() >= fragmentSizeHint) {
            flush(channel);
        }

        return src.position() - p;
    }

    final void streamEnd(final StreamChannel<ByteBuffer> channel) throws IOException {
        if (state == State.ACTIVE) {
            state = State.FLUSHING;
            if (!bytebuf.hasRemaining()) {
                flush(channel);
            }

            final CoderResult result = charsetEncoder.encode(EMPTY, bytebuf, true);
            if (result.isError()) {
                result.throwException();
            }
            final CoderResult result2 = charsetEncoder.flush(bytebuf);
            if (result2.isError()) {
                result.throwException();
            } else if (result.isUnderflow()) {
                flush(channel);
                if (bytebuf.position() == 0) {
                    state = State.END_STREAM;
                    channel.endStream();
                }
            }
        }

    }

    /**
     * Returns the number of bytes immediately available for output.
     * This method can be used as a hint to control output events
     * of the underlying I/O session.
     *
     * @return the number of bytes immediately available for output
     */
    protected abstract int availableData();

    /**
     * Triggered to signal the ability of the underlying char channel
     * to accept more data. The data producer can choose to write data
     * immediately inside the call or asynchronously at some later point.
     * <p>
     * {@link StreamChannel} passed to this method is threading-safe.
     *
     * @param channel the data channel capable to accepting more data.
     */
    protected abstract void produceData(StreamChannel<CharBuffer> channel) throws IOException;

    @Override
    public final String getContentType() {
        return contentType != null ? contentType.toString() : null;
    }

    @Override
    public String getContentEncoding() {
        return null;
    }

    @Override
    public long getContentLength() {
        return -1;
    }

    @Override
    public boolean isChunked() {
        return false;
    }

    @Override
    public Set<String> getTrailerNames() {
        return null;
    }

    @Override
    public final int available() {
        if (state == State.ACTIVE) {
            return availableData();
        } else {
            synchronized (bytebuf) {
                return bytebuf.position();
            }
        }
    }

    @Override
    public final void produce(final DataStreamChannel channel) throws IOException {
        synchronized (bytebuf) {
            if (state == State.ACTIVE) {
                produceData(new StreamChannel<CharBuffer>() {

                    @Override
                    public int write(final CharBuffer src) throws IOException {
                        Args.notNull(src, "Buffer");
                        synchronized (bytebuf) {
                            return writeData(channel, src);
                        }
                    }

                    @Override
                    public void endStream() throws IOException {
                        synchronized (bytebuf) {
                            streamEnd(channel);
                        }
                    }

                });
            }
            if (state == State.FLUSHING) {
                final CoderResult result = charsetEncoder.flush(bytebuf);
                if (result.isError()) {
                    result.throwException();
                } else if (result.isOverflow()) {
                    flush(channel);
                } else if (result.isUnderflow()) {
                    flush(channel);
                    if (bytebuf.position() == 0) {
                        state = State.END_STREAM;
                        channel.endStream();
                    }
                }

            }

        }
    }

    @Override
    public void releaseResources() {
        state = State.ACTIVE;
        charsetEncoder.reset();
    }

}


text:
- Linear Search is used to find an item in a list.
- The items do not necessarily have to be sorted like in Binary Search.
- To search for an item, start at the beginning and continue searching until either the end of the list is reached or the item is found.

## Algorithm
1. position <- 0
2. found <- False
3. while position < len(List) and not found:
4. 	if List[position] = item:
5.		found <- True
6.	position <- position + 1

## Time Complexity

The Worst-case time Complexity of Linear Search is O(n).


text:
<!DOCTYPE html>

    <meta name="project_path" value="/java/docs/reference/_project.yaml">
    <meta name="book_path" value="/java/docs/reference/cloud.google.com/java/latest/_book.yaml">

    {% verbatim %}

Interface LongRunningRecognizeRequestOrBuilder (2.0.0)

public interface LongRunningRecognizeRequestOrBuilder extends MessageOrBuilder

Implements

    MessageOrBuilder

Methods

getAudio()

public abstract RecognitionAudio getAudio()

 Required. The audio data to be recognized.

 .google.cloud.speech.v1p1beta1.RecognitionAudio audio = 2 [(.google.api.field_behavior) = REQUIRED];

  Returns

        Type
        Description

        RecognitionAudio

The audio.

getAudioOrBuilder()

public abstract RecognitionAudioOrBuilder getAudioOrBuilder()

 Required. The audio data to be recognized.

 .google.cloud.speech.v1p1beta1.RecognitionAudio audio = 2 [(.google.api.field_behavior) = REQUIRED];

  Returns

        Type
        Description

        RecognitionAudioOrBuilder

getConfig()

public abstract RecognitionConfig getConfig()

 Required. Provides information to the recognizer that specifies how to
 process the request.

 .google.cloud.speech.v1p1beta1.RecognitionConfig config = 1 [(.google.api.field_behavior) = REQUIRED];

  Returns

        Type
        Description

        RecognitionConfig

The config.

getConfigOrBuilder()

public abstract RecognitionConfigOrBuilder getConfigOrBuilder()

 Required. Provides information to the recognizer that specifies how to
 process the request.

 .google.cloud.speech.v1p1beta1.RecognitionConfig config = 1 [(.google.api.field_behavior) = REQUIRED];

  Returns

        Type
        Description

        RecognitionConfigOrBuilder

getOutputConfig()

public abstract TranscriptOutputConfig getOutputConfig()

 Optional. Specifies an optional destination for the recognition results.

 .google.cloud.speech.v1p1beta1.TranscriptOutputConfig output_config = 4 [(.google.api.field_behavior) = OPTIONAL];

  Returns

        Type
        Description

        TranscriptOutputConfig

The outputConfig.

getOutputConfigOrBuilder()

public abstract TranscriptOutputConfigOrBuilder getOutputConfigOrBuilder()

 Optional. Specifies an optional destination for the recognition results.

 .google.cloud.speech.v1p1beta1.TranscriptOutputConfig output_config = 4 [(.google.api.field_behavior) = OPTIONAL];

  Returns

        Type
        Description

        TranscriptOutputConfigOrBuilder

hasAudio()

public abstract boolean hasAudio()

 Required. The audio data to be recognized.

 .google.cloud.speech.v1p1beta1.RecognitionAudio audio = 2 [(.google.api.field_behavior) = REQUIRED];

  Returns

        Type
        Description

        boolean

Whether the audio field is set.

hasConfig()

public abstract boolean hasConfig()

 Required. Provides information to the recognizer that specifies how to
 process the request.

 .google.cloud.speech.v1p1beta1.RecognitionConfig config = 1 [(.google.api.field_behavior) = REQUIRED];

  Returns

        Type
        Description

        boolean

Whether the config field is set.

hasOutputConfig()

public abstract boolean hasOutputConfig()

 Optional. Specifies an optional destination for the recognition results.

 .google.cloud.speech.v1p1beta1.TranscriptOutputConfig output_config = 4 [(.google.api.field_behavior) = OPTIONAL];

  Returns

        Type
        Description

        boolean

Whether the outputConfig field is set.

    {% endverbatim %}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2019 The Android Open Source Project

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

          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.
-->
<resources>

  <string name="application_name">ExoPlayer SurfaceControl demo</string>
  <string name="no_output_label">No output</string>
  <string name="full_screen_label">Full screen</string>
  <string name="new_activity_label">New activity</string>

</resources>


text:
from flask import Flask

import pots

app = Flask(__name__)
pot = pots.RaspCoffeePot('coffee', 10, 24)

@app.route('/teapot', methods=['GET'])
def get():
    return pot.get()

@app.route('/teapot', methods=['BREW', 'POST'])
def brew():
    return pot.brew()

@app.route('/teapot', methods=['WHEN'])
def when():
    return pot.when()

if __name__ == '__main__':
    app.run(port=8081)


text:
<?php

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype;

return function (ContainerConfigurator $c) {
    $di = $c->services()->defaults()
        ->tag('baz');
    $di->load(Prototype::class.'\\', '../Prototype')
        ->autoconfigure()
        ->exclude('../Prototype/{OtherDir,BadClasses}')
        ->factory('f')
        ->deprecate('%service_id%')
        ->args([0])
        ->args([1])
        ->autoconfigure(false)
        ->tag('foo')
        ->parent('foo');
    $di->set('foo')->lazy()->abstract();
    $di->get(Prototype\Foo::class)->lazy(false);
};


text:
$(function() {
    $('button').click(function() {
        var user = $('#txtUsername').val();
        var pass = $('#txtPassword').val();
        $.ajax({
            url: '/signUpUser',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response) {
                console.log(response);
            },
            error: function(error) {
                console.log(error);
            }
        });
    });
});


text:
package org.dasein.cloud.network;

import org.dasein.cloud.CloudException;
import org.dasein.cloud.CloudProvider;
import org.dasein.cloud.InternalException;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * A reference to a compute firewall represented by {@link Firewall}. Because a compute firewall is often
 * referenced by an account number/firewall ID pair, this class helps maintain the reference without the need
 * to fully load firewall instances.
 *
Created by George Reese: 2/9/14 10:16 AM

 * @author George Reese
 * @since 2014.03
 * @version 2014.03 initial version in support of data cluster firewalls
 */
public class FirewallReference implements Comparable<FirewallReference> {
    /**
     * Constructs a firewall reference from the specified owner ID/firewall ID pair
     * @param ownerId the owner of the target firewall
     * @param firewallId the unique ID of the target firewall
     * @return a firewall reference that refers to the specified owner ID/firewall ID pair
     */
    static public @Nonnull FirewallReference getInstance(@Nonnull String ownerId, @Nonnull String firewallId) {
        FirewallReference r = new FirewallReference();

        r.providerOwnerId = ownerId;
        r.providerFirewallId = firewallId;
        return r;
    }

    private String providerOwnerId;
    private String providerFirewallId;

    private FirewallReference() { }

    @Override
    public int compareTo(@Nullable FirewallReference other) {
        if( other == null ) {
            return -1;
        }
        return toString().compareTo(other.toString());
    }

    @Override
    public boolean equals(@Nullable Object other) {
        if( other == null ) {
            return false;
        }
        if( other == this ) {
            return true;
        }
        if( !getClass().getName().equals(other.getClass().getName()) ) {
            return false;
        }
        FirewallReference r = (FirewallReference)other;

        return (providerOwnerId.equals(r.providerOwnerId) && providerFirewallId.equals(r.providerFirewallId));
    }

    /**
     * @return the supposedly unique ID of the firewall being referenced
     */
    public @Nonnull String getProviderFirewallId() {
        return providerFirewallId;
    }

    /**
     * @return the account owner of the firewall being referenced
     */
    public @Nonnull String getProviderOwnerId() {
        return providerOwnerId;
    }

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

    @Override
    public @Nonnull String toString() {
        return (providerOwnerId + "/" + providerFirewallId);
    }
}


text:
<house>
    <floor id="1" name="Ground">
        <room name="Living" id="1">
           <tv id="1" type="LG"></tv>
        </room>
    </floor>
    <config listen_port="50000" rfm12_port="COM15" background_delay="10000">
    </config>
    <plugins>
        <plugin class="net.geekgrandad.plugin.JeenodeControl" type="Jeenode">
            <interface name="InfraredControl"></interface>
        </plugin>
    </plugins>
</house>


text:
  Domnon-lès-Dieuze est
       un village
       situé dans le département de Moselle en Lorraine. Elle totalisait 106 habitants en 2008.

Le parc d'habitations, à Domnon-lès-Dieuze, se décomposait en 2011 en quatre appartements et 50 maisons soit
 un marché plutôt équilibré.

À proximité de Domnon-lès-Dieuze sont localisées les communes de
Bidestroff à 2 km, 134 habitants,
Bassing située à 1 km, 133 habitants,
Cutting située à 1 km, 132 habitants,
Marimont-lès-Bénestroff localisée à 4 km, 48 habitants,
Molring située à 2 km, onze habitants,
Zommange localisée à 4 km, 36 habitants,
 entre autres. De plus, Domnon-lès-Dieuze est située à seulement 28 km de Saint-Avold.

Si vous envisagez de venir habiter à Domnon-lès-Dieuze, vous pourrez facilement trouver une maison à acheter.


text:
__all__ = []

import bot
import comandos
import config
import inline
import install
import mensagens
import metodos


text:
.class public interface abstract Lcom/android/settings/fingerprint/FingerprintRemoveSidecar$Listener;
.super Ljava/lang/Object;
.source "FingerprintRemoveSidecar.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/settings/fingerprint/FingerprintRemoveSidecar;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "Listener"
.end annotation

# virtual methods
.method public abstract onRemovalError(Landroid/hardware/fingerprint/Fingerprint;ILjava/lang/CharSequence;)V
.end method

.method public abstract onRemovalSucceeded(Landroid/hardware/fingerprint/Fingerprint;)V
.end method


text:
package com.stackmob.sdkapi.http.request;

import com.stackmob.sdkapi.http.Header;

import java.net.MalformedURLException;
import java.util.Set;

public class DeleteRequest extends HttpRequestWithoutBody {
    public DeleteRequest(String url, Set<Header> headers) throws MalformedURLException {
        super(url, headers);
    }

    public DeleteRequest(String url) throws MalformedURLException {
        super(url, HttpRequest.EmptyHeaders);
    }
}


text:
package trainstation.exception;

/**
 * Exception to be thrown when route representation is incorrectly passed in to the app
 *
 * @author Jijo Wilson (jiwilson@expedia.com)
 */
public class InvalidRouteRepresentationException extends RuntimeException {

    public InvalidRouteRepresentationException(String message) {
        super(message);
    }

    public InvalidRouteRepresentationException(String message, Throwable throwable) {
        super(message, throwable);
    }
}


text:
using BoundedLayers.Models;
using Xunit;

namespace BoundedLayers.Test
{
	public class SolutionTest
	{
		[Fact]
		public void ValidateSolution()
		{
			Layers.Configure(Expression.Type.RegularExpression)
				.Layer(@"BoundedLayers.*").HasNoReferences()
				.Component(@"BoundedLayers").HasNoReferences()
				.Component(@".*\.Test").References(@"BoundedLayers")
				.Validate(@"../../../../BoundedLayers.sln")
				.Assert();
		}
	}
}


text:
package org.tud.inf.st.mbt.ulang.guigraph;

import org.eclipse.core.resources.IMarker;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.LineBorder;
import org.eclipse.draw2d.RectangleFigure;
import org.eclipse.draw2d.RoundedRectangle;
import org.eclipse.draw2d.Shape;
import org.eclipse.draw2d.XYLayout;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.tud.inf.st.mbt.core.CorePackage;
import org.tud.inf.st.mbt.emf.graphicaleditor.basics.MultiLabeled;
import org.tud.inf.st.mbt.emf.graphicaleditor.beauty.BeautyBorder;
import org.tud.inf.st.mbt.emf.ui.MBTConstants;

public class CATransitionFigure extends RoundedRectangle implements
		MultiLabeled {
	private static GuigraphPackage GGP = GuigraphPackage.eINSTANCE;
	public static final EAttribute AC = GGP
			.getConditionActionTransition_ApplicationConditionText();
	public static final EAttribute UE = GGP
			.getConditionActionTransition_ActionsText();
	public static final EAttribute NOTE = CorePackage.eINSTANCE
			.getAbstractModelElement_Note();

	private Label ac_label, ue_label, note_label, time_label;
	private Shape ac, ue, note, time;
	private LineBorder border;
	private String toolTip;

	private int severity = -1;

	public CATransitionFigure(String toolTip) {
		this.toolTip = toolTip;

		setLayoutManager(new XYLayout());

		setCornerDimensions(new Dimension(10, 10));

		setBackgroundColor(ColorConstants.white);

		setBorder(border = new LineBorder());

		setToolTip(new Label());

		ac_label = new Label();
		ue_label = new Label();
		note_label = new Label();
		time_label = new Label();

		ac_label.setForegroundColor(ColorConstants.black);
		ue_label.setForegroundColor(ColorConstants.white);
		note_label.setForegroundColor(ColorConstants.black);
		time_label.setForegroundColor(ColorConstants.white);

		add(ac = new RoundedRectangle());
		add(ue = new RectangleFigure());
		add(note = new RectangleFigure());
		add(time = new RectangleFigure());

		((RectangleFigure) ue).setLineWidth(0);
		ac.setBorder(new BeautyBorder());

		add(ac_label);
		add(ue_label);
		add(note_label);
		add(time_label);

		time.setBackgroundColor(ColorConstants.darkBlue);

		setProblem(-1, null, AC);
		setProblem(-1, null, UE);
		setProblem(-1, null, NOTE);
		setTerminates(false);
	}

	public void setTerminates(boolean term) {
		border.setWidth(term ? 3 : 1);
		border.setColor(term ? ColorConstants.red : ColorConstants.gray);
	}

	public void setTime(TimingType t, long min, long max) {

		if (t.equals(TimingType.DELAY_UNTIL_START)) {
			time_label.setText(">=" + (min < 0 ? 0 : min));
		} else if (t.equals(TimingType.INTERVAL)) {
			time_label.setText("[" + (min < 0 ? 0 : min) + ".."
					+ (max < min || max == Long.MAX_VALUE ? "*" : max) + "]");
		}
	}

	public void setActive(boolean active) {
		border.setWidth(active ? 5 : 1);
		border.setColor(active ? ColorConstants.blue : ColorConstants.gray);
	}

	public void setProblem(int severity, String text, EStructuralFeature f) {
		if (severity == IMarker.SEVERITY_WARNING) {
			if (this.severity != IMarker.SEVERITY_ERROR)
				this.severity = severity;
		} else
			this.severity = severity;

		Figure fig = null;
		if (f.equals(AC))
			fig = ac;
		if (f.equals(UE))
			fig = ue;
		if (f.equals(NOTE))
			fig = note;

		switch (this.severity) {
		case IMarker.SEVERITY_WARNING: {
			fig.setBackgroundColor(ColorConstants.yellow);
			break;
		}
		case IMarker.SEVERITY_ERROR: {
			fig.setBackgroundColor(ColorConstants.red);
			break;
		}
		default: {
			if (f.equals(AC))
				fig.setBackgroundColor(GGColors.c1);
			if (f.equals(UE))
				fig.setBackgroundColor(GGColors.c3);
			if (f.equals(NOTE))
				fig.setBackgroundColor(GGColors.c0);
		}
		}

		Label tt = (Label) getToolTip();

		if (text == null)
			tt.setText(toolTip);
		else {
			tt.setText(toolTip + "\n" + text);
		}
	}

	public void paintFigure(Graphics graphics) {
		Dimension size = getBounds().getSize();

		Dimension upper = new Dimension(size.width, MBTConstants.IS_MOBILE ? 0
				: 17);

		Dimension lower = new Dimension(size.width, 20);
		Dimension middle = new Dimension(size.width, size.height - upper.height
				- lower.height);

		Point topLeft = new Point(0, 0);

		setConstraint(ac, new Rectangle(new Point(topLeft), new Dimension(
				(int) (upper.width * 0.7), upper.height)));
		setConstraint(ac_label, new Rectangle(new Point(topLeft),
				new Dimension((int) (upper.width * 0.7), upper.height)));

		setConstraint(time, new Rectangle(new Point(
				(int) (upper.width * 0.7) + 1, topLeft.y), new Dimension(
				(int) (upper.width * 0.3) - 1, upper.height)));
		setConstraint(time_label, new Rectangle(new Point(
				(int) (upper.width * 0.7) + 1, topLeft.y), new Dimension(
				(int) (upper.width * 0.3) - 1, upper.height)));

		setConstraint(ue,
				new Rectangle(
						new Point(topLeft).getTranslated(0, upper.height),
						middle));
		setConstraint(ue_label,
				new Rectangle(
						new Point(topLeft).getTranslated(0, upper.height),
						middle));
		setConstraint(
				note,
				new Rectangle(new Point(topLeft).getTranslated(0, upper.height
						+ middle.height), lower));
		setConstraint(
				note_label,
				new Rectangle(new Point(topLeft).getTranslated(0, upper.height
						+ middle.height), lower));

		ac_label.invalidate();
		ac.invalidate();
		ue_label.invalidate();
		ue.invalidate();
		note_label.invalidate();
		note.invalidate();
		time_label.invalidate();
		time.invalidate();
	}

	@Override
	public EStructuralFeature getFeatureOn(Point on) {
		Label[] labels = new Label[] { ac_label, ue_label, note_label };
		EStructuralFeature[] features = new EStructuralFeature[] { AC, UE, NOTE };
		for (int i = 0; i < labels.length; i++) {
			Point p = new Point(on);
			labels[i].translateToRelative(p);
			if (labels[i].containsPoint(p))
				return features[i];
		}

		return null;
	}

	@Override
	public Label getLabel(EStructuralFeature key) {
		if (key.equals(AC))
			return ac_label;
		if (key.equals(UE))
			return ue_label;
		if (key.equals(NOTE))
			return note_label;
		return null;
	}

}


text:
<?php

/* FrontendBundle:Default:about.html.twig */
class __TwigTemplate_47a69aaf7cbda69156a2d430b0c4d8ad extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("FrontendBundle::layout.html.twig");

        $this->blocks = array(
            'stylesheets' => array($this, 'block_stylesheets'),
            'body' => array($this, 'block_body'),
            'javascripts' => array($this, 'block_javascripts'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "FrontendBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_stylesheets($context, array $blocks = array())
    {
        // line 4
        $this->displayParentBlock("stylesheets", $context, $blocks);
        echo "
<link rel=\"stylesheet\" href=\"";
        // line 5
        echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("css/jquery.bxslider.css"), "html", null, true);
        echo "\">
";
    }

    // line 8
    public function block_body($context, array $blocks = array())
    {
        // line 9
        echo "

               env, $this->env->getExtension('assets')->getAssetUrl("images/keyarts/fotos/la-nina-vintage-960x460.jpg"), "html", null, true);
        echo "\" alt=\"foto la niña\">

about la niña

               Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est, sit, molestiae pariatur consectetur quisquam non fuga quidem et modi asperiores aliquam aliquid odio assumenda eius dolor quaerat in libero eum!
               Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati, ea, eos dolore fuga facere similique ipsam consequuntur eaque officiis dolor esse sequi et omnis odio ratione corporis nostrum. Dolorum, eveniet.
               Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque, quod, mollitia, quidem possimus quaerat vitae expedita itaque laborum debitis laudantium eum optio earum quis deleniti asperiores cupiditate facere! Officiis, soluta!

               the story

               Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi, non, aliquam velit eum dolor assumenda temporibus mollitia earum veritatis voluptas modi doloremque pariatur sapiente minima necessitatibus molestiae nulla illum fuga!
               Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error, beatae, perspiciatis eius explicabo sit hic consequatur magni laudantium animi vitae labore quisquam voluptates aliquid rem qui necessitatibus minima nesciunt vero.

env, $this->env->getExtension('assets')->getAssetUrl("images/keyarts/fotos/la-nacional-300x227.jpg"), "html", null, true);
        echo "\" alt=\"imagen 1\">

env, $this->env->getExtension('assets')->getAssetUrl("images/keyarts/fotos/la-nacional-300x227.jpg"), "html", null, true);
        echo "\" alt=\"imagen 2\">

env, $this->env->getExtension('assets')->getAssetUrl("images/keyarts/fotos/la-nacional-300x227.jpg"), "html", null, true);
        echo "\" alt=\"imagen 3\">

env, $this->env->getExtension('assets')->getAssetUrl("images/keyarts/fotos/la-nacional-300x227.jpg"), "html", null, true);
        echo "\" alt=\"imagen 1\">

env, $this->env->getExtension('assets')->getAssetUrl("images/keyarts/fotos/la-nacional-300x227.jpg"), "html", null, true);
        echo "\" alt=\"imagen 2\">

env, $this->env->getExtension('assets')->getAssetUrl("images/keyarts/fotos/la-nacional-300x227.jpg"), "html", null, true);
        echo "\" alt=\"imagen 3\">

                     env, $this->env->getExtension('assets')->getAssetUrl("images/keyarts/arrow_left.png"), "html", null, true);
        echo "\" alt=\"control galeria izquierda\">

                     env, $this->env->getExtension('assets')->getAssetUrl("images/keyarts/arrow_right.png"), "html", null, true);
        echo "\" alt=\"control galeria derecha\">

               Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto, quae, atque mollitia aspernatur illo ipsum vero sed error soluta quisquam itaque tempore voluptates est in blanditiis nostrum vitae minima molestiae?
               Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi, earum, inventore, quas, hic minima a adipisci ullam libero illum tempore doloribus nihil atque similique deserunt perferendis. Atque minus necessitatibus magnam.

               env, $this->env->getExtension('assets')->getAssetUrl("images/keyarts/facebook_share.png"), "html", null, true);
        echo "\" alt=\"compartir en facebook\">

               env, $this->env->getExtension('assets')->getAssetUrl("images/keyarts/twitter_share.png"), "html", null, true);
        echo "\" alt=\"compartir en twitter\">

";
    }

    // line 64
    public function block_javascripts($context, array $blocks = array())
    {
        // line 65
        $this->displayParentBlock("javascripts", $context, $blocks);
        echo "

";
    }

    public function getTemplateName()
    {
        return "FrontendBundle:Default:about.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  143 => 66,  139 => 65,  136 => 64,  126 => 57,  120 => 54,  107 => 44,  101 => 41,  94 => 37,  90 => 36,  86 => 35,  82 => 34,  78 => 33,  74 => 32,  51 => 12,  46 => 9,  43 => 8,  37 => 5,  33 => 4,  30 => 3,);
    }
}


text:
<?php

namespace App\Http\Requests\Backend;

use Illuminate\Foundation\Http\FormRequest;

class UpdateAppointmentRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'employee_id' => ['required'],
            'seminar_id' => ['required'],
            'date' => ['required', 'date_format:Y-m-d'],
            'time' => ['required', 'date_format:H:i'],
            'zip' => ['required'],
            'city' => ['required'],
            'street' => ['required'],
            'housenumber' => ['required']
        ];
    }

    public function messages()
    {
        return [
            'employee_id.required' => 'Employee is required',
            'seminar_id.required' => 'Seminar is required',
            'date.required' => 'Date is required',
            'time.required' => 'Time is required',
            'zip.required' => 'Zip is required',
            'city.required' => 'City is required',
            'street.required' => 'Street is required',
            'housenumber.required' => 'Housenumber is required'
        ];
    }
}


text:
CBJoystick
==========

A UIKit joystick view, MIT license.

<img src="https://raw.github.com/CocoaBob/CBJoystick/master/screenshot.jpg" width="240" height="360"/>


text:
class Broadcast < ActiveRecord::Base
  extend Enumerize
  # Everyone gets the same notification,
  # or same general notification with custom variables.
  belongs_to :creator, class_name: :User

  validates :subject, presence: true
  validates :body, presence: true

  enumerize :state, in: [:draft, :scheduled, :delivered],
    default: :draft, predicates: true

  # This is 'telling'.
  def schedule!
    raise StandardError, 'Not schedulable.' unless schedulable?
    # TODO: Scheduling work
    scheduled
  end

  # This is 'notifying'.
  def scheduled
    self.state = :scheduled
  end

  def deliver!
    raise StandardError, 'Not deliverable.' unless deliverable?
    # TODO: Delivery work
    # This #delivered call may exist in the background job,
    # but we're writing it here to notify that the 'work', presently
    # nothing, is done.
    delivered
  end

  def delivered
    self.state = :delivered
  end

  def schedulable?
    scope.present? && scheduled_for.present? &&
      scope_returns_at_least_one_record
  end

  def deliverable?
    scope.present? && scope_returns_at_least_one_record
  end

  private

  def scope_returns_at_least_one_record
    User.where(scope).any?
  end

end


text:
import Lion from './API/Lion';
import Crocodile from './API/Crocodile';
import Gazelle from './API/Gazelle';

// ==============================
// CLIENT CODE
// ==============================

let lion: Lion = new Lion(),
    crocodile: Crocodile = new Crocodile(),
    gazelle: Gazelle = new Gazelle();

gazelle.addPredator(lion);
gazelle.addPredator(crocodile);

console.log(gazelle.notifyPredators());


text:
/*
 * \brief
 * \author Sylvain Jaume, Francois Huguet
 */

# ifndef SO_VTK_IMAGENONMAXIMUMSUPPRESSION_H_
# define SO_VTK_IMAGENONMAXIMUMSUPPRESSION_H_

# include <Inventor/engines/SoSubEngine.h>

# include "xip/inventor/vtk/SoSFVtkAlgorithmOutput.h"
# include "xip/inventor/vtk/SoSFVtkObject.h"

# include "vtkImageNonMaximumSuppression.h"

# include "Inventor/fields/SoSFInt32.h"

class SoVtkImageNonMaximumSuppression : public SoEngine
{
	SO_ENGINE_HEADER( SoVtkImageNonMaximumSuppression );

public:

	/// Constructor
	SoVtkImageNonMaximumSuppression();

	/// Class Initialization
	static void initClass();

	// Inputs
	/// Dimensionality
	SoSFInt32 Dimensionality;
	/// HandleBoundaries
	SoSFInt32 HandleBoundaries;
	/// VectorInput of type vtkImageData
	SoSFVtkObject VectorInput;
	/// NumberOfThreads
	SoSFInt32 NumberOfThreads;
	/// MagnitudeInput of type vtkImageData
	SoSFVtkObject MagnitudeInput;
	/// Input connection
	SoSFVtkAlgorithmOutput InputConnection;

	// Outputs
	/// SoSFVtkObject of type vtkImageData
	SoEngineOutput Output;
	/// SoSFVtkAlgorithmOutput
	SoEngineOutput OutputPort;

protected:

	/// Destructor
	~SoVtkImageNonMaximumSuppression();

	/// Evaluate Function
	virtual void evaluate();

	/// inputChanged Function
	virtual void inputChanged(SoField *);

	/// reset Function
	virtual void reset();

	/// vtkImageData
	SoVtkObject *mOutput;

	/// vtkAlgorithm
	SoVtkAlgorithmOutput *mOutputPort;

private:

	vtkImageNonMaximumSuppression* mObject;
	/// addCalled checks if the Add*() method has been called
	bool addCalled;
};

#endif // SO_VTK_IMAGENONMAXIMUMSUPPRESSION_H_


text:
class AddHashToFiles < ActiveRecord::Migration
  def change
    add_column :files, :file_hash, :string, null: false, default: ""
    add_index :files, :file_hash
  end
end


text:
#pragma once

#include <QDateTime>
#include <QVariant>
#include <QUrl>

namespace Mnemosy
{
class LJMessage
{
    quint64 m_QId;

    QDateTime m_Date;
    QString m_Subject;
    quint64 m_PosterId;
    quint64 m_EntryDItemId;
    QUrl m_PosterPicUrl;
    QUrl m_CommentUrl;
    QString m_EntrySubject;
    QString m_Poster;
    QString m_Body;
    quint64 m_DTalkID;
    QString m_To;
    quint64 m_ToId;
    quint64 m_MessageId;
    quint64 m_ParentID;
    quint64 m_FromId;
    QString m_From;
    QString m_JournalName;
public:
    enum Type
    {
        MTNoType = 0,
        MTBeFriended,
        MTBirthday,
        MTCommunityInvite,
        MTCommunityJoinApprove,
        MTCommunityJoinReject,
        MTCommunityJoinRequest,
        MTDefriended,
        MTInvitedFriendJoins,
        MTJournalNewComment,
        MTJournalNewEntry,
        MTNewUserpic,
        MTNewVGift,
        MTOfficialPost,
        MTPermSale,
        MTPollVote,
        MTSupOfficialPost,
        MTUserExpunged,
        MTUserMessageRecvd,
        MTUserMessageSent,
        MTUserNewComment,
        MTUserNewEntry,
        MTCommentReply
    };

    enum Direction
    {
        DUnknown = 0,
        DIn,
        DOut
    };

    enum State
    {
        SNoState = 0,
        SRead,
        SUnread,
    };

    enum Action
    {
        ANoAction = 0,
        ADeleted,
        ACommentDeleted,
        AEdited,
        ANew
    };

private:
    State m_State;
    Type m_Type;
    Action m_Action;
    Direction m_Direction;

public:
    explicit LJMessage();

    quint64 GetQId() const;
    void SetQId(quint64 qid);
    QDateTime GetDate() const;
    void SetDate(const QDateTime& dt);
    QString GetSubject() const;
    void SetSubject(const QString& subject);
    quint64 GetPosterId() const;
    void SetPosterId(quint64 posterId);
    quint64 GetEntryDItemId() const;
    void SetEntryDItemId(const quint64 id);
    QUrl GetPosterPicUrl() const;
    void SetPosterPicUrl(const QUrl& url);
    QUrl GetCommentUrl() const;
    void SetCommentUrl(const QUrl& url);
    QString GetEntrySubject() const;
    void SetEntrySubject(const QString& subject);
    QString GetPoster() const;
    void SetPoster(const QString& poster);
    QString GetBody() const;
    void SetBody(const QString& body);
    quint64 GetDTalkID() const;
    void SetDTalkID(quint64 id);
    QString GetTo() const;
    void SetTo(const QString& to);
    quint64 GetToId() const;
    void SetToId(quint64 id);
    quint64 GetMessageId() const;
    void SetMessageId(quint64 id);
    quint64 GetParentID() const;
    void SetParentID(quint64 id);
    quint64 GetFromId() const;
    void SetFromId(quint64 id);
    QString GetFrom() const;
    void SetFrom(const QString& from);
    State GetState() const;
    void SetState(State st);
    Type GetType() const;
    void SetType(Type t);
    Action GetAction() const;
    void SetAction(Action act);
    Direction GetDirection() const;
    void SetDirection(Direction direction);
    QString GetJournalName() const;
    void SetJournalName(const QString& journal);

    QByteArray Serialize() const;
    static bool Deserialize(const QByteArray& data, LJMessage& message);

    bool IsValid() const;

    QVariantMap ToMap() const;
};

typedef QList<LJMessage> LJMessages_t;
} // namespace Mnemosy