text:
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;

// ReSharper disable MemberCanBePrivate.Global
#if BUILD_PEANUTBUTTER_INTERNAL
namespace Imported.PeanutButter.Utils
#else
namespace PeanutButter.Utils
#endif
{
    /// <summary>
    /// Determines the comparison strategy for DeepEquals and friends
    /// </summary>
#if BUILD_PEANUTBUTTER_INTERNAL
    internal
#else
    public
#endif
        enum ObjectComparisons
    {
        /// <summary>
        /// Test properties and fields (default behavior for DeepEquals)
        /// </summary>
        PropertiesAndFields,

        /// <summary>
        /// Only test properties (behavior for PropertyAssert)
        /// </summary>
        PropertiesOnly
    }

    /// <summary>
    /// Provides a set of convenience extensions on everything
    /// </summary>
#if BUILD_PEANUTBUTTER_INTERNAL
    internal
#else
    public
#endif
        static class ObjectExtensions
    {
        /// <summary>
        /// Runs a deep equality test between two objects, glossing over reference
        /// differences between class-types and comparing only primitive types. Use
        /// this when you'd like to essentially test whether the data in one object
        /// hierachy matches that of another
        /// </summary>
        /// <param name="objSource">Object which is the source of truth</param>
        /// <param name="objCompare">Object to compare with</param>
        /// <param name="ignorePropertiesByName">Params array of properties to ignore by name</param>
        /// <returns></returns>
        public static bool DeepEquals(
            this object objSource,
            object objCompare,
            params string[] ignorePropertiesByName
        )
        {
            return objSource.DeepEquals(
                objCompare,
                ObjectComparisons.PropertiesAndFields,
                ignorePropertiesByName);
        }

        /// <summary>
        /// Tests if two objects have the same "shape" -- basically Deep Equality testing
        /// without actually testing final property values.
        /// </summary>
        /// <param name="objSource">Source / Master object</param>
        /// <param name="objCompare">Comparison object</param>
        /// <param name="ignorePropertiesByName">Ignore these properties by name</param>
        /// <returns>True if the "shapes" are the same, false otherwise</returns>
        public static bool ShapeEquals(
            this object objSource,
            object objCompare,
            params string[] ignorePropertiesByName
        )
        {
            return PerformShapeEqualityTesting(
                objSource,
                objCompare,
                false,
                ignorePropertiesByName
            );
        }

        /// <summary>
        /// Tests if a second object has at least the "shape" of a primary one. Basically
        /// a DeepSubEquals without testing final property values.
        /// without actually testing final property values.
        /// </summary>
        /// <param name="objSource">Source / Master object</param>
        /// <param name="objCompare">Comparison object</param>
        /// <param name="ignorePropertiesByName">Ignore these properties by name</param>
        /// <returns>True if the comparison object "contains the shape" of the source object, false otherwise</returns>
        public static bool ShapeSubEquals(
            this object objSource,
            object objCompare,
            params string[] ignorePropertiesByName
        )
        {
            return PerformShapeEqualityTesting(
                objSource,
                objCompare,
                true,
                ignorePropertiesByName
            );
        }

        private static bool PerformShapeEqualityTesting(
            object left,
            object right,
            bool allowMissingProperties,
            params string[] ignorePropsByName
        )
        {
            var tester = new DeepEqualityTester(left, right, ignorePropsByName)
            {
                OnlyCompareShape = true,
                IncludeFields = true,
                FailOnMissingProperties = !allowMissingProperties
            };
            return tester.AreDeepEqual();
        }

        /// <summary>
        /// Runs a deep equality test between two objects, glossing over reference
        /// differences between class-types and comparing only primitive types. Use
        /// this when you'd like to essentially test whether the data in one object
        /// hierachy matches that of another
        /// </summary>
        /// <param name="objSource">Object which is the source of truth</param>
        /// <param name="objCompare">Object to compare with</param>
        /// <param name="comparison">Method for comparison</param>
        /// <param name="ignorePropertiesByName">Params array of properties to ignore by name</param>
        /// <returns></returns>
        public static bool DeepEquals(
            this object objSource,
            object objCompare,
            ObjectComparisons comparison,
            params string[] ignorePropertiesByName
        )
        {
            var tester = new DeepEqualityTester(
                objSource,
                objCompare,
                ignorePropertiesByName
            ) { IncludeFields = comparison == ObjectComparisons.PropertiesAndFields };
            return tester.AreDeepEqual();
        }

        /// <summary>
        /// Runs a deep equality test between two objects,
        /// ignoring reference differences wherever possible
        /// and logging failures with the provided action. Properties
        /// can be explided by name with the ignorePropertiesByName params
        /// </summary>
        /// <param name="objSource"></param>
        /// <param name="objCompare"></param>
        /// <param name="failureLogAction"></param>
        /// <param name="ignorePropertiesByName"></param>
        /// <returns></returns>
        public static bool DeepEquals(this object objSource,
            object objCompare,
            Action<string> failureLogAction,
            params string[] ignorePropertiesByName)
        {
            var tester = new DeepEqualityTester(
                objSource, objCompare, ignorePropertiesByName)
            {
                RecordErrors = true
            };
            var result = tester.AreDeepEqual();
            tester.Errors.ForEach(failureLogAction);
            return result;
        }

        /// <summary>
        /// Runs a deep equality test between two objects, using the properties on objSource (and children) as
        /// the set of properties to match on
        /// </summary>
        /// <param name="objSource">Source object to perform comparison against</param>
        /// <param name="objCompare">Comparison object to compare</param>
        /// <param name="ignorePropertiesByName">Optional params array of properties to ignore by name</param>
        /// <returns>True if relevant properties are found and match; false otherwise</returns>
        public static bool DeepSubEquals(
            this object objSource,
            object objCompare,
            params string[] ignorePropertiesByName)
        {
            var tester = new DeepEqualityTester(
                objSource,
                objCompare,
                ignorePropertiesByName
            ) { FailOnMissingProperties = false };
            return tester.AreDeepEqual();
        }

        /// <summary>
        /// Runs a deep equality test between two objects, using the properties common to both sides
        /// of the comparison to match on.
        /// </summary>
        /// <param name="objSource">Source object to perform comparison against</param>
        /// <param name="objCompare">Comparison object to compare</param>
        /// <param name="ignorePropertiesByName">Optional params array of properties to ignore by name</param>
        /// <returns>True if relevant properties are found and match; false otherwise. If no common properties are found, returns false; caveat: performing this comparison on two vanilla Object() instances will return true.</returns>
        public static bool DeepIntersectionEquals(
            this object objSource,
            object objCompare,
            params string[] ignorePropertiesByName)
        {
            var tester = new DeepEqualityTester(
                objSource,
                objCompare,
                ignorePropertiesByName
            ) { OnlyTestIntersectingProperties = true };
            return tester.AreDeepEqual();
        }

        /// <summary>
        /// Searches a collection for one or more objects which DeepEquals the provided reference item
        /// </summary>
        /// <param name="collection">Collection of objects to search</param>
        /// <param name="item">Item to find a match for</param>
        /// <param name="ignoreProperties">Optional params array of properties to ignore by name</param>
        /// <typeparam name="T1">Item type of the collection</typeparam>
        /// <typeparam name="T2">Type of the comparison item (can be the same as or different from T1)</typeparam>
        /// <returns>True if one or more matching objects were found; false otherwise</returns>
        public static bool ContainsAtLeastOneDeepEqualTo<T1, T2>(
            this IEnumerable<T1> collection,
            T2 item,
            params string[] ignoreProperties)
        {
            return collection.Any(i => i.DeepEquals(item, ignoreProperties));
        }

        /// <summary>
        /// Searches a collection for a single object which DeepEquals the provided reference item
        /// </summary>
        /// <param name="collection">Collection of objects to search</param>
        /// <param name="item">Item to find a match for</param>
        /// <param name="ignoreProperties">Optional params array of properties to ignore by name</param>
        /// <typeparam name="T1">Item type of the collection</typeparam>
        /// <typeparam name="T2">Type of the comparison item (can be the same as or different from T1)</typeparam>
        /// <returns>True if one or more matching objects were found; false otherwise</returns>
        public static bool ContainsOneDeepEqualTo<T1, T2>(
            this IEnumerable<T1> collection,
            T2 item,
            params string[] ignoreProperties)
        {
            return collection.Count(i => i.DeepEquals(item, ignoreProperties)) == 1;
        }

        /// <summary>
        /// Searches a collection for an object which IntersectionEquals the provided reference item
        /// </summary>
        /// <param name="collection">Collection of objects to search</param>
        /// <param name="item">Item to find a match for</param>
        /// <param name="ignoreProperties">Optional params array of properties to ignore by name</param>
        /// <typeparam name="T1">Item type of the collection</typeparam>
        /// <typeparam name="T2">Type of the comparison item (can be the same as or different from T1)</typeparam>
        /// <returns>True if one or more matching objects were found; false otherwise</returns>
        public static bool ContainsOneIntersectionEqualTo<T1, T2>(
            this IEnumerable<T1> collection,
            T2 item,
            params string[] ignoreProperties
        )
        {
            return collection.Any(i => i.DeepIntersectionEquals(item, ignoreProperties));
        }

        /// <summary>
        /// Searches a collection for an object which DeepEquals the provided reference item
        /// </summary>
        /// <param name="collection">Collection of objects to search</param>
        /// <param name="item">Item to find a match for</param>
        /// <param name="ignoreProperties">Optional params array of properties to ignore by name</param>
        /// <typeparam name="T1">Item type of the collection</typeparam>
        /// <typeparam name="T2">Type of the comparison item (can be the same as or different from T1)</typeparam>
        /// <returns>True if exactly one matching object was found; false otherwise</returns>
        public static bool ContainsOnlyOneDeepEqualTo<T1, T2>(
            this IEnumerable<T1> collection,
            T2 item,
            params string[] ignoreProperties)
        {
            return collection.ContainsOnlyOneMatching(
                item,
                (t1, t2) => t1.DeepEquals(t2, ignoreProperties));
        }

        /// <summary>
        /// Searches a collection for an object which IntersectionEquals the provided reference item
        /// </summary>
        /// <param name="collection">Collection of objects to search</param>
        /// <param name="item">Item to find a match for</param>
        /// <param name="ignoreProperties">Optional params array of properties to ignore by name</param>
        /// <typeparam name="T1">Item type of the collection</typeparam>
        /// <typeparam name="T2">Type of the comparison item (can be the same as or different from T1)</typeparam>
        /// <returns>True if exactly one matching object was found; false otherwise</returns>
        public static bool ContainsOnlyOneIntersectionEqualTo<T1, T2>(
            this IEnumerable<T1> collection,
            T2 item,
            params string[] ignoreProperties
        )
        {
            return collection.ContainsOnlyOneMatching(
                item,
                (t1, t2) => t1.DeepIntersectionEquals(t2, ignoreProperties));
        }

        /// <summary>
        /// Searches a collection for an object which matches the provided reference item, according
        /// to the provided matcher Func
        /// </summary>
        /// <param name="collection">Collection of objects to search</param>
        /// <param name="item">Item to find a match for</param>
        /// <param name="comparer">Func to use to perform comparison</param>
        /// <typeparam name="T1">Item type of the collection</typeparam>
        /// <typeparam name="T2">Type of the comparison item (can be the same as or different from T1)</typeparam>
        /// <returns>True if exactly one matching object was found; false otherwise</returns>
        public static bool ContainsOnlyOneMatching<T1, T2>(
            this IEnumerable<T1> collection,
            T2 item,
            Func<T1, T2, bool> comparer
        )
        {
            return collection.Aggregate(
                    0,
                    (acc, cur) =>
                    {
                        if (acc > 1)
                            return acc;
                        acc += comparer(cur, item)
                            ? 1
                            : 0;
                        return acc;
                    }) ==
                1;
        }

        /// <summary>
        /// Copies all public primitive property values of intersecting properties from the source object
        /// to the target object, ala poor-man's AutoMapper
        /// </summary>
        /// <param name="src">Source object</param>
        /// <param name="dst">Target object</param>
        public static void CopyPropertiesTo(this object src, object dst)
        {
            src.CopyPropertiesTo(dst, true);
        }

        /// <summary>
        /// Copies all public primitive property values of intersecting properties from the source object
        /// to the target object, ala poor-man's AutoMapper
        /// </summary>
        /// <param name="src">Source object</param>
        /// <param name="dst">Target object</param>
        /// <param name="ignoreProperties">Optional list of properties to ignore by name</param>
        public static void CopyPropertiesTo(this object src, object dst, params string[] ignoreProperties)
        {
            src.CopyPropertiesTo(dst, true, ignoreProperties);
        }

        /// <summary>
        /// Copies all public primitive property values of intersecting properties from the source object
        /// to the target object, ala poor-man's AutoMapper
        /// </summary>
        /// <param name="src">Source object</param>
        /// <param name="dst">Target object</param>
        /// <param name="deep">Flag as to whether or not the process should copy deep (ie, traverse into child objects)</param>
        /// <param name="ignoreProperties"></param>
        public static void CopyPropertiesTo(this object src, object dst, bool deep, params string[] ignoreProperties)
        {
            if (src is null || dst is null)
            {
                return;
            }

            var srcType = src.GetType();
            if (!PropertyCache.TryGetValue(srcType, out var props))
            {
                props = srcType.GetProperties();
                PropertyCache.TryAdd(srcType, props);
            }

            var srcPropInfos = props
                .Where(pi => !ignoreProperties.Contains(pi.Name));
            var dstPropInfos = dst.GetType().GetProperties()
                .Where(p => p.CanWrite)
                .ToArray();

            var targetPropertyCache = dstPropInfos.ToDictionary(
                pi => Tuple.Create(pi.Name, pi.PropertyType),
                pi => pi
            );

            foreach (var srcPropInfo in srcPropInfos.Where(
                         pi => pi.CanRead &&
                             pi.GetIndexParameters().Length == 0))
            {
                if (!targetPropertyCache.TryGetValue(Tuple.Create(
                        srcPropInfo.Name,
                        srcPropInfo.PropertyType
                    ), out var matchingTarget))
                {
                    continue;
                }

                var srcVal = srcPropInfo.GetValue(src);

                PropertySetterStrategies.Aggregate(
                    false,
                    (acc, cur) =>
                        acc || cur(deep, srcPropInfo, matchingTarget, dst, srcVal)
                );
            }
        }

        private static readonly ConcurrentDictionary<Type, PropertyInfo[]> PropertyCache = new();

        private static readonly Func<bool, PropertyInfo, PropertyInfo, object, object, bool>[]
            PropertySetterStrategies =
            {
                SetSimpleOrNullableOfSimpleTypeValue,
                SetArrayOrGenericIEnumerableValue,
                SetGenericListValue,
                SetEnumValue,
                DefaultSetValue
            };

        private static bool SetEnumValue(
            bool deep,
            PropertyInfo srcPropertyInfo,
            PropertyInfo dstPropertyInfo,
            object dst,
            object srcValue)
        {
            if (!srcPropertyInfo.PropertyType.IsEnum())
                return false;
            dstPropertyInfo.SetValue(dst, srcValue);

            return true;
        }

        private static bool DefaultSetValue(
            bool deep,
            PropertyInfo srcPropertyInfo,
            PropertyInfo dstPropertyInfo,
            object dst,
            object srcVal
        )
        {
            if (srcVal != null)
            {
                var clone = srcVal.DeepCloneInternal(srcPropertyInfo.PropertyType);
                dstPropertyInfo.SetValue(dst, clone);
                return true;
            }

            dstPropertyInfo.SetValue(dst, null, null);
            return false;
        }

        private static bool SetGenericListValue(
            bool deep,
            PropertyInfo srcPropertyInfo,
            PropertyInfo dstPropertyInfo,
            object dst,
            object srcVal
        )
        {
            if (!srcPropertyInfo.PropertyType.IsGenericOf(typeof(List<>)))
                return false;
            var itemType = srcPropertyInfo.PropertyType.GetCollectionItemType();
            if (itemType == null)
                return false;
            var method = _genericMakeListCopy.MakeGenericMethod(itemType);
            var newValue = method.Invoke(null, new[] { srcVal });
            dstPropertyInfo.SetValue(dst, newValue);
            return true;
        }

        private static bool SetArrayOrGenericIEnumerableValue(
            bool deep,
            PropertyInfo srcPropertyInfo,
            PropertyInfo dstPropertyInfo,
            object dst,
            object srcVal
        )
        {
            if (!srcPropertyInfo.PropertyType.IsArrayOrAssignableFromArray())
                return false;
            var underlyingType = srcPropertyInfo.PropertyType.GetCollectionItemType();
            if (underlyingType == null)
                return false;
            var specific = _genericMakeArrayCopy.MakeGenericMethod(underlyingType);
            // ReSharper disable once RedundantExplicitArrayCreation
            var newValue = specific.Invoke(null, new[] { srcVal });
            dstPropertyInfo.SetValue(dst, newValue);
            return true;
        }

        private static bool SetSimpleOrNullableOfSimpleTypeValue(
            bool deep,
            PropertyInfo srcPropertyInfo,
            PropertyInfo dstPropertyInfo,
            object dst,
            object srcVal
        )
        {
            if (deep && !IsSimpleTypeOrNullableOfSimpleType(srcPropertyInfo.PropertyType))
                return false;
            dstPropertyInfo.SetValue(dst, srcVal);
            return true;
        }

        private static readonly BindingFlags _privateStatic =
            BindingFlags.NonPublic | BindingFlags.Static;

        private static readonly MethodInfo _genericMakeArrayCopy
            = typeof(ObjectExtensions).GetMethod(
                nameof(MakeArrayCopyOf),
                _privateStatic);

        private static readonly MethodInfo _genericMakeListCopy
            = typeof(ObjectExtensions).GetMethod(
                nameof(MakeListCopyOf),
                _privateStatic);

        private static readonly MethodInfo _genericMakeDictionaryCopy
            = typeof(ObjectExtensions).GetMethod(
                nameof(MakeDictionaryCopyOf),
                _privateStatic);

#pragma warning disable S1144 // Unused private types or members should be removed
        // ReSharper disable once UnusedMember.Local
        private static T[] MakeArrayCopyOf<T>(IEnumerable<T> src)
        {
            return MakeListCopyOf(src)?.ToArray();
        }

        private static List<T> MakeListCopyOf<T>(IEnumerable<T> src)
        {
            try
            {
                if (src == null)
                    return null;
                // ReSharper disable once PossibleMultipleEnumeration
                var result = new List<T>();
                // ReSharper disable once PossibleMultipleEnumeration
                result.AddRange(src.Select(item => item.DeepClone()));
                return result;
            }
            catch
            {
                return null;
            }
        }

        private static IDictionary<TKey, TValue> MakeDictionaryCopyOf<TKey, TValue>(
            IDictionary<TKey, TValue> src,
            Type targetType
        )
        {
            var instance = Activator.CreateInstance(targetType) as IDictionary<TKey, TValue>;
            if (instance == null)
                throw new InvalidOperationException($"Activator couldn't create instance of {targetType}");
            src?.ForEach(kvp => instance.Add(new KeyValuePair<TKey, TValue>(kvp.Key, kvp.Value)));
            return instance;
        }

#pragma warning restore S1144 // Unused private types or members should be removed

        /// <summary>
        /// Creates a deep clone of the provided item, as far as possible
        /// Works on properties which are:
        ///  * simple values,
        ///  * any complex, non-generic value with a parameterless constructor
        ///  * Collections which are arrays, generic IEnumerable or generic List,
        ///      conforming to the rules above
        /// </summary>
        /// <param name="item">Item to clone</param>
        /// <typeparam name="T">Type of the item to clone</typeparam>
        /// <returns>a new copy of the original item</returns>
        public static T DeepClone<T>(this T item)
        {
            return item is null || item.Equals(default(T))
                ? default(T)
                : (T) item.DeepCloneInternal(item.GetType());
        }

        private static object DeepCloneInternal(
            this object src,
            Type cloneType
        )
        {
            if (src == null)
                return null;
            try
            {
                if (Types.PrimitivesAndImmutables.Contains(cloneType))
                {
                    // FIXME: can we get new instances for Dates and such?
                    return src;
                }

                return _cloneStrategies.Aggregate(
                    null as object,
                    (acc, cur) => acc ?? cur(src, cloneType));
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Unable to clone item of type {cloneType.Name}: {e.Message}");
                return cloneType.DefaultValue();
            }
        }

        private static readonly Func<object, Type, object>[] _cloneStrategies =
        {
            CloneArray,
            CloneList,
            CloneDictionary,
            CloneEnumerable,
            CloneObject
        };

        private static object CloneDictionary(object src, Type cloneType)
        {
            if (!cloneType.TryGetDictionaryKeyAndValueTypes(
                    out var keyType,
                    out var valueType))
            {
                return null;
            }

            var key = Tuple.Create(keyType, valueType);
            if (!DictionaryCopyMethodCache.TryGetValue(key, out var method))
            {
                method = _genericMakeDictionaryCopy.MakeGenericMethod(keyType, valueType);
                DictionaryCopyMethodCache.TryAdd(key, method);
            }

            return method.Invoke(null, new[] { src, cloneType });
        }

        private static readonly ConcurrentDictionary<Tuple<Type, Type>, MethodInfo> DictionaryCopyMethodCache = new();

        private static object CloneEnumerable(object src, Type cloneType)
        {
            if (!cloneType.ImplementsEnumerableGenericType())
                return null;
            var itemType = cloneType.GetCollectionItemType();
            var method = FindGenericMethodFor(
                itemType, _genericMakeArrayCopy, ArrayCopyMethodCache
            );
            return method.Invoke(null, new[] { src });
        }

        private static object CloneList(object src, Type cloneType)
        {
            if (!cloneType.IsGenericOf(typeof(List<>)) && !cloneType.IsGenericOf(typeof(IList<>)))
                return null;
            var itemType = cloneType.GetCollectionItemType();
            var method = FindGenericMethodFor(
                itemType,
                _genericMakeListCopy,
                ListCopyMethodCache
            );
            return method.Invoke(null, new[] { src });
        }

        private static object CloneArray(object src, Type cloneType)
        {
            if (!cloneType.IsArray)
                return null;
            var itemType = cloneType.GetCollectionItemType();
            var method = FindGenericMethodFor(
                itemType,
                _genericMakeArrayCopy, ArrayCopyMethodCache
            );
            return method.Invoke(null, new[] { src });
        }

        private static readonly ConcurrentDictionary<Type, MethodInfo> ListCopyMethodCache = new();
        private static readonly ConcurrentDictionary<Type, MethodInfo> ArrayCopyMethodCache = new();

        private static MethodInfo FindGenericMethodFor(
            Type type,
            MethodInfo genericMethod,
            ConcurrentDictionary<Type, MethodInfo> cache
        )
        {
            if (cache.TryGetValue(type, out var cached))
            {
                return cached;
            }

            var result = genericMethod.MakeGenericMethod(type);
            cache.TryAdd(type, result);
            return result;
        }

        private static object CloneObject(object src, Type cloneType)
        {
            try
            {
                var newInstance = Activator.CreateInstance(cloneType);
                src.CopyPropertiesTo(newInstance);
                return newInstance;
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Unable to clone object of type {cloneType.Name}: {e.Message}");
                return cloneType.DefaultValue();
            }
        }

        private static bool IsSimpleTypeOrNullableOfSimpleType(Type t)
        {
            return Types.PrimitivesAndImmutables.Any(
                si => si == t ||
                    (t.IsGenericType() &&
                        t.GetGenericTypeDefinition() == typeof(Nullable<>) &&
                        Nullable.GetUnderlyingType(t) == si));
        }

        /// <summary>
        /// Gets the value of a property on an object, specified by the property path, of the given Type
        /// </summary>
        /// <param name="src">Object to search for the required property</param>
        /// <param name="propertyPath">Path to the property: may be a property name or a dotted path down an object heirachy, eg: Company.Name</param>
        /// <typeparam name="T">Expected type of the property value</typeparam>
        /// <returns></returns>
        public static T Get<T>(
            this object src,
            string propertyPath)
        {
            var type = src.GetType();
            return ResolvePropertyValueFor<T>(src, propertyPath, type);
        }

        /// <summary>
        /// Gets the value of a property on an object, specified by the property path, of the given Type
        /// or returns a default value when that property cannot be found by path and/or type
        /// </summary>
        /// <param name="src"></param>
        /// <param name="propertyPath"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetOrDefault<T>(
            this object src,
            string propertyPath)
        {
            return src.GetOrDefault(propertyPath, default(T));
        }

        /// <summary>
        /// Gets the value of a property on an object, specified by the property path, of the given Type
        /// or returns a default value when that property cannot be found by path and/or type
        /// </summary>
        /// <param name="src"></param>
        /// <param name="propertyPath"></param>
        /// <param name="defaultValue"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetOrDefault<T>(
            this object src,
            string propertyPath,
            T defaultValue)
        {
            try
            {
                return Get<T>(src, propertyPath);
            }
            catch (MemberNotFoundException)
            {
                return defaultValue;
            }
        }

        /// <summary>
        /// Fluency extension to wrap a single item in an array, eg:
        /// new SomeBusinessObject().AsArray().Union(SomeOtherCollection);
        /// </summary>
        /// <param name="input">The item to wrap</param>
        /// <typeparam name="T">The type of the object</typeparam>
        /// <returns>A single-element array containing the input object</returns>
        [Obsolete("This method was poorly-named and will be removed at some point. Please rather use .InArray() to avoid confusion with the IEnumerable<T> extension AsArray")]
        public static T[] AsArray<T>(this T input)
        {
            return new[] { input };
        }

        /// <summary>
        /// Fluency extension to wrap a single item in an array, eg:
        /// new SomeBusinessObject().InArray().Union(SomeOtherCollection);
        /// </summary>
        /// <param name="input">The item to wrap</param>
        /// <typeparam name="T">The type of the object</typeparam>
        /// <returns>A single-element array containing the input object</returns>
        public static T[] InArray<T>(this T input)
        {
            return new[] { input };
        }

        /// <summary>
        /// Fluency extension to wrap a single item in a list, eg:
        /// new SomeBusinessObject().InList().Union(SomeOtherCollection);
        /// </summary>
        /// <param name="input">The item to wrap</param>
        /// <typeparam name="T">The type of the object</typeparam>
        /// <returns>A single-element list containing the input object</returns>
        public static List<T> InList<T>(this T input)
        {
            return new List<T>() { input };
        }

        private static T ResolvePropertyValueFor<T>(
            object src,
            string propertyPath,
            Type type)
        {
            var valueAsObject = GetPropertyValue(src, propertyPath);
            if (valueAsObject is null)
            {
                if (type.IsNullableType())
                {
                    return default;
                }

                throw new InvalidOperationException(
                    $"value for {propertyPath} is null but {typeof(T)} is not nullable"
                );
            }

            var valueType = valueAsObject.GetType();
            if (!valueType.IsAssignableTo<T>())
                throw new ArgumentException(
                    "Get<> must be invoked with a type to which the property value could be assigned (" +
                    type.Name +
                    "." +
                    propertyPath +
                    " has type '" +
                    valueType.Name +
                    "', but expected '" +
                    typeof(T).Name +
                    "' or derivative");
            return (T) valueAsObject;
        }

        /// <summary>
        /// Gets a property value by name from an object
        /// </summary>
        /// <param name="src">Source object</param>
        /// <param name="propertyPath">Name of the property to search for</param>
        /// <returns>Value of the property, cast/boxed to object</returns>
        /// <exception cref="MemberNotFoundException">Thrown when the property is not found by name</exception>
        public static object GetPropertyValue(
            this object src,
            string propertyPath
        )
        {
            if (src is null)
            {
                throw new InvalidOperationException(
                    "Cannot retrieve any property value off of null"
                );
            }

            var trailingMember = FindPropertyOrField(
                src,
                propertyPath,
                AnyInstanceProperty,
                AnyInstanceField
            );
            if (!trailingMember.Found)
            {
                throw new MemberNotFoundException(src?.GetType(), propertyPath);
            }

            return trailingMember.GetValue();
        }

        private static PropertyOrField[] AnyInstanceProperty(
            Type type)
        {
            var ancestry = type.Ancestry()
                .Reverse()
                .Select((t, idx) => new { type = t, idx })
                .ToDictionary(o => o.type, o => o.idx);
            var result = type.GetProperties(AllOnInstance)
                .Where(pi => !(pi.DeclaringType is null))
                .Select(pi => new { pi, idx = ancestry[pi.DeclaringType] })
                .OrderBy(o => o.pi.Name)
                .ThenBy(o => o.idx)
                .Select(o => o.pi)
                .ImplicitCast<PropertyOrField>()
                .ToArray();
            return result;
        }

        private static PropertyOrField[] AnyInstanceField(
            Type type)
        {
            return type.GetFields(AllOnInstance)
                .ImplicitCast<PropertyOrField>()
                .ToArray();
        }

        /// <summary>
        /// Invokes a method on an object, if available; otherwise 'splodes
        /// </summary>
        /// <param name="src">Object to invoke the method on</param>
        /// <param name="methodName">Method to invoke, by name</param>
        /// <param name="args">Any parameters to give to the method</param>
        /// <returns>return value of the method</returns>
        public static object InvokeMethodWithResult(this object src, string methodName, params object[] args)
        {
            var srcType = src.GetType();
            var method = srcType.GetMethod(
                methodName,
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (method == null)
                throw new InvalidOperationException($"Can't find method {methodName} on {srcType.Name}");
            return method.Invoke(src, args);
        }

        /// <summary>
        /// Attempts to set a property value on an object by property path
        /// </summary>
        /// <param name="src">Source object to set property on</param>
        /// <param name="propertyPath">Path into the property: could be an immediate property name or something like "Company.Name"</param>
        /// <param name="newValue">New value to attempt to set the property to</param>
        /// <exception cref="MemberNotFoundException">Thrown when the property cannot be found</exception>
        public static void SetPropertyValue(
            this object src,
            string propertyPath,
            object newValue)
        {
            src.SetPropertyOrFieldValue(
                propertyPath,
                newValue);
        }

        private static void SetPropertyOrFieldValue(
            this object src,
            string propertyPath,
            object newValue)
        {
            var trailingMember = FindPropertyOrField(
                src,
                propertyPath,
                AnyInstanceProperty,
                AnyInstanceField);

            if (!trailingMember.Found)
            {
                throw new MemberNotFoundException(src.GetType(), propertyPath);
            }

            trailingMember.SetValue(newValue);
        }

        private class TrailingMember
        {
            public bool Found => Member != null;
            public PropertyOrField Member { get; set; }
            public object Host { get; set; }
            public object Index { get; set; }
            public bool IsIndexed { get; set; }

            public object GetValue()
            {
                return IsIndexed
                    ? Member.GetValueAt(Host, Index)
                    : Member.GetValue(Host);
            }

            public void SetValue(object value)
            {
                if (IsIndexed)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    Member.SetValue(Host, value);
                }
            }
        }

        private static TrailingMember FindPropertyOrField(
            object src,
            string propertyPath,
            params Func<Type, PropertyOrField[]>[] fetchers)
        {
            var queue = new Queue<string>(propertyPath.Split('.'));
            var result = new TrailingMember();
            while (queue.Count > 0)
            {
                var current = queue.Dequeue();
                var isIndexed = ParseIndexes(current, out var name, out var indexes);
                if (isIndexed && indexes.Length > 1)
                {
                    throw new NotSupportedException("Multi-dimensional indexing is not supported");
                }

                var index = indexes?.FirstOrDefault();

                var type = src.GetType();
                var memberInfo = fetchers.Aggregate(
                    null as PropertyOrField,
                    (acc, cur) => acc ?? cur(type).FirstOrDefault(mi => mi.Name == name)
                );
                if (memberInfo == null)
                {
                    throw new MemberNotFoundException(type, name);
                }

                if (queue.Count == 0)
                {
                    result.Member = memberInfo;
                    result.Host = src;
                    result.IsIndexed = isIndexed;
                    result.Index = index;
                    break;
                }

                src = isIndexed
                    ? memberInfo.GetValueAt(src, index)
                    : memberInfo.GetValue(src);
            }

            return result;
        }

        private static bool ParseIndexes(
            string path,
            out string name,
            out object[] indexes
        )
        {
            var parts = path.Split('[', ']').Where(p => p.Length > 0)
                .ToArray();
            name = parts[0];
            if (parts.Length == 1)
            {
                indexes = default;
                return false;
            }

            indexes = parts.Skip(1).Select(s => int.TryParse(s, out var asInt)
                ? asInt
                : s as object
            ).ToArray();
            return true;
        }

        /// <summary>
        /// Attempts to set a property value on an object by property path
        /// </summary>
        /// <param name="src"></param>
        /// <param name="propertyPath"></param>
        /// <param name="newValue"></param>
        /// <typeparam name="T"></typeparam>
        public static void Set<T>(
            this object src,
            string propertyPath,
            T newValue)
        {
            src.SetPropertyValue(propertyPath, newValue);
        }

        /// <summary>
        /// attempts to set a property value on an object by path and value
        /// - will not throw on error, but will return false instead
        /// </summary>
        /// <param name="src"></param>
        /// <param name="propertyPath"></param>
        /// <param name="newValue"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static bool TrySet<T>(
            this object src,
            string propertyPath,
            T newValue
        )
        {
            try
            {
                src.Set(propertyPath, newValue);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private static readonly BindingFlags AllOnInstance =
            BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

        /// <summary>
        /// Gets an immediate property value, cast to the specified type
        /// </summary>
        /// <param name="src">Source object</param>
        /// <param name="propertyPath">Immediate property name</param>
        /// <typeparam name="T">Required type</typeparam>
        /// <returns>Value of the property, if it can be found and cast. Will throw otherwise.</returns>
        public static T GetPropertyValue<T>(this object src, string propertyPath)
        {
            var objectResult = GetPropertyValue(src, propertyPath);
            return (T) objectResult;
        }

        /// <summary>
        /// Tests if a type is assignable to another type (inverse of IsAssignableFrom)
        /// </summary>
        /// <param name="type">Type to operate on</param>
        /// <typeparam name="T">Type to check assignment possibility against</typeparam>
        /// <returns>True if objects of type {type} can be assigned to objects of type T</returns>
        public static bool IsAssignableTo<T>(this Type type)
        {
            var targetType = typeof(T);
            return targetType.IsAssignableFrom(type);
        }

        /// <summary>
        /// Truncates a decimal value to a required number of places
        /// </summary>
        /// <param name="value">Source decimal value</param>
        /// <param name="places">Number of decimal places required</param>
        /// <returns>A new decimal value which is the original value truncated to the required places</returns>
        public static decimal TruncateTo(this decimal value, int places)
        {
            var mul = new decimal(Math.Pow(10, places));
            return Math.Truncate(value * mul) / mul;
        }

        /// <summary>
        /// Truncates a decimal value to a required number of places
        /// </summary>
        /// <param name="value">Source decimal value</param>
        /// <param name="places">Number of decimal places required</param>
        /// <returns>A new decimal value which is the original value truncated to the required places</returns>
        public static double TruncateTo(this double value, int places)
        {
            var mul = Math.Pow(10, places);
            return Math.Truncate(value * mul) / mul;
        }

        /// <summary>
        /// Provides a similar api to Javascript's
        /// .toFixed(), except returning a useful decimal!
        /// Note: this is different from .TruncateTo since that will
        /// truncate the value, whereas this will round
        /// </summary>
        /// <param name="value">Source decimal value</param>
        /// <param name="places">Number of decimal places required</param>
        /// <returns></returns>
        public static decimal ToFixed(this decimal value, int places)
        {
            return Math.Round(value, places, MidpointRounding.AwayFromZero);
        }

        /// <summary>
        /// Provides a similar api to Javascript's
        /// .toFixed(), except returning a useful double!
        /// Note: this is different from .TruncateTo since that will
        /// truncate the value, whereas this will round
        /// </summary>
        /// <param name="value">Source double value</param>
        /// <param name="places">Number of double places required</param>
        /// <returns></returns>
        public static double ToFixed(this double value, int places)
        {
            return Math.Round(value, places, MidpointRounding.AwayFromZero);
        }

        /// <summary>
        /// Attempts to convert any object to an IEnumerable<T>
        /// - existing IEnumerables will "just work"
        /// - where possible, types are cast or converted
        ///   - eg an array of strings which are numbers will be converted to ints if required
        /// - also deals with objects which don't implement IEnumerable, but are enumerable
        ///   in a foreach as per C#/.NET compile-time duck-typing, like Regex's MatchCollection
        /// </summary>
        /// <param name="src">Object to operate on</param>
        /// <typeparam name="T">Desired collection element type</typeparam>
        /// <returns></returns>
        public static IEnumerable<T> AsEnumerable<T>(
            this object src)
        {
            if (src == null)
            {
                return new T[0];
            }

            var asEnumerable = src as IEnumerable;
            if (asEnumerable != null)
            {
                return Enumerate<T>(asEnumerable.GetEnumerator());
            }

            var wrapped = new EnumerableWrapper<T>(src);
            if (!wrapped.IsValid)
            {
                return new T[0];
            }

            return wrapped;
        }

        private static IEnumerable<T> Enumerate<T>(IEnumerator enumerator)
        {
            while (enumerator.MoveNext())
            {
                if (enumerator.Current is T current)
                {
                    yield return current;
                }
                else if (TryChangeType<T>(enumerator.Current, out var converted))
                {
                    yield return converted;
                }
                else
                {
                    throw new InvalidOperationException(
                        $"Object of type {enumerator.Current} cannot be converted to {typeof(T)}"
                    );
                }
            }
        }

        /// <summary>
        /// Analogous to TryParse methods, this will attempt to convert a value to
        /// the type T, returning true if it can, and populating the output parameter
        /// </summary>
        /// <param name="input">Value to work on</param>
        /// <param name="output">Output parameter to collect result</param>
        /// <typeparam name="T">Desired type</typeparam>
        /// <returns>True when can ChangeType, false otherwise</returns>
        public static bool TryChangeType<T>(
            this object input,
            out T output)
        {
            if (input is T immediateResult)
            {
                output = immediateResult;
                return true;
            }

            var result = TryChangeType(input, typeof(T), out var outputObj);
            output = (T) outputObj;
            return result;
        }

        /// <summary>
        /// Analogous to TryParse methods, this will attempt to convert a value to
        /// the type requiredType, returning true if it can, and populating the output parameter
        /// </summary>
        /// <param name="input">Value to work on</param>
        /// <param name="requiredType">The required type</param>
        /// <param name="output">Output parameter to collect result</param>
        /// <returns>True when can ChangeType, false otherwise</returns>
        public static bool TryChangeType(
            this object input,
            Type requiredType,
            out object output)
        {
            try
            {
                output = Convert.ChangeType(input, requiredType);
                return true;
            }
            catch
            {
                var method = GenericDefaultOfT.MakeGenericMethod(requiredType);
                output = method.Invoke(null, new object[0]);
                return false;
            }
        }

        private static readonly MethodInfo GenericDefaultOfT = typeof(ObjectExtensions)
            .GetMethod(nameof(Default), BindingFlags.Static | BindingFlags.NonPublic);

        private static T Default<T>()
        {
            return default(T);
        }

        /// <summary>
        /// Tests if the given object is an instance of the type T
        /// - returns false if obj is null
        /// - returns true if T is the exact type of obj
        /// - returns true if T is a base type of obj
        /// - returns true if T is an interface implemented by obj
        /// - returns false otherwise
        /// </summary>
        /// <param name="obj"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static bool IsInstanceOf<T>(this object obj)
        {
            var objType = obj?.GetType();
            if (objType is null)
            {
                return false;
            }

            var searchType = typeof(T);

            var search = searchType.IsInterface
                ? objType.GetAllImplementedInterfaces()
                : objType.Ancestry();
            return search.Contains(searchType);
        }

        private static readonly BindingFlags _publicStatic =
            BindingFlags.Public | BindingFlags.Static;

        private static readonly MethodInfo GenericIsInstanceOf
            = typeof(ObjectExtensions)
                .GetMethods(_publicStatic)
                .Single(mi => mi.IsGenericMethod &&
                    mi.Name == nameof(ObjectExtensions.IsInstanceOf));

        /// <summary>
        /// Tests if the given object is an instance of the provided type
        /// - returns false if obj is null
        /// - returns true if the type is the exact type of obj
        /// - returns true if the type is a base type of obj
        /// - returns true if the type is an interface implemented by obj
        /// - returns false otherwise
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool IsInstanceOf(
            this object obj,
            Type type
        )
        {
            var method = GenericIsInstanceOf.MakeGenericMethod(
                type
            );
            return (bool) method.Invoke(null, new[] { obj });
        }

        /// <summary>
        /// Determines whether or not an arbitrary object is a RuntimeType
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool IsRuntimeType(this object obj)
        {
            var objType = obj?.GetType();
            return objType is not null &&
                objType.Name == "RuntimeType" &&
                objType.Namespace == "System";
        }
    }
}


text:
import Ember from 'ember';
import layout from '../../templates/components/bs-modal/header';

/**

 Modal header element used within [Components.Modal](Components.Modal.html) components. See there for examples.

 @class ModalHeader
 @namespace Components
 @extends Ember.Component
 @public
 */
export default Ember.Component.extend({
  layout,
  classNames: ['modal-header'],

  /**
   * Show a close button (x icon)
   *
   * @property closeButton
   * @type boolean
   * @default true
   * @public
   */
  closeButton: true,

  /**
   * The title to display in the modal header
   *
   * @property title
   * @type string
   * @default null
   * @public
   */
  title: null,

  /**
   * @event onClose
   * @public
   */
  onClose() {}

});

redpajama_set_name: RedPajamaGithub


text:
package twilightforest.client.renderer.entity;

import net.minecraft.client.model.ModelBase;
import net.minecraft.client.renderer.entity.RenderPig;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;

public class RenderTFBoar
  extends RenderPig
{
  private static final ResourceLocation textureLoc = new ResourceLocation("twilightforest:textures/model/wildboar.png");

  public RenderTFBoar(ModelBase par1ModelBase, ModelBase par2ModelBase, float par3) {
    super(par1ModelBase, par2ModelBase, par3);
  }

  protected ResourceLocation func_110775_a(Entity par1Entity)
  {
    return textureLoc;
  }
}


text:
package dyvilx.tools.compiler.ast.statement;

import dyvil.collection.iterator.ArrayIterator;
import dyvil.lang.Formattable;
import dyvil.lang.Name;
import dyvil.reflect.Modifiers;
import dyvil.source.position.SourcePosition;
import dyvilx.tools.compiler.ast.context.*;
import dyvilx.tools.compiler.ast.expression.IValue;
import dyvilx.tools.compiler.ast.expression.IValueList;
import dyvilx.tools.compiler.ast.expression.access.FieldAccess;
import dyvilx.tools.compiler.ast.expression.access.MethodCall;
import dyvilx.tools.compiler.ast.field.IDataMember;
import dyvilx.tools.compiler.ast.field.IVariable;
import dyvilx.tools.compiler.ast.generic.ITypeContext;
import dyvilx.tools.compiler.ast.header.IClassCompilableList;
import dyvilx.tools.compiler.ast.header.ICompilableList;
import dyvilx.tools.compiler.ast.member.ClassMember;
import dyvilx.tools.compiler.ast.member.MemberKind;
import dyvilx.tools.compiler.ast.method.IMethod;
import dyvilx.tools.compiler.ast.method.MatchList;
import dyvilx.tools.compiler.ast.parameter.ArgumentList;
import dyvilx.tools.compiler.ast.statement.control.Label;
import dyvilx.tools.compiler.ast.type.IType;
import dyvilx.tools.compiler.ast.type.builtin.Types;
import dyvilx.tools.compiler.backend.exception.BytecodeException;
import dyvilx.tools.compiler.backend.method.MethodWriter;
import dyvilx.tools.compiler.config.Formatting;
import dyvilx.tools.compiler.transform.Names;
import dyvilx.tools.compiler.transform.TypeChecker;
import dyvilx.tools.compiler.util.Markers;
import dyvilx.tools.compiler.util.Util;
import dyvilx.tools.parsing.marker.MarkerList;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class StatementList implements IValue, IValueList, IDefaultContext, ILabelContext
{
	private static final TypeChecker.MarkerSupplier RETURN_MARKER_SUPPLIER = TypeChecker
		                                                                         .markerSupplier("statementlist.return",
		                                                                              "type.expected",
		                                                                              "return.type");
	protected            SourcePosition             position;

	protected IValue[] values;
	protected int      valueCount;
	protected Label[]  labels;

	// Metadata
	protected List<IVariable> variables;
	protected List<IMethod>   methods;
	protected IType           returnType;

	public StatementList()
	{
		this.values = new IValue[3];
	}

	public StatementList(SourcePosition position)
	{
		this.position = position;
		this.values = new IValue[3];
	}

	@Override
	public SourcePosition getPosition()
	{
		return this.position;
	}

	@Override
	public void setPosition(SourcePosition position)
	{
		this.position = position;
	}

	@Override
	public int valueTag()
	{
		return STATEMENT_LIST;
	}

	@Override
	public boolean isStatement()
	{
		return true;
	}

	@Override
	public boolean isUsableAsStatement()
	{
		return true;
	}

	@Override
	public boolean isResolved()
	{
		return this.valueCount == 0 || this.values[this.valueCount - 1].isResolved();
	}

	@Override
	public IType getType()
	{
		if (this.returnType != null)
		{
			return this.returnType;
		}
		if (this.valueCount == 0)
		{
			return this.returnType = Types.VOID;
		}
		return this.returnType = this.values[this.valueCount - 1].getType();
	}

	@Override
	public IValue withType(IType type, ITypeContext typeContext, MarkerList markers, IContext context)
	{
		if (this.valueCount <= 0)
		{
			return Types.isVoid(type) ? this : null;
		}

		context = context.push(this);

		final IValue value = this.values[this.valueCount - 1];
		if (Types.isVoid(type) && !value.isStatement())
		{
			final IValue applyStatementCall = resolveApplyStatement(markers, context, value);
			if (applyStatementCall != null)
			{
				this.returnType = type;
				this.values[this.valueCount - 1] = applyStatementCall;
				return this;
			}
		}

		final IValue typed = TypeChecker
			                     .convertValue(value, type, typeContext, markers, context, RETURN_MARKER_SUPPLIER);

		context.pop();

		if (typed != null)
		{
			this.values[this.valueCount - 1] = typed;
			this.returnType = typed.getType();
		}

		return this;
	}

	@Override
	public boolean isType(IType type)
	{
		if (this.valueCount > 0)
		{
			return this.values[this.valueCount - 1].isType(type);
		}
		return Types.isVoid(type);
	}

	@Override
	public int getTypeMatch(IType type, IImplicitContext implicitContext)
	{
		if (this.valueCount <= 0)
		{
			return MISMATCH;
		}
		return this.values[this.valueCount - 1].getTypeMatch(type, implicitContext);
	}

	@Override
	public Iterator<IValue> iterator()
	{
		return new ArrayIterator<>(this.values, 0, this.valueCount);
	}

	@Override
	public int size()
	{
		return this.valueCount;
	}

	@Override
	public boolean isEmpty()
	{
		return this.valueCount == 0;
	}

	@Override
	public void set(int index, IValue value)
	{
		this.values[index] = value;
	}

	@Override
	public void add(IValue value)
	{
		final int index = this.valueCount++;
		if (index >= this.values.length)
		{
			final IValue[] temp = new IValue[index + 1];
			System.arraycopy(this.values, 0, temp, 0, index);
			this.values = temp;
		}
		this.values[index] = value;
	}

	@Override
	public void add(Name label, IValue value)
	{
		final int index = this.valueCount;
		this.add(value);

		final Label theLabel = new Label(label, value);

		if (this.labels == null)
		{
			this.labels = new Label[index + 1];
			this.labels[index] = theLabel;
			return;
		}
		if (index >= this.labels.length)
		{
			final Label[] temp = new Label[index + 1];
			System.arraycopy(this.labels, 0, temp, 0, this.labels.length);
			this.labels = temp;
		}
		this.labels[index] = theLabel;
	}

	@Override
	public IValue get(int index)
	{
		return this.values[index];
	}

	@Override
	public IDataMember resolveField(Name name)
	{
		if (this.variables == null)
		{
			return null;
		}

		// Intentionally start at the last variable
		for (int i = this.variables.size() - 1; i >= 0; i--)
		{
			final IVariable variable = this.variables.get(i);
			if (variable.getName() == name)
			{
				return variable;
			}
		}

		return null;
	}

	@Override
	public IValue resolveImplicit(IType type)
	{
		if (type == null || this.variables == null)
		{
			return null;
		}

		// Intentionally start at the last variable, so the last declared implicit variable has precedence
		for (int i = this.variables.size() - 1; i >= 0; i--)
		{
			final IVariable variable = this.variables.get(i);
			if (variable.hasModifier(Modifiers.IMPLICIT) && Types.isSuperType(type, variable.getType()))
			{
				return new FieldAccess(variable);
			}
		}

		return null;
	}

	@Override
	public void getMethodMatches(MatchList<IMethod> list, IValue receiver, Name name, ArgumentList arguments)
	{
		if (this.methods == null)
		{
			return;
		}

		for (IMethod method : this.methods)
		{
			method.checkMatch(list, receiver, name, arguments);
		}
	}

	@Override
	public void getImplicitMatches(MatchList<IMethod> list, IValue value, IType targetType)
	{
		if (this.methods == null)
		{
			return;
		}

		for (IMethod method : this.methods)
		{
			method.checkImplicitMatch(list, value, targetType);
		}
	}

	@Override
	public Label resolveLabel(Name name)
	{
		if (this.labels != null)
		{
			for (Label label : this.labels)
			{
				if (label != null && name == label.name)
				{
					return label;
				}
			}
		}

		return null;
	}

	@Override
	public Label getContinueLabel()
	{
		return null;
	}

	@Override
	public Label getBreakLabel()
	{
		return null;
	}

	@Override
	public boolean isMember(IVariable variable)
	{
		return this.variables != null && this.variables.contains(variable);
	}

	@Override
	public void resolveTypes(MarkerList markers, IContext context)
	{
		// We don't push this context because Statement Lists can't define any types (yet)

		for (int i = 0; i < this.valueCount; i++)
		{
			this.values[i].resolveTypes(markers, context);
		}
	}

	@Override
	public void resolveStatement(ILabelContext context, MarkerList markers)
	{
		final ILabelContext labelContext = new CombiningLabelContext(this, context);
		for (int i = 0; i < this.valueCount; i++)
		{
			this.values[i].resolveStatement(labelContext, markers);
		}
	}

	@Override
	public IValue resolve(MarkerList markers, IContext context)
	{
		if (this.valueCount <= 0)
		{
			return this;
		}

		context = context.push(this);

		// Resolve and check all values
		final int lastIndex = this.valueCount - 1;
		for (int i = 0; i < this.valueCount; i++)
		{
			final IValue resolvedValue = this.values[i] = this.values[i].resolve(markers, context);
			final int valueTag = resolvedValue.valueTag();

			if (valueTag == IValue.VARIABLE)
			{
				this.addVariable((VariableStatement) resolvedValue, markers, context);
				continue;
			}
			if (valueTag == IValue.MEMBER_STATEMENT)
			{
				this.addMethod((MemberStatement) resolvedValue, markers);
				continue;
			}

			if (i == lastIndex)
			{
				break;
			}

			// Try to resolve an applyStatement method

			if (!resolvedValue.isStatement())
			{
				final IValue applyStatementCall = resolveApplyStatement(markers, context, resolvedValue);
				if (applyStatementCall != null)
				{
					this.values[i] = applyStatementCall;
					continue;
				}
			}

			this.values[i] = IStatement.checkStatement(markers, context, resolvedValue, "statementlist.statement");
		}

		context.pop();

		return this;
	}

	private static IValue resolveApplyStatement(MarkerList markers, IContext context, IValue resolvedValue)
	{
		final ArgumentList arguments = new ArgumentList(resolvedValue);

		final IValue implicitValue = context.resolveImplicit(null);
		if (implicitValue != null)
		{
			final IValue call = resolveApplyStatement(markers, context, arguments,
			                                          implicitValue.resolve(markers, context));
			if (call != null)
			{
				return call;
			}
		}

		return resolveApplyStatement(markers, context, arguments, null);
	}

	private static IValue resolveApplyStatement(MarkerList markers, IContext context, ArgumentList arguments,
		IValue receiver)
	{
		final MethodCall call = new MethodCall(arguments.getFirst().getPosition(), receiver, Names.applyStatement,
		                                       arguments);
		return call.resolveCall(markers, context, false);
	}

	protected void addVariable(VariableStatement initializer, MarkerList markers, IContext context)
	{
		final IVariable variable = initializer.variable;
		final Name variableName = variable.getName();

		// Additional Semantic Analysis

		// Uninitialized Variables
		if (variable.getValue() == null)
		{
			variable.setValue(variable.getType().getDefaultValue());
			markers.add(Markers.semanticError(variable.getPosition(), "variable.uninitialized", variableName));
		}

		// Variable Name Shadowing
		final IDataMember dataMember = context.resolveField(variableName);
		if (dataMember != null && dataMember.isLocal() && !variable.hasModifier(Modifiers.GENERATED))
		{
			markers.add(Markers.semantic(initializer.getPosition(), "variable.shadow", variableName));
		}

		// Actually add the Variable to the List (this has to happen after checking for shadowed variables)

		this.addVariable(variable);
	}

	public void addVariable(IVariable variable)
	{
		if (this.variables == null)
		{
			this.variables = new ArrayList<>();
		}
		this.variables.add(variable);
	}

	protected void addMethod(MemberStatement memberStatement, MarkerList markers)
	{
		final ClassMember member = memberStatement.member;
		final MemberKind memberKind = member.getKind();
		if (memberKind != MemberKind.METHOD)
		{
			markers.add(
				Markers.semantic(member.getPosition(), "statementlist.declaration.invalid", Util.memberNamed(member)));

			return;
		}

		final IMethod method = (IMethod) member;

		if (this.methods == null)
		{
			this.methods = new ArrayList<>();
			this.methods.add(method);
			return;
		}

		final Name methodName = method.getName();
		final int parameterCount = method.getParameters().size();
		final String desc = method.getDescriptor();
		for (IMethod candidate : this.methods)
		{
			if (candidate.getName() == methodName // same name
			    && candidate.getParameters().size() == parameterCount && candidate.getDescriptor().equals(desc))
			{
				markers.add(Markers
					            .semanticError(memberStatement.getPosition(), "method.duplicate.descriptor", methodName,
					                           desc));
			}
		}

		this.methods.add(method);
	}

	@Override
	public void checkTypes(MarkerList markers, IContext context)
	{
		context = context.push(this);

		for (int i = 0; i < this.valueCount; i++)
		{
			this.values[i].checkTypes(markers, context);
		}

		context.pop();
	}

	@Override
	public void check(MarkerList markers, IContext context)
	{
		context = context.push(this);

		for (int i = 0; i < this.valueCount; i++)
		{
			this.values[i].check(markers, context);
		}

		context.pop();
	}

	@Override
	public IValue foldConstants()
	{
		if (this.valueCount == 1)
		{
			return this.values[0].foldConstants();
		}

		for (int i = 0; i < this.valueCount; i++)
		{
			this.values[i] = this.values[i].foldConstants();
		}
		return this;
	}

	@Override
	public IValue cleanup(ICompilableList compilableList, IClassCompilableList classCompilableList)
	{
		if (this.valueCount == 1)
		{
			return this.values[0].cleanup(compilableList, classCompilableList);
		}

		for (int i = 0; i < this.valueCount; i++)
		{
			this.values[i] = this.values[i].cleanup(compilableList, classCompilableList);
		}
		return this;
	}

	@Override
	public void writeExpression(MethodWriter writer, IType type) throws BytecodeException
	{
		int statementCount = this.valueCount - 1;
		if (statementCount < 0)
		{
			return;
		}

		dyvilx.tools.asm.Label start = new dyvilx.tools.asm.Label();
		dyvilx.tools.asm.Label end = new dyvilx.tools.asm.Label();

		writer.visitLabel(start);
		int localCount = writer.localCount();

		if (this.labels == null)
		{
			// Write all statements except the last one
			for (int i = 0; i < statementCount; i++)
			{
				this.values[i].writeExpression(writer, Types.VOID);
			}

			// Write the last expression
			this.values[statementCount].writeExpression(writer, type);
		}
		else
		{
			final int labelCount = this.labels.length;
			Label label;

			// Write all statements except the last one
			for (int i = 0; i < statementCount; i++)
			{
				if (i < labelCount && (label = this.labels[i]) != null)
				{
					writer.visitLabel(label.getTarget());
				}

				this.values[i].writeExpression(writer, Types.VOID);
			}

			// Write last expression (and label)
			if (statementCount < labelCount && (label = this.labels[statementCount]) != null)
			{
				writer.visitLabel(label.getTarget());
			}

			this.values[statementCount].writeExpression(writer, type);
		}

		writer.resetLocals(localCount);
		writer.visitLabel(end);

		if (this.variables == null)
		{
			return;
		}

		for (IVariable variable : this.variables)
		{
			variable.writeLocal(writer, start, end);
		}
	}

	@Override
	public String toString()
	{
		return Formattable.toString(this);
	}

	@Override
	public void toString(String prefix, StringBuilder buffer)
	{
		if (this.valueCount == 0)
		{
			if (Formatting.getBoolean("statement.empty.newline"))
			{
				buffer.append('{').append('\n').append(prefix).append('}');
			}
			else if (Formatting.getBoolean("statement.empty.space_between"))
			{
				buffer.append("{ }");
			}
			else
			{
				buffer.append("{}");
			}
			return;
		}

		buffer.append('{').append('\n');

		String indentedPrefix = Formatting.getIndent("statement.indent", prefix);
		int prevLine = 0;
		Label label;

		for (int i = 0; i < this.valueCount; i++)
		{
			IValue value = this.values[i];
			SourcePosition pos = value.getPosition();
			buffer.append(indentedPrefix);

			if (pos != null)
			{
				if (pos.startLine() - prevLine > 1 && i > 0)
				{
					buffer.append('\n').append(indentedPrefix);
				}
				prevLine = pos.endLine();
			}

			if (this.labels != null && i < this.labels.length && (label = this.labels[i]) != null)
			{
				buffer.append("label ");
				buffer.append(label.name);

				if (Formatting.getBoolean("label.separator.space_before"))
				{
					buffer.append(' ');
				}
				buffer.append(':');
				if (Formatting.getBoolean("label.separator.newline_after"))
				{
					buffer.append('\n').append(indentedPrefix);
				}
				else if (Formatting.getBoolean("label.separator.newline_after"))
				{
					buffer.append(' ');
				}
			}

			value.toString(indentedPrefix, buffer);

			if (Formatting.getBoolean("statement.semicolon"))
			{
				buffer.append(';');
			}
			buffer.append('\n');
		}

		buffer.append(prefix).append('}');
	}
}


text:
<?php
	defined('C5_EXECUTE') or die("Access Denied.");

	class Concrete5_Controller_Block_GoogleMap extends BlockController {

		protected $btTable = 'btGoogleMap';
		protected $btInterfaceWidth = "400";
		protected $btInterfaceHeight = "200";
		protected $btCacheBlockRecord = true;
		protected $btCacheBlockOutput = true;
		protected $btCacheBlockOutputOnPost = true;
		protected $btCacheBlockOutputForRegisteredUsers = false;

		public $title = "";
		public $location = "";
		public $latitude = "";
		public $longitude = "";
		public $zoom = 14;

		/**
		 * Used for localization. If we want to localize the name/description we have to include this
		 */
		public function getBlockTypeDescription() {
			return t("Enter an address and a Google Map of that location will be placed in your page.");
		}

		public function getBlockTypeName() {
			return t("Google Map");
		}

		public function validate($args) {
			$error = Loader::helper('validation/error');

			if(!is_numeric($args['zoom'])) {
				$error->add(t('Please enter a zoom number from 0 to 21.'));
			}

			if($error->has()) {
				return $error;
			}
		}

		public function on_page_view() {
			$html = Loader::helper('html');
			$c = Page::getCurrentPage();
			if (!$c->isEditMode()) {
				$this->addFooterItem('');
				$this->addFooterItem('');
			}
		}

		public function view(){
			$this->set('bID', $this->bID);
			$this->set('title', $this->title);
			$this->set('location', $this->location);
			$this->set('latitude', $this->latitude);
			$this->set('longitude', $this->longitude);
			$this->set('zoom', $this->zoom);
		}

		public function save($data) {
			$args['title'] = isset($data['title']) ? trim($data['title']) : '';
			$args['location'] = isset($data['location']) ? trim($data['location']) : '';
			$args['zoom'] = (intval($data['zoom'])>=0 && intval($data['zoom'])<=21) ? intval($data['zoom']) : 14;

			if( strlen($args['location'])>0 ){
				$coords = $this->lookupLatLong($args['location']);
				$args['latitude']=floatval($coords['lat']);
				$args['longitude']=floatval($coords['lng']);
			} else {
				$args['latitude']=0;
				$args['longitude']=0;
			}

			parent::save($args);
		}

		public function lookupLatLong($address) {
			if(preg_match('/^\\s*([+\\-]?\\d+(\\.\\d*)?)[\\s,;]+([+\\-]?\\d+(\\.\\d*)?)\\s*$/', $address, $matches)) {
				return array('lat' => floatval($matches[1]), 'lng' => floatval($matches[3]));
			}
			$json = Loader::helper('json');
			$fh = Loader::helper('file');

			$base_url = "http://maps.google.com/maps/api/geocode/json?sensor=false";
			$request_url = $base_url . "&address=".urlencode($address);

			$res = $fh->getContents($request_url);
			$res = $json->decode($res);
			if(!is_object($res)) {
				return false;
			}
			switch($res->status) {
				case 'OK':
					$lat = $res->results[0]->geometry->location->lat;
					$lng = $res->results[0]->geometry->location->lng;
					return array('lat'=>$lat,'lng'=>$lng);
					break;
				case 'ZERO_RESULTS':
				case 'OVER_QUERY_LIMIT':
				case 'REQUEST_DENIED':
				case 'INVALID_REQUEST':
					return false;
					break;
			}
		}

	}


text:
const logger = require('winston');
const express = require('express');
const path = require('path');
const http = require('http');

const websockets = require('../websockets');

class Webserver {
    constructor() {
        this.app  = express();
        this.http = http.createServer(this.app);

        this.wss = new websockets.boards(this.http);

        this.static = path.resolve(__dirname, '..', '..', 'boards');
        this.assets = path.resolve(__dirname, '..', '..', 'assets');

        this.app.use(express.static(this.static));
        this.app.use(express.static(this.assets));

        const fallback = (req, res, next) => {
            res.sendFile(path.resolve(this.static, 'app.html'));
        }

        this.app.get('/', fallback);
        this.app.get('*', fallback);

        logger.info('web:boards:listen (9185)');
        this.http.listen(9185);
    }
}

module.exports = new Webserver();


text:
package com.b2international.snowowl.snomed.importer.rf2.validation;

import static com.google.common.collect.Sets.newHashSet;

import java.net.URL;
import java.util.List;
import java.util.Set;

import org.eclipse.core.runtime.IProgressMonitor;

import com.b2international.snowowl.snomed.common.SnomedRf2Headers;
import com.b2international.snowowl.snomed.importer.net4j.DefectType;
import com.b2international.snowowl.snomed.importer.net4j.ImportConfiguration;
import com.b2international.snowowl.snomed.importer.rf2.model.ComponentImportType;

/**
 * Represents a release file validator that validates the simple map type reference set.
 */
public class SnomedSimpleMapTypeRefSetValidator extends SnomedRefSetValidator {

	private Set<String> mapTargetIsEmpty = newHashSet();

	public SnomedSimpleMapTypeRefSetValidator(final ImportConfiguration configuration, final URL releaseUrl, final SnomedValidationContext context) {
		super(configuration, releaseUrl, ComponentImportType.SIMPLE_MAP_TYPE_REFSET, context, SnomedRf2Headers.SIMPLE_MAP_TYPE_HEADER);
	}

	protected SnomedSimpleMapTypeRefSetValidator(ImportConfiguration configuration, URL releaseUrl, ComponentImportType importType, SnomedValidationContext validationUtil, String[] expectedHeader) {
		super(configuration, releaseUrl, importType, validationUtil, expectedHeader);
	}

	@Override
	protected void doValidate(final List<String> row) {
		super.doValidate(row);
		validateMapTarget(row);
	}

	@Override
	protected void doValidate(String effectiveTime, IProgressMonitor monitor) {
		super.doValidate(effectiveTime, monitor);
		addDefect(DefectType.SIMPLE_MAP_TARGET_IS_EMPTY, mapTargetIsEmpty);
	}

	@Override
	protected String getName() {
		return "simple map type";
	}

	private void validateMapTarget(final List<String> row) {
		final String uuid = row.get(0);
		final String effectiveTime = row.get(1);
		final String mapTarget = row.get(6);
		if (mapTarget.isEmpty()) {
			mapTargetIsEmpty.add(String.format("Reference set member '%s''s map target is empty", uuid, effectiveTime));
		}
	}

	@Override
	protected void clearCaches() {
		super.clearCaches();
		mapTargetIsEmpty = newHashSet();
	}
}


text:
#region

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using LinqKit;
using Repository.Pattern.DataContext;
using Repository.Pattern.Infrastructure;
using Repository.Pattern.Repositories;
using Repository.Pattern.UnitOfWork;

#endregion

namespace Repository.Pattern.Ef6
{
    public class Repository<TEntity> : IRepositoryAsync<TEntity> where TEntity : class, IObjectState
    {
        #region Private Fields

        private readonly IDataContextAsync _context;
        private readonly DbSet<TEntity> _dbSet;
        private readonly IUnitOfWorkAsync _unitOfWork;

        #endregion Private Fields

        public Repository(IDataContextAsync context, IUnitOfWorkAsync unitOfWork)
        {
            _context = context;
            _unitOfWork = unitOfWork;

            // Temporarily for FakeDbContext, Unit Test and Fakes
            var dbContext = context as DbContext;

            if (dbContext != null)
            {
                _dbSet = dbContext.Set<TEntity>();
            }
            else
            {
                var fakeContext = context as FakeDbContext;

                if (fakeContext != null)
                {
                    _dbSet = fakeContext.Set<TEntity>();
                }
            }
        }

        public virtual TEntity Find(params object[] keyValues)
        {
            return _dbSet.Find(keyValues);
        }

        public virtual IQueryable<TEntity> SelectQuery(string query, params object[] parameters)
        {
            return _dbSet.SqlQuery(query, parameters).AsQueryable();
        }

        public virtual void Insert(TEntity entity)
        {
            entity.ObjectState = ObjectState.Added;;
            _dbSet.Attach(entity);
            _context.SyncObjectState(entity);
        }

        public virtual void InsertRange(IEnumerable<TEntity> entities)
        {
            foreach (var entity in entities)
            {
                Insert(entity);
            }
        }

        public virtual void InsertGraphRange(IEnumerable<TEntity> entities)
        {
            _dbSet.AddRange(entities);
        }

        public virtual void Update(TEntity entity)
        {
            entity.ObjectState = ObjectState.Modified;
            _dbSet.Attach(entity);
            _context.SyncObjectState(entity);
        }

        public virtual void Delete(object id)
        {
            var entity = _dbSet.Find(id);
            Delete(entity);
        }

        public virtual void Delete(TEntity entity)
        {
            entity.ObjectState = ObjectState.Deleted;
            _dbSet.Attach(entity);
            _context.SyncObjectState(entity);
        }

        public IQueryFluent<TEntity> Query()
        {
            return new QueryFluent<TEntity>(this);
        }

        public virtual IQueryFluent<TEntity> Query(IQueryObject<TEntity> queryObject)
        {
            return new QueryFluent<TEntity>(this, queryObject);
        }

        public virtual IQueryFluent<TEntity> Query(Expression<Func<TEntity, bool>> query)
        {
            return new QueryFluent<TEntity>(this, query);
        }

        public IQueryable<TEntity> Queryable()
        {
            return _dbSet;
        }

        public IRepository<T> GetRepository<T>() where T : class, IObjectState
        {
            return _unitOfWork.Repository<T>();
        }

        public virtual async Task<TEntity> FindAsync(params object[] keyValues)
        {
            return await _dbSet.FindAsync(keyValues);
        }

        public virtual async Task<TEntity> FindAsync(CancellationToken cancellationToken, params object[] keyValues)
        {
            return await _dbSet.FindAsync(cancellationToken, keyValues);
        }

        public virtual async Task<bool> DeleteAsync(params object[] keyValues)
        {
            return await DeleteAsync(CancellationToken.None, keyValues);
        }

        public virtual async Task<bool> DeleteAsync(CancellationToken cancellationToken, params object[] keyValues)
        {
            var entity = await FindAsync(cancellationToken, keyValues);

            if (entity == null)
            {
                return false;
            }

            entity.ObjectState = ObjectState.Deleted;
            _dbSet.Attach(entity);

            return true;
        }

        internal IQueryable<TEntity> Select(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            List<Expression<Func<TEntity, object>>> includes = null,
            int? page = null,
            int? pageSize = null)
        {
            IQueryable<TEntity> query = _dbSet;

            if (includes != null)
            {
                query = includes.Aggregate(query, (current, include) => current.Include(include));
            }
            if (orderBy != null)
            {
                query = orderBy(query);
            }
            if (filter != null)
            {
                query = query.AsExpandable().Where(filter);
            }
            if (page != null && pageSize != null)
            {
                query = query.Skip((page.Value - 1)*pageSize.Value).Take(pageSize.Value);
            }
            return query;
        }

        internal async Task<IEnumerable<TEntity>> SelectAsync(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            List<Expression<Func<TEntity, object>>> includes = null,
            int? page = null,
            int? pageSize = null)
        {
            return await Select(filter, orderBy, includes, page, pageSize).ToListAsync();
        }

        // Insert or Updating an object graph
        [Obsolete("Will be renamed to UpsertGraph(TEntity entity) in next version.")]
        public virtual void InsertOrUpdateGraph(TEntity entity)
        {
            SyncObjectGraph(entity);
            _entitesChecked = null;
            _dbSet.Attach(entity);
        }

        // tracking of all processed entities in the object graph when calling SyncObjectGraph
        HashSet<object> _entitesChecked;

        private void SyncObjectGraph(object entity) // scan object graph for all
        {
            // instantiating _entitesChecked so we can keep track of all entities we have scanned, avoid any cyclical issues
            if(_entitesChecked == null)
                _entitesChecked = new HashSet<object>();

            // if already processed skip
            if (_entitesChecked.Contains(entity))
                return;

            // add entity to alreadyChecked collection
            _entitesChecked.Add(entity);

            var objectState = entity as IObjectState;

            // discovered entity with ObjectState.Added, sync this with provider e.g. EF
            if (objectState != null && objectState.ObjectState == ObjectState.Added)
                _context.SyncObjectState((IObjectState)entity);

            // Set tracking state for child collections
            foreach (var prop in entity.GetType().GetProperties())
            {
                // Apply changes to 1-1 and M-1 properties
                var trackableRef = prop.GetValue(entity, null) as IObjectState;
                if (trackableRef != null)
                {
                    // discovered entity with ObjectState.Added, sync this with provider e.g. EF
                    if(trackableRef.ObjectState == ObjectState.Added)
                        _context.SyncObjectState((IObjectState) entity);

                    // recursively process the next property
                    SyncObjectGraph(prop.GetValue(entity, null));
                }

                // Apply changes to 1-M properties
                var items = prop.GetValue(entity, null) as IEnumerable<IObjectState>;

                // collection was empty, nothing to process, continue
                if (items == null) continue;

                // collection isn't empty, continue to recursively scan the elements of this collection
                foreach (var item in items)
                    SyncObjectGraph(item);
            }
        }
    }
}


text:
output = {
  loopback: $.create(loopback)
}


text:
- [ ] Have you followed the guidelines in our [Contributing](https://thorntail.io/community/contributing/) document?
- [ ] Have you created a [JIRA](https://issues.jboss.org/browse/THORN) and used it in the commit message?
- [ ] Have you checked to ensure there aren't other open [Pull Requests](https://github.com/thorntail/thorntail/pulls) for the same issue?
- [ ] Have you built the project locally prior to submission with `mvn clean install`?

-----


text:
@**
 * Generate an HTML radio group
 *
 * Example:
 * {{{
 * @inputRadioGroup(
 *           contactForm("gender"),
 *           options = Seq("M"->"Male","F"->"Female"),
 *           '_label -> "Gender",
 *           '_error -> contactForm("gender").error.map(_.withMessage("select gender")))
 *
 * }}}
 *
 * @param field The form field.
 * @param args Set of extra HTML attributes.
 * @param handler The field constructor.
 *@
@(field: play.api.data.Field, options: Seq[String], args: (Symbol,Any)*)(implicit handler: views.html.helper.FieldConstructor, lang: play.api.i18n.Lang)

@views.html.helper.input(field, args:_*) { (id, name, value, htmlArgs) =>
	<div class="btn-group buttonset" id="@id" data-toggle="buttons">
		@options.map { v =>
	    	<label id="@(id)_@(v)_label" for="@(id)_@v" class="radio-inline btn btn-default @(if(value == Some(v)) "active")">
				@input(field, "radio", id + "_" + v, name, Some(v), true, htmlArgs)

				@if(Messages.isDefinedAt(name + "." + v)) {
			    	@Messages(name + "." + v)
			    } else {
					@v
				}
			</label>
	    }
	    <script type="text/javascript">
			$(window).load(function(){
				$('#@id label').click(function() {
					$(this).closest('.form-group').removeClass('has-error').addClass('has-success');
					$("#@(id)_infosErrorsDiv").hide();
				});
			});
		</script>
	</div>
}


text:
<?php

/**
 * Checks that all file names are lowercased.
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Andy Grunwald <andygrunwald@gmail.com>
 * @copyright 2010-2014 Andy Grunwald
 * @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */
class Generic_Sniffs_Files_LowercasedFilenameSniff implements PHP_CodeSniffer_Sniff
{

    /**
     * Returns an array of tokens this test wants to listen for.
     *
     * @return array
     */
    public function register()
    {
        return array(T_OPEN_TAG);

    }//end register()

    /**
     * Processes this sniff, when one of its tokens is encountered.
     *
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
     * @param int                  $stackPtr  The position of the current token in
     *                                        the stack passed in $tokens.
     *
     * @return void
     */
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        // We are only interested if this is the first open tag.
        if ($stackPtr !== 0) {
            if ($phpcsFile->findPrevious(T_OPEN_TAG, ($stackPtr - 1)) !== false) {
                return;
            }
        }

        $fileName          = basename($phpcsFile->getFilename());
        $lowercaseFileName = strtolower($fileName);
        if ($fileName !== $lowercaseFileName) {
            $data  = array(
                      $fileName,
                      $lowercaseFileName,
                     );
            $error = 'Filename "%s" doesn\'t match the expected filename "%s"';
            $phpcsFile->addError($error, $stackPtr, 'NotFound', $data);
        }

    }//end process()

}//end class

?>


text:
package com.zupcat.model;

import org.json.JSONException;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;

/**
 * It adds features to JSONObject
 */
public class WithIdDataObject extends DataObject {

    public static final String ID_KEY = "_id_";
    private static final long serialVersionUID = 471847964351314234L;

    public WithIdDataObject() {
    }

    public WithIdDataObject(final Map map) {
        super(map);
    }

    public WithIdDataObject(final WithIdDataObject another) {
        super(another);
    }

    public WithIdDataObject(final String source) throws JSONException {
        super(source);
    }

    public String getId() {
        return optString(ID_KEY, null);
    }

    public void setId(final String id) {
        put(ID_KEY, id);
    }

    private void writeObject(final ObjectOutputStream objectOutputStream) throws IOException {
        objectOutputStream.defaultWriteObject();
        objectOutputStream.writeUTF(this.toString());
    }

    private void readObject(final ObjectInputStream objectInputStream) throws ClassNotFoundException, IOException {
        // default deserialization
        objectInputStream.defaultReadObject();

        this.mergeWith(new WithIdDataObject(objectInputStream.readUTF()));
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;

        if (!(o instanceof WithIdDataObject)) return false;

        final WithIdDataObject that = (WithIdDataObject) o;

        final String myId = getId();
        final String thatId = that.getId();

        return !(myId != null ? !myId.equals(thatId) : thatId != null);
    }

    @Override
    public int hashCode() {
        final String myId = getId();

        return myId != null ? myId.hashCode() : 0;
    }
}


text:
package com.diligentengine.tutorial13_shadowmap;
import com.diligentengine.android.common.DiligentApplicationBase;

public class Tutorial13Application extends DiligentApplicationBase {

}


text:
package org.apache.sentry.policy.search;

import java.io.File;
import java.io.IOException;
import java.util.Collections;

import junit.framework.Assert;

import org.apache.commons.io.FileUtils;
import org.apache.sentry.core.common.ActiveRoleSet;
import org.apache.sentry.policy.common.PolicyEngine;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.io.Files;

public class TestSearchPolicyNegative {

  @SuppressWarnings("unused")
  private static final Logger LOGGER = LoggerFactory
      .getLogger(TestSearchPolicyNegative.class);

  private File baseDir;
  private File globalPolicyFile;
  private File otherPolicyFile;

  @Before
  public void setup() {
    baseDir = Files.createTempDir();
    globalPolicyFile = new File(baseDir, "global.ini");
    otherPolicyFile = new File(baseDir, "other.ini");
  }

  @After
  public void teardown() {
    if(baseDir != null) {
      FileUtils.deleteQuietly(baseDir);
    }
  }

  private void append(String from, File to) throws IOException {
    Files.append(from + "\n", to, Charsets.UTF_8);
  }

  @Test
  public void testPerDbFileException() throws Exception {
    append("[databases]", globalPolicyFile);
    append("other_group_db = " + otherPolicyFile.getPath(), globalPolicyFile);
    append("[groups]", otherPolicyFile);
    append("other_group = some_role", otherPolicyFile);
    append("[roles]", otherPolicyFile);
    append("some_role = collection=c1", otherPolicyFile);
    SearchPolicyFileBackend policy = new SearchPolicyFileBackend(globalPolicyFile.getPath());
    Assert.assertEquals(Collections.emptySet(),
        policy.getPrivileges(Sets.newHashSet("other_group"), ActiveRoleSet.ALL));
  }

  @Test
  public void testCollectionRequiredInRole() throws Exception {
    append("[groups]", globalPolicyFile);
    append("group = some_role", globalPolicyFile);
    append("[roles]", globalPolicyFile);
    append("some_role = action=query", globalPolicyFile);
    PolicyEngine policy = new SearchPolicyFileBackend(globalPolicyFile.getPath());
    ImmutableSet<String> permissions = policy.getPrivileges(Sets.newHashSet("group"), ActiveRoleSet.ALL);
    Assert.assertTrue(permissions.toString(), permissions.isEmpty());
  }

  @Test
  public void testGroupIncorrect() throws Exception {
    append("[groups]", globalPolicyFile);
    append("group = malicious_role", globalPolicyFile);
    append("[roles]", globalPolicyFile);
    append("malicious_role = collection=*", globalPolicyFile);
    PolicyEngine policy = new SearchPolicyFileBackend(globalPolicyFile.getPath());
    ImmutableSet<String> permissions = policy.getPrivileges(Sets.newHashSet("incorrectGroup"), ActiveRoleSet.ALL);
    Assert.assertTrue(permissions.toString(), permissions.isEmpty());
  }
}


text:
<?php

namespace OC\Files\Storage;

class FTP extends \OC\Files\Storage\StreamWrapper{
	private $password;
	private $user;
	private $host;
	private $secure;
	private $root;

	private static $tempFiles=array();

	public function __construct($params) {
		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
			$this->host=$params['host'];
			$this->user=$params['user'];
			$this->password=$params['password'];
			if (isset($params['secure'])) {
				if (is_string($params['secure'])) {
					$this->secure = ($params['secure'] === 'true');
				} else {
					$this->secure = (bool)$params['secure'];
				}
			} else {
				$this->secure = false;
			}
			$this->root=isset($params['root'])?$params['root']:'/';
			if ( ! $this->root || $this->root[0]!='/') {
				$this->root='/'.$this->root;
			}
			if (substr($this->root, -1) !== '/') {
				$this->root .= '/';
			}
		} else {
			throw new \Exception();
		}

	}

	public function getId(){
		return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
	}

	/**
	 * construct the ftp url
	 * @param string $path
	 * @return string
	 */
	public function constructUrl($path) {
		$url='ftp';
		if ($this->secure) {
			$url.='s';
		}
		$url.='://'.$this->user.':'.$this->password.'@'.$this->host.$this->root.$path;
		return $url;
	}

	/**
	 * Unlinks file or directory
	 * @param string $path
	 */
	public function unlink($path) {
		if ($this->is_dir($path)) {
			return $this->rmdir($path);
		}
		else {
			$url = $this->constructUrl($path);
			$result = unlink($url);
			clearstatcache(true, $url);
			return $result;
		}
	}
	public function fopen($path,$mode) {
		switch($mode) {
			case 'r':
			case 'rb':
			case 'w':
			case 'wb':
			case 'a':
			case 'ab':
				//these are supported by the wrapper
				$context = stream_context_create(array('ftp' => array('overwrite' => true)));
				return fopen($this->constructUrl($path), $mode, false, $context);
			case 'r+':
			case 'w+':
			case 'wb+':
			case 'a+':
			case 'x':
			case 'x+':
			case 'c':
			case 'c+':
				//emulate these
				if (strrpos($path, '.')!==false) {
					$ext=substr($path, strrpos($path, '.'));
				} else {
					$ext='';
				}
				$tmpFile=\OCP\Files::tmpFile($ext);
				\OC\Files\Stream\Close::registerCallback($tmpFile, array($this, 'writeBack'));
				if ($this->file_exists($path)) {
					$this->getFile($path, $tmpFile);
				}
				self::$tempFiles[$tmpFile]=$path;
				return fopen('close://'.$tmpFile, $mode);
		}
		return false;
	}

	public function writeBack($tmpFile) {
		if (isset(self::$tempFiles[$tmpFile])) {
			$this->uploadFile($tmpFile, self::$tempFiles[$tmpFile]);
			unlink($tmpFile);
		}
	}

	/**
	 * check if php-ftp is installed
	 */
	public static function checkDependencies() {
		if (function_exists('ftp_login')) {
			return(true);
		} else {
			return array('ftp');
		}
	}

}