text:
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Assert = Lucene.Net.TestFramework.Assert;
using Console = Lucene.Net.Util.SystemConsole;

namespace Lucene.Net.Util
{

    /// <summary>
    /// LUCENENET specific - functionality for scanning the API to ensure
    /// naming and .NET conventions are followed consistently. Not for use
    /// by end users.
    /// </summary>
    public abstract class ApiScanTestBase : LuceneTestCase
    {
        internal ApiScanTestBase() { } // LUCENENET: Not for use by end users

        /// <summary>
        /// Private fields must be upper case separated with underscores,
        /// must be camelCase (optionally may be prefixed with underscore,
        /// but it is preferred not to use the underscore to match Lucene).
        /// </summary>
        private static readonly Regex PrivateFieldName = new Regex("^_?[a-z][a-zA-Z0-9_]*$|^[A-Z0-9_]+$", RegexOptions.Compiled);

        /// <summary>
        /// Protected fields must either be upper case separated with underscores or
        /// must be prefixed with m_ (to avoid naming conflicts with properties).
        /// </summary>
        private static readonly Regex ProtectedFieldName = new Regex("^m_[a-z][a-zA-Z0-9_]*$|^[A-Z0-9_]+$", RegexOptions.Compiled);

        /// <summary>
        /// Method parameters must be camelCase and not begin or end with underscore.
        /// </summary>
        private static readonly Regex MethodParameterName = new Regex("^[a-z](?:[a-zA-Z0-9_]*[a-zA-Z0-9])?$", RegexOptions.Compiled);

        /// <summary>
        /// Interfaces must begin with "I" followed by another captial letter. Note this includes a
        /// fix for generic interface names, that end with `{number}.
        /// </summary>
        private static readonly Regex InterfaceName = new Regex("^I[A-Z][a-zA-Z0-9_]*(?:`\\d+)?$", RegexOptions.Compiled);

        /// <summary>
        /// Class names must be pascal case and not use the interface naming convention.
        /// </summary>
        private static readonly Regex ClassName = new Regex("^[A-Z][a-zA-Z0-9_]*(?:`\\d+)?$", RegexOptions.Compiled);

        /// <summary>
        /// Public members should not contain the word "Comparer". In .NET, these should be named "Comparer".
        /// </summary>
        private static readonly Regex ContainsComparer = new Regex("[Cc]omparator", RegexOptions.Compiled);

        /// <summary>
        /// Public methods and properties should not contain the word "Int" that is not followed by 16, 32, or 64,
        /// "Long", "Short", or "Float". These should be converted to their .NET names "Int32", "Int64", "Int16", and "Short".
        /// Note we need to ignore common words such as "point", "intern", and "intersect".
        /// </summary>
        private static readonly Regex ContainsNonNetNumeric = new Regex("(?<![Pp]o|[Pp]r|[Jj]o)[Ii]nt(?!16|32|64|er|eg|ro)|[Ll]ong(?!est|er)|[Ss]hort(?!est|er)|[Ff]loat", RegexOptions.Compiled);

        ///// <summary>
        ///// Constants should not contain the word INT that is not followed by 16, 32, or 64, LONG, SHORT, or FLOAT
        ///// </summary>
        //private static readonly Regex ConstContainsNonNetNumeric = new Regex("(?<!PO|PR|JO)INT(?!16|32|64|ER|EG|RO)|LONG(?!EST|ER)|SHORT(?!EST|ER)|FLOAT", RegexOptions.Compiled);

        /// <summary>
        /// Matches IL code pattern for a method body with only a return statement for a local variable.
        /// In this case, the array is writable by the consumer.
        /// </summary>
        private static readonly Regex MethodBodyReturnValueOnly = new Regex("\\0\\u0002\\{(?:.|\\\\u\\d\\d\\d\\d|\\0|\\[a-z]){3}\\u0004\\n\\+\\0\\u0006\\*", RegexOptions.Compiled);

        //[Test, LuceneNetSpecific]
        public virtual void TestProtectedFieldNames(Type typeFromTargetAssembly)
        {
            var names = GetInvalidProtectedFields(typeFromTargetAssembly.Assembly);

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " invalid protected field names detected. " +
                "Protected fields must be camelCase and prefixed with 'm_' to prevent naming conflicts with properties.");
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestPrivateFieldNames(Type typeFromTargetAssembly)
        {
            TestPrivateFieldNames(typeFromTargetAssembly, null);
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestPrivateFieldNames(Type typeFromTargetAssembly, string exceptionRegex)
        {
            var names = GetInvalidPrivateFields(typeFromTargetAssembly.Assembly, exceptionRegex);

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " invalid private field names detected. " +
                "Private field names should be camelCase.");
        }

        public virtual void TestPublicFields(Type typeFromTargetAssembly)
        {
            TestPublicFields(typeFromTargetAssembly, null);
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestPublicFields(Type typeFromTargetAssembly, string exceptionRegex)
        {
            var names = GetInvalidPublicFields(typeFromTargetAssembly.Assembly, exceptionRegex);

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " public fields detected. Consider using public properties instead." +
                "Public properties that return arrays should be decorated with the WritableArray attribute.");
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestMethodParameterNames(Type typeFromTargetAssembly)
        {
            var names = GetInvalidMethodParameterNames(typeFromTargetAssembly.Assembly);

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " invalid method parameter names detected. " +
                "Parameter names must be camelCase and may not start or end with '_'.");
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestInterfaceNames(Type typeFromTargetAssembly)
        {
            var names = GetInvalidInterfaceNames(typeFromTargetAssembly.Assembly);

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " invalid interface names detected. " +
                "Interface names must begin with a capital 'I' followed by another capital letter.");
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestClassNames(Type typeFromTargetAssembly)
        {
            var names = GetInvalidClassNames(typeFromTargetAssembly.Assembly);

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " invalid class names detected. " +
                "Class names must be Pascal case, but may not follow the interface naming " +
                "convention of captial 'I' followed by another capital letter.");
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestForPropertiesWithNoGetter(Type typeFromTargetAssembly)
        {
            var names = GetPropertiesWithNoGetter(typeFromTargetAssembly.Assembly);

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " properties with a setter but no getter detected. " +
                "Getters are required for properties. If the main functionality is to set a value, " +
                "consider using a method instead (prefixed with Set).");
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestForPropertiesThatReturnArray(Type typeFromTargetAssembly)
        {
            var names = GetPropertiesThatReturnArray(typeFromTargetAssembly.Assembly);

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " properties that return Array detected. " +
                "Properties should generally not return Array. Change to a method (prefixed with Get) " +
                "or if returning an array that can be written to was intended, decorate with the WritableArray attribute. " +
                "Note that returning an array field from either a property or method means the array can be written to by " +
                "the consumer if the array is not cloned using arr.ToArray().");
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestForMethodsThatReturnWritableArray(Type typeFromTargetAssembly)
        {
            var names = GetMethodsThatReturnWritableArray(typeFromTargetAssembly.Assembly);

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " methods that return a writable Array detected. " +
                "An array should be cloned before returning using arr.ToArray() or if it is intended to be writable, " +
                "decorate with the WritableArray attribute and consider making it a property for clarity.");
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestForPublicMembersContainingComparer(Type typeFromTargetAssembly)
        {
            var names = new List<string>();

            names.AddRange(GetProtectedFieldsContainingComparer(typeFromTargetAssembly.Assembly));
            names.AddRange(GetMembersContainingComparer(typeFromTargetAssembly.Assembly));

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " member names containing the word 'comparer' detected. " +
                "In .NET, we need to change the word 'comparer' to 'comparer'.");
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestForPublicMembersNamedSize(Type typeFromTargetAssembly)
        {
            var names = GetMembersNamedSize(typeFromTargetAssembly.Assembly);

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " member names named 'Size'. " +
                "In .NET, we need to change the name 'Size' to either 'Count' or 'Length', " +
                "and it should generally be made a property.");
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestForPublicMembersContainingNonNetNumeric(Type typeFromTargetAssembly)
        {
            var names = GetMembersContainingNonNetNumeric(typeFromTargetAssembly.Assembly);

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " member names containing the word 'Int' not followed " +
                "by 16, 32, or 64, 'Long', 'Short', or 'Float' detected. " +
                "In .NET, we need to change to 'Short' to 'Int16', 'Int' to 'Int32', 'Long' to 'Int64', and 'Float' to 'Single'.");
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestForTypesContainingNonNetNumeric(Type typeFromTargetAssembly)
        {
            var names = GetTypesContainingNonNetNumeric(typeFromTargetAssembly.Assembly);

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " member names containing the word 'Int' not followed " +
                "by 16, 32, or 64, 'Long', 'Short', or 'Float' detected. " +
                "In .NET, we need to change to 'Short' to 'Int16', 'Int' to 'Int32', 'Long' to 'Int64', and 'Float' to 'Single'." +
                "\n\nIMPORTANT: Before making changes, make sure to rename any types with ambiguous use of the word `Single` (meaning 'singular' rather than `System.Single`) to avoid confusion.");
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestForPublicMembersWithNullableEnum(Type typeFromTargetAssembly)
        {
            var names = GetPublicNullableEnumMembers(typeFromTargetAssembly.Assembly);

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " members that are type nullable enum detected. " +
                "Nullable enum parameters, fields, methods, and properties should be eliminated (where possible), either by " +
                "eliminating the logic that depends on 'null'. Sometimes, it makes sense to keep a nullable enum parameter. " +
                "In those cases, mark the member with the [ExceptionToNullableEnumConvention] attribute.");
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestForMembersAcceptingOrReturningIEnumerable(Type typeFromTargetAssembly)
        {
            TestForMembersAcceptingOrReturningIEnumerable(typeFromTargetAssembly, null);
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestForMembersAcceptingOrReturningIEnumerable(Type typeFromTargetAssembly, string exceptionRegex)
        {
            var names = GetMembersAcceptingOrReturningType(typeof(IEnumerable<>), typeFromTargetAssembly.Assembly, false, exceptionRegex);

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " members that accept or return IEnumerable<T> detected.");
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestForMembersAcceptingOrReturningListOrDictionary(Type typeFromTargetAssembly)
        {
            TestForMembersAcceptingOrReturningListOrDictionary(typeFromTargetAssembly, null);
        }

        //[Test, LuceneNetSpecific]
        public virtual void TestForMembersAcceptingOrReturningListOrDictionary(Type typeFromTargetAssembly, string exceptionRegex)
        {
            var names = new List<string>();
            names.AddRange(GetMembersAcceptingOrReturningType(typeof(List<>), typeFromTargetAssembly.Assembly, true, exceptionRegex));
            names.AddRange(GetMembersAcceptingOrReturningType(typeof(Dictionary<,>), typeFromTargetAssembly.Assembly, true, exceptionRegex));

            //if (VERBOSE)
            //{
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
            //}

            Assert.IsFalse(names.Any(), names.Count() + " members that accept or return List<T> or Dictionary<K, V> detected. " +
                "These should be changed to IList<T> and IDictionary<K, V>, respectively.");
        }

        private static IEnumerable<string> GetInvalidPrivateFields(Assembly assembly, string exceptionRegex)
        {
            var result = new List<string>();

            var classes = assembly.GetTypes().Where(t => t.IsClass);

            foreach (var c in classes)
            {
                var fields = c.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

                foreach (var field in fields)
                {
                    if (field.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore auto-implemented properties
                    {
                        continue;
                    }

                    if (field.DeclaringType.GetEvent(field.Name) != null) // Ignore events
                    {
                        continue;
                    }

                    if ((field.IsPrivate || field.IsAssembly) && !PrivateFieldName.IsMatch(field.Name) && field.DeclaringType.Equals(c.UnderlyingSystemType))
                    {
                        var name = string.Concat(c.FullName, ".", field.Name);
                        if (!IsException(name, exceptionRegex))
                        {
                            result.Add(name);
                        }
                    }
                }
            }

            return result.ToArray();
        }

        private static IEnumerable<string> GetInvalidProtectedFields(Assembly assembly)
        {
            var result = new List<string>();

            var classes = assembly.GetTypes().Where(t => t.IsClass);

            foreach (var c in classes)
            {
                if (!string.IsNullOrEmpty(c.Namespace) && c.Namespace.StartsWith("Lucene.Net.Support", StringComparison.Ordinal))
                {
                    continue;
                }
                if (!string.IsNullOrEmpty(c.Name) && c.Name.Equals("AssemblyKeys", StringComparison.Ordinal))
                {
                    continue;
                }

                var fields = c.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

                foreach (var field in fields)
                {
                    if (field.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore auto-implemented properties
                    {
                        continue;
                    }

                    if (field.DeclaringType.GetEvent(field.Name) != null) // Ignore events
                    {
                        continue;
                    }

                    if ((field.IsFamily || field.IsFamilyOrAssembly) && !ProtectedFieldName.IsMatch(field.Name) && field.DeclaringType.Equals(c.UnderlyingSystemType))
                    {
                        result.Add(string.Concat(c.FullName, ".", field.Name));
                    }
                }
            }

            return result.ToArray();
        }

        /// <summary>
        /// All public fields are invalid
        /// </summary>
        /// <param name="assembly"></param>
        /// <returns></returns>
        private static IEnumerable<string> GetInvalidPublicFields(Assembly assembly, string exceptionRegex)
        {
            var result = new List<string>();

            var classes = assembly.GetTypes().Where(t => t.IsClass);

            foreach (var c in classes)
            {
                if (c.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore classes produced by anonymous methods
                {
                    continue;
                }

                if (!string.IsNullOrEmpty(c.Namespace) && c.Namespace.StartsWith("Lucene.Net.Support", StringComparison.Ordinal))
                {
                    continue;
                }

                var fields = c.GetFields(BindingFlags.Public | BindingFlags.Instance);

                foreach (var field in fields)
                {
                    if (field.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore auto-implemented properties
                    {
                        continue;
                    }

                    if (field.DeclaringType.GetEvent(field.Name) != null) // Ignore events
                    {
                        continue;
                    }

                    if (field.IsPublic && field.DeclaringType.Equals(c.UnderlyingSystemType))
                    {
                        var name = string.Concat(c.FullName, ".", field.Name);
                        if (!IsException(name, exceptionRegex))
                        {
                            result.Add(name);
                        }
                    }
                }
            }

            return result.ToArray();
        }

        private static IEnumerable<string> GetInvalidMethodParameterNames(Assembly assembly)
        {
            var result = new List<string>();

            var classes = assembly.GetTypes().Where(t => t.IsClass);

            foreach (var c in classes)
            {
                var methods = c.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

                foreach (var method in methods)
                {
                    if (method.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore auto-generated methods
                    {
                        continue;
                    }

                    var parameters = method.GetParameters();

                    foreach (var parameter in parameters)
                    {
                        if (!MethodParameterName.IsMatch(parameter.Name) && method.DeclaringType.Equals(c.UnderlyingSystemType))
                        {
                            result.Add(string.Concat(c.FullName, ".", method.Name, " -parameter- ", parameter.Name));
                        }
                    }
                }
            }

            return result.ToArray();
        }

        private static IEnumerable<string> GetInvalidInterfaceNames(Assembly assembly)
        {
            var result = new List<string>();

            var interfaces = assembly.GetTypes().Where(t => t.IsInterface);

            foreach (var i in interfaces)
            {
                if (!InterfaceName.IsMatch(i.Name))
                {
                    result.Add(i.FullName);
                }
            }

            return result.ToArray();
        }

        private static IEnumerable<string> GetInvalidClassNames(Assembly assembly)
        {
            var result = new List<string>();

            var classes = assembly.GetTypes().Where(t => t.IsClass);

            foreach (var c in classes)
            {
                if (c.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore classes produced by anonymous methods
                {
                    continue;
                }

                if (c.IsDefined(typeof(ExceptionToClassNameConventionAttribute)))
                {
                    continue;
                }

                if (!ClassName.IsMatch(c.Name) || InterfaceName.IsMatch(c.Name))
                {
                    result.Add(c.FullName);
                }
            }

            return result.ToArray();
        }

        private static IEnumerable<string> GetPropertiesWithNoGetter(Assembly assembly)
        {
            var result = new List<string>();

            var classes = assembly.GetTypes().Where(t => t.IsClass);

            foreach (var c in classes)
            {
                var properties = c.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

                foreach (var property in properties)
                {
                    if (property.GetSetMethod(true) != null && property.GetGetMethod(true) is null && property.DeclaringType.Equals(c.UnderlyingSystemType))
                    {
                        result.Add(string.Concat(c.FullName, ".", property.Name));
                    }
                }
            }

            return result.ToArray();
        }

        private static IEnumerable<string> GetPropertiesThatReturnArray(Assembly assembly)
        {
            var result = new List<string>();

            var classes = assembly.GetTypes().Where(t => t.IsClass);

            foreach (var c in classes)
            {
                var properties = c.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

                foreach (var property in properties)
                {
                    // Skip attributes with WritableArrayAttribute defined. These are
                    // properties that were intended to expose arrays, as per MSDN this
                    // is not a .NET best practice. However, Lucene's design requires that
                    // this be done.
                    if (property.IsDefined(typeof(WritableArrayAttribute)))
                    {
                        continue;
                    }

                    var getMethod = property.GetGetMethod();

                    if (getMethod != null && getMethod.ReturnParameter != null && getMethod.ReturnParameter.ParameterType.IsArray && property.DeclaringType.Equals(c.UnderlyingSystemType))
                    {
                        result.Add(string.Concat(c.FullName, ".", property.Name));
                    }
                }
            }

            return result.ToArray();
        }

        private static IEnumerable<string> GetProtectedFieldsContainingComparer(Assembly assembly)
        {
            var result = new List<string>();

            var classes = assembly.GetTypes().Where(t => t.IsClass);

            foreach (var c in classes)
            {
                var fields = c.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

                foreach (var field in fields)
                {
                    if (field.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore auto-implemented properties
                    {
                        continue;
                    }

                    if (field.DeclaringType.GetEvent(field.Name) != null) // Ignore events
                    {
                        continue;
                    }

                    if ((field.IsFamily || field.IsFamilyOrAssembly) && ContainsComparer.IsMatch(field.Name) && field.DeclaringType.Equals(c.UnderlyingSystemType))
                    {
                        result.Add(string.Concat(c.FullName, ".", field.Name));
                    }
                }
            }

            return result.ToArray();
        }

        private static IEnumerable<string> GetMembersContainingComparer(Assembly assembly)
        {
            var result = new List<string>();

            var types = assembly.GetTypes();

            foreach (var t in types)
            {
                if (ContainsComparer.IsMatch(t.Name) && t.IsVisible)
                {
                    result.Add(t.FullName);
                }

                var members = t.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

                foreach (var member in members)
                {
                    if (ContainsComparer.IsMatch(member.Name) && member.DeclaringType.Equals(t.UnderlyingSystemType))
                    {
                        if (member.MemberType == MemberTypes.Method && !(member.Name.StartsWith("get_", StringComparison.Ordinal) || member.Name.StartsWith("set_", StringComparison.Ordinal)))
                        {
                            result.Add(string.Concat(t.FullName, ".", member.Name, "()"));
                        }
                        else if (member.MemberType == MemberTypes.Property)
                        {
                            result.Add(string.Concat(t.FullName, ".", member.Name));
                        }
                        else if (member.MemberType == MemberTypes.Event)
                        {
                            result.Add(string.Concat(t.FullName, ".", member.Name, " (event)"));
                        }
                    }
                }
            }

            return result.ToArray();
        }

        private static IEnumerable<string> GetMembersNamedSize(Assembly assembly)
        {
            var result = new List<string>();

            var types = assembly.GetTypes();

            foreach (var t in types)
            {
                var members = t.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

                foreach (var member in members)
                {
                    if ("Size".Equals(member.Name, StringComparison.OrdinalIgnoreCase) && member.DeclaringType.Equals(t.UnderlyingSystemType))
                    {
                        if (member.MemberType == MemberTypes.Method && !(member.Name.StartsWith("get_", StringComparison.Ordinal) || member.Name.StartsWith("set_", StringComparison.Ordinal)))
                        {
                            var method = (MethodInfo)member;
                            // Ignore methods with parameters
                            if (!method.GetParameters().Any())
                            {
                                result.Add(string.Concat(t.FullName, ".", member.Name, "()"));
                            }
                        }
                        else if (member.MemberType == MemberTypes.Property)
                        {
                            result.Add(string.Concat(t.FullName, ".", member.Name));
                        }

                    }
                }
            }

            return result.ToArray();
        }

        private static IEnumerable<string> GetMembersContainingNonNetNumeric(Assembly assembly)
        {
            var result = new List<string>();

            var types = assembly.GetTypes();

            foreach (var t in types)
            {
                //if (ContainsComparer.IsMatch(t.Name) && t.IsVisible)
                //{
                //    result.Add(t.FullName);
                //}

                var members = t.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

                foreach (var member in members)
                {
                    // Ignore properties, methods, and events with IgnoreNetNumericConventionAttribute
                    if (member.IsDefined(typeof(ExceptionToNetNumericConventionAttribute)))
                    {
                        continue;
                    }

                    if (ContainsNonNetNumeric.IsMatch(member.Name) && member.DeclaringType.Equals(t.UnderlyingSystemType))
                    {
                        if (member.MemberType == MemberTypes.Method && !(member.Name.StartsWith("get_", StringComparison.Ordinal) || member.Name.StartsWith("set_", StringComparison.Ordinal)))
                        {
                            result.Add(string.Concat(t.FullName, ".", member.Name, "()"));
                        }
                        else if (member.MemberType == MemberTypes.Property)
                        {
                            result.Add(string.Concat(t.FullName, ".", member.Name));
                        }
                        else if (member.MemberType == MemberTypes.Event)
                        {
                            result.Add(string.Concat(t.FullName, ".", member.Name, " (event)"));
                        }
                    }
                }
            }

            return result.ToArray();
        }

        private static IEnumerable<string> GetTypesContainingNonNetNumeric(Assembly assembly)
        {
            var result = new List<string>();

            var types = assembly.GetTypes();

            foreach (var t in types)
            {
                if (t.IsDefined(typeof(ExceptionToNetNumericConventionAttribute)))
                {
                    continue;
                }

                if (ContainsNonNetNumeric.IsMatch(t.Name))
                {
                    result.Add(t.FullName);
                }
            }

            return result.ToArray();
        }

        private static IEnumerable<string> GetMethodsThatReturnWritableArray(Assembly assembly)
        {
            var result = new List<string>();

            var classes = assembly.GetTypes().Where(t => t.IsClass);

            foreach (var c in classes)
            {
                if (c.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore classes produced by anonymous methods
                {
                    continue;
                }

                var methods = c.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

                foreach (var method in methods)
                {
                    // Skip attributes with WritableArrayAttribute defined. These are
                    // properties that were intended to expose arrays, as per MSDN this
                    // is not a .NET best practice. However, Lucene's design requires that
                    // this be done.
                    if (method.IsDefined(typeof(WritableArrayAttribute)))
                    {
                        continue;
                    }

                    // Ignore property method definitions
                    if (method.Name.StartsWith("get_", StringComparison.Ordinal) || method.Name.StartsWith("set_", StringComparison.Ordinal))
                    {
                        continue;
                    }

                    if (method != null && method.ReturnParameter != null
                        && method.ReturnParameter.ParameterType.IsArray
                        && method.DeclaringType.Equals(c.UnderlyingSystemType))
                    {

                        var methodBody = method.GetMethodBody();
                        if (methodBody != null)
                        {
                            var il = Encoding.UTF8.GetString(methodBody.GetILAsByteArray());

                            if (MethodBodyReturnValueOnly.IsMatch(il))
                            {
                                result.Add(string.Concat(c.FullName, ".", method.Name));
                            }
                        }
                    }
                }
            }

            return result.ToArray();
        }

        private static IEnumerable<string> GetPublicNullableEnumMembers(Assembly assembly)
        {
            var result = new List<string>();

            var types = assembly.GetTypes();

            foreach (var t in types)
            {
                var members = t.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

                foreach (var member in members)
                {
                    if (member.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore auto-generated methods
                    {
                        continue;
                    }

                    // Ignore properties, methods, and events with IgnoreNetNumericConventionAttribute
                    if (member.IsDefined(typeof(ExceptionToNullableEnumConventionAttribute)))
                    {
                        continue;
                    }

                    if (member.DeclaringType.Equals(t.UnderlyingSystemType))
                    {
                        if (member.MemberType == MemberTypes.Method && !(member.Name.StartsWith("get_", StringComparison.Ordinal) || member.Name.StartsWith("set_", StringComparison.Ordinal)))
                        {
                            var method = (MethodInfo)member;

                            if (!method.IsPrivate)
                            {
                                if (method.ReturnParameter != null
                                    && Nullable.GetUnderlyingType(method.ReturnParameter.ParameterType) != null
                                    && method.ReturnParameter.ParameterType.GetGenericArguments()[0].IsEnum)
                                {
                                    result.Add(string.Concat(t.FullName, ".", member.Name, "()"));
                                }

                                var parameters = method.GetParameters();

                                foreach (var parameter in parameters)
                                {
                                    if (Nullable.GetUnderlyingType(parameter.ParameterType) != null
                                        && parameter.ParameterType.GetGenericArguments()[0].IsEnum
                                        && member.DeclaringType.Equals(t.UnderlyingSystemType))
                                    {
                                        result.Add(string.Concat(t.FullName, ".", member.Name, "()", " -parameter- ", parameter.Name));
                                    }
                                }
                            }
                        }
                        else if (member.MemberType == MemberTypes.Constructor)
                        {
                            var constructor = (ConstructorInfo)member;

                            if (!constructor.IsPrivate)
                            {
                                var parameters = constructor.GetParameters();

                                foreach (var parameter in parameters)
                                {
                                    if (Nullable.GetUnderlyingType(parameter.ParameterType) != null
                                        && parameter.ParameterType.GetGenericArguments()[0].IsEnum
                                        && member.DeclaringType.Equals(t.UnderlyingSystemType))
                                    {
                                        result.Add(string.Concat(t.FullName, ".", member.Name, "()", " -parameter- ", parameter.Name));
                                    }
                                }
                            }
                        }
                        else if (member.MemberType == MemberTypes.Property
                            && Nullable.GetUnderlyingType(((PropertyInfo)member).PropertyType) != null
                            && ((PropertyInfo)member).PropertyType.GetGenericArguments()[0].IsEnum
                            && IsNonPrivateProperty((PropertyInfo)member))
                        {
                            result.Add(string.Concat(t.FullName, ".", member.Name));
                        }
                        else if (member.MemberType == MemberTypes.Field
                            && Nullable.GetUnderlyingType(((FieldInfo)member).FieldType) != null
                            && ((FieldInfo)member).FieldType.GetGenericArguments()[0].IsEnum
                            && (((FieldInfo)member).IsFamily || ((FieldInfo)member).IsFamilyOrAssembly))
                        {
                            result.Add(string.Concat(t.FullName, ".", member.Name, " (field)"));
                        }
                    }
                }
            }

            return result.ToArray();
        }

        private static bool IsNonPrivateProperty(PropertyInfo property)
        {
            var getMethod = property.GetGetMethod();
            var setMethod = property.GetSetMethod();
            return ((getMethod != null && !getMethod.IsPrivate) ||
                (setMethod != null && !setMethod.IsPrivate));
        }

        private static bool IsException(string name, string exceptionRegex)
        {
            bool hasExceptions = !string.IsNullOrWhiteSpace(exceptionRegex);
            return (hasExceptions && Regex.IsMatch(name, exceptionRegex));
        }

        /// <summary>
        /// Some parameters were incorrectly changed from List to IEnumerable during the port. This is
        /// to track down constructor and method parameters and property and method return types
        /// containing IEnumerable
        /// </summary>
        /// <param name="assembly"></param>
        /// <returns></returns>
        private static IEnumerable<string> GetMembersAcceptingOrReturningType(Type lookFor, Assembly assembly, bool publiclyVisibleOnly, string exceptionRegex)
        {
            var result = new List<string>();

            var types = assembly.GetTypes();

            foreach (var t in types)
            {
                var members = t.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

                foreach (var member in members)
                {
                    if (member.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore auto-generated methods
                    {
                        continue;
                    }

                    if (member.DeclaringType.Equals(t.UnderlyingSystemType))
                    {
                        if (member.MemberType == MemberTypes.Method && !(member.Name.StartsWith("get_", StringComparison.Ordinal) || member.Name.StartsWith("set_", StringComparison.Ordinal)))
                        {
                            var method = (MethodInfo)member;

                            if (!publiclyVisibleOnly || !method.IsPrivate)
                            {

                                if (method.ReturnParameter != null
                                    && method.ReturnParameter.ParameterType.IsGenericType
                                    && method.ReturnParameter.ParameterType.GetGenericTypeDefinition().IsAssignableFrom(lookFor))
                                {
                                    var name = string.Concat(t.FullName, ".", member.Name, "()");

                                    if (!IsException(name, exceptionRegex))
                                    {
                                        result.Add(name);
                                    }
                                }

                                var parameters = method.GetParameters();

                                foreach (var parameter in parameters)
                                {
                                    if (parameter.ParameterType.IsGenericType
                                        && parameter.ParameterType.GetGenericTypeDefinition().IsAssignableFrom(lookFor)
                                        && member.DeclaringType.Equals(t.UnderlyingSystemType))
                                    {
                                        var name = string.Concat(t.FullName, ".", member.Name, "()", " -parameter- ", parameter.Name);

                                        if (!IsException(name, exceptionRegex))
                                        {
                                            result.Add(name);
                                        }
                                    }
                                }
                            }
                        }
                        else if (member.MemberType == MemberTypes.Constructor)
                        {
                            var constructor = (ConstructorInfo)member;

                            if (!publiclyVisibleOnly || !constructor.IsPrivate)
                            {
                                var parameters = constructor.GetParameters();

                                foreach (var parameter in parameters)
                                {
                                    if (parameter.ParameterType.IsGenericType
                                        && parameter.ParameterType.GetGenericTypeDefinition().IsAssignableFrom(lookFor)
                                        && member.DeclaringType.Equals(t.UnderlyingSystemType))
                                    {
                                        var name = string.Concat(t.FullName, ".", member.Name, "()", " -parameter- ", parameter.Name);

                                        if (!IsException(name, exceptionRegex))
                                        {
                                            result.Add(name);
                                        }
                                    }
                                }
                            }
                        }
                        else if (member.MemberType == MemberTypes.Property
                            && ((PropertyInfo)member).PropertyType.IsGenericType
                            && ((PropertyInfo)member).PropertyType.GetGenericTypeDefinition().IsAssignableFrom(lookFor)
                            && (!publiclyVisibleOnly || IsNonPrivateProperty((PropertyInfo)member)))
                        {
                            var name = string.Concat(string.Concat(t.FullName, ".", member.Name));

                            if (!IsException(name, exceptionRegex))
                            {
                                result.Add(name);
                            }
                        }
                        //else if (member.MemberType == MemberTypes.Field
                        //    && ((FieldInfo)member).IndexableFieldType.IsGenericType
                        //    && ((FieldInfo)member).IndexableFieldType.GetGenericTypeDefinition().IsAssignableFrom(lookFor)
                        //    && (!publiclyVisibleOnly || (((FieldInfo)member).IsFamily || ((FieldInfo)member).IsFamilyOrAssembly)))
                        //{
                        //    result.Add(string.Concat(t.FullName, ".", member.Name, " (field)"));
                        //}
                    }
                }
            }

            return result.ToArray();
        }
    }
}


text:
<?php

/**
 * The "impressionMetrics" collection of methods.
 * Typical usage is:
 *  <code>
 *   $adexchangebuyer2Service = new Google_Service_AdExchangeBuyerII(...);
 *   $impressionMetrics = $adexchangebuyer2Service->impressionMetrics;
 *  </code>
 */
class Google_Service_AdExchangeBuyerII_Resource_AccountsFilterSetsImpressionMetrics extends Google_Service_Resource
{
  /**
   * Lists all metrics that are measured in terms of number of impressions.
   * (impressionMetrics.listAccountsFilterSetsImpressionMetrics)
   *
   * @param string $accountId Account ID of the buyer.
   * @param string $filterSetId The ID of the filter set to apply.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string pageToken A token identifying a page of results the server
   * should return. Typically, this is the value of
   * ListImpressionMetricsResponse.nextPageToken returned from the previous call
   * to the accounts.filterSets.impressionMetrics.list method.
   * @opt_param int pageSize Requested page size. The server may return fewer
   * results than requested. If unspecified, the server will pick an appropriate
   * default.
   * @return Google_Service_AdExchangeBuyerII_ListImpressionMetricsResponse
   */
  public function listAccountsFilterSetsImpressionMetrics($accountId, $filterSetId, $optParams = array())
  {
    $params = array('accountId' => $accountId, 'filterSetId' => $filterSetId);
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_AdExchangeBuyerII_ListImpressionMetricsResponse");
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace RedKiteLabs\RedKiteCms\RedKiteCmsBundle\Core\Deploy\TemplateSection;

use RedKiteLabs\RedKiteCms\RedKiteCmsBundle\Core\PageTree\PageTree;
use RedKiteLabs\ThemeEngineBundle\Core\Theme\ThemeInterface;

/**
 * AssetSection is the object deputed to generate the metatag sections of a twig template
 *
 * @author RedKite Labs <webmaster@redkite-labs.com>
 *
 * @api
 */
class MetatagSection extends TemplateSectionTwig
{
    /**
     * Defines the base method to generate a section
     *
     * @param \RedKiteLabs\RedKiteCms\RedKiteCmsBundle\Core\PageTree\PageTree     $pageTree
     * @param \RedKiteLabs\ThemeEngineBundle\Core\Theme\ThemeInterface $theme
     * @param array                                                      $options
     */
    public function generateSection(PageTree $pageTree, ThemeInterface $theme, array $options)
    {
        parent::generateSection($pageTree, $theme, $options);

        $metatagsSection = $this->writeComment("Metatags section");
        $metatagsSection .= $this->writeInlineBlock('title', $this->pageTree->getMetaTitle());
        $metatagsSection .= $this->writeInlineBlock('description', $this->pageTree->getMetaDescription());
        $metatagsSection .= $this->writeInlineBlock('keywords', $this->pageTree->getMetaKeywords());

        return $metatagsSection;
    }
}


text:
node-x11-mouseserver
====================

control a mouse on an X server from a web page


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

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

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

<!-- $Rev$ $Date$ -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.apache.geronimo.plugins</groupId>
        <artifactId>jetty8</artifactId>
        <version>4.0.0-SNAPSHOT</version>
    </parent>

    <groupId>org.apache.geronimo.modules</groupId>
    <artifactId>geronimo-jetty8-builder</artifactId>
    <packaging>bundle</packaging>
    <name>Geronimo Plugins, Jetty 8 :: Builder</name>

    <dependencies>
        <dependency>
            <groupId>org.apache.geronimo.modules</groupId>
            <artifactId>geronimo-web-2.5-builder</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.geronimo.modules</groupId>
            <artifactId>geronimo-jetty8</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.openejb</groupId>
            <artifactId>openejb-jee</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.geronimo.framework</groupId>
            <artifactId>geronimo-kernel</artifactId>
            <version>${project.version}</version>
            <classifier>tests</classifier>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.geronimo.components</groupId>
            <artifactId>geronimo-jaspi</artifactId>
            <classifier>tests</classifier>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>xmlbeans-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <configuration>
                    <instructions>
                        <!--packages containing "impl" or "internal" are excluded by default -->
                        <Export-Package>
                            org.apache.geronimo.jetty8.deployment,
                            org.apache.geronimo.xbeans.geronimo.web.jetty,
                            org.apache.geronimo.xbeans.geronimo.web.jetty.impl,
                            org.apache.geronimo.xbeans.geronimo.web.jetty.config,
                            org.apache.geronimo.xbeans.geronimo.web.jetty.config.impl
                        </Export-Package>
                        <_exportcontents>schemaorg_apache_xmlbeans*</_exportcontents>
                        <DynamicImport-Package>schemaorg_apache_xmlbeans.*</DynamicImport-Package>
                        <Import-Package>
                            org.apache.geronimo.deployment.xbeans.impl,
                            org.apache.geronimo.deployment.javabean.xbeans.impl,
                            org.apache.geronimo.deployment.xbeans,
                            org.apache.geronimo.deployment.javabean.xbeans,
                            org.apache.geronimo.deployment.dconfigbean,
                            org.apache.geronimo.deployment.service,
                            org.apache.geronimo.deployment.service.jsr88,
                            org.apache.xmlbeans.impl.schema;version="2.4",
                            org.apache.geronimo.xbeans.geronimo.j2ee,
                            org.apache.geronimo.xbeans.geronimo.j2ee.impl,
                            org.apache.geronimo.j2ee.deployment,
                            org.apache.geronimo.j2ee.deployment.annotation,
                            org.apache.geronimo.j2ee.jsr88,
                            org.apache.geronimo.xbeans.geronimo.naming,
                            org.apache.geronimo.xbeans.geronimo.naming.impl,
                            org.apache.geronimo.naming.deployment,
                            org.apache.geronimo.naming.deployment.jsr88,
                            org.apache.geronimo.xbeans.geronimo.jaspi,
                            org.apache.geronimo.xbeans.geronimo.jaspi.impl,
                            *
                        </Import-Package>
                        <!--<_versionpolicy>[$(version;==;$(@)),$(version;+;$(@)))</_versionpolicy>-->
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
module ConfigOpenApi
  def list(options={})
    response = call(config_open_path("list"), add_config_credentials(options))
    if location == "Beta"
      response[:body]["PadConfigResponse"]["data"]["data"]
    else
      response
    end
  end

  def view(options={})
    call(config_open_path("view"),add_config_credentials(options))
  end

  def add(options={})
    call(config_open_path("add"),add_config_credentials(options))
  end

  def edit(options={})
    call(config_open_path("edit"),add_config_credentials(options))
  end

  def config_open_path(command)
    if location == "Beta"
      "/api/rest/pan/site/#{command}"
    else
      "/config/rest/pan/site/#{command}"
    end
  end

  def add_config_credentials(options)
    if location == "Beta"
      session_token = get_session_token
      keys = get_api_key_list(session_token)
      api_key = keys.find{|k| k["type"] == 0}["apiKey"]

      options[:sessionToken] = session_token
      options[:apiKey] = api_key
    else
      options[:user]     = @user
      options[:pass] = @password
    end

    options
  end
end


text:
using System;

namespace CC.MT.Public.Election.Areas.HelpPage.ModelDescriptions
{
  /// <summary>
  /// Parameter Annotation
  /// </summary>
  public class ParameterAnnotation
  {
    /// <summary>
    /// Annotation Attribute
    /// </summary>
    public Attribute AnnotationAttribute { get; set; }

    /// <summary>
    /// Documentation
    /// </summary>
    public string Documentation { get; set; }
  }
}


text:
Neo-Fuzzy-Neuron
================

A simple library that describes neo-fuzzy-neuron as part of the hybrid neural network based system modeling approaches.

While **API** documentation is in progress you can explore it via Maven Central. Please, use this dependency:

```xml
<dependency>
    <groupId>com.fixedorgo</groupId>
    <artifactId>neo-fuzzy-neuron</artifactId>
    <version>0.1.2</version>
</dependency>
```

If you have any questions, suggestions or comments, please, let me know.

---

**TODO:** API of `Extended Neo-Fuzzy-Neuron` and `Neuro-Fuzzy Kolmogorov's Network`.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>SKTrackablePOI (SKMaps Framework)</title>
<meta name="date" content="2016-10-27">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.skobbler.ngx.poitracker

Class SKTrackablePOI

java.lang.Object

com.skobbler.ngx.poitracker.SKTrackablePOI

public class SKTrackablePOI
extends java.lang.Object

SKTrackablePOI provides the model object of a trackable POI, used by the
 SKPOITracker.

Version:

3.0.2

Constructor Summary

Constructors

Constructor and Description

SKTrackablePOI()

Constructor

SKTrackablePOI(int id,
              int type,
              double latitude,
              double longitude,
              double heading,
              java.lang.String street)

Constructor

SKTrackablePOI(int id,
              int type,
              SKCoordinate coordinate,
              double heading,
              java.lang.String street)

Method Summary

Methods

Modifier and Type
Method and Description

SKCoordinate
getCoordinate()

double
getHeading()

int
getId()

java.lang.String
getStreet()

int
getType()

return the type of the SKTrackablePOI

void
setCoordinate(SKCoordinate coordinate)

Sets the coordinates of the SKTrackablePOI, used for detecting it.

void
setHeading(double heading)

Sets the heading of the SKTrackablePOI.

void
setId(int id)

Sets the unique ID of the SKTrackablePOI.

void
setStreet(java.lang.String street)

Sets the street name where the POI is located

void
setType(int type)

Sets the type of the SKTrackablePOI.

java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

SKTrackablePOI

public SKTrackablePOI()

Constructor

SKTrackablePOI

public SKTrackablePOI(int id,
              int type,
              double latitude,
              double longitude,
              double heading,
              java.lang.String street)

Constructor

Parameters:

id -

type -

latitude -

longitude -

heading -

SKTrackablePOI

public SKTrackablePOI(int id,
              int type,
              SKCoordinate coordinate,
              double heading,
              java.lang.String street)

Method Detail

getId

public int getId()

Returns:

the unique ID of the SKTrackablePOI.

setId

public void setId(int id)

Sets the unique ID of the SKTrackablePOI.

Parameters:

id -

getType

public int getType()

return the type of the SKTrackablePOI

setType

public void setType(int type)

Sets the type of the SKTrackablePOI.

Parameters:

type -

getCoordinate

public SKCoordinate getCoordinate()

Returns:

the coordinates of the SKTrackablePOI, used for detecting it.

setCoordinate

public void setCoordinate(SKCoordinate coordinate)

Sets the coordinates of the SKTrackablePOI, used for detecting it.

getHeading

public double getHeading()

Returns:

the heading of the SKTrackablePOI

setHeading

public void setHeading(double heading)

Sets the heading of the SKTrackablePOI.

Parameters:

heading -

getStreet

public java.lang.String getStreet()

Returns:

the street name where the POI is located

setStreet

public void setStreet(java.lang.String street)

Sets the street name where the POI is located

Parameters:

street -

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

			Copyright &#169 2014  skobbler GmbH, Luisenstr. 41, 10117 Berlin, Germany. All rights reserved.


text:
define(['backbone'], function(Backbone) {
	'use strict';

	return Backbone.Model.extend({
		defaults: {
			title: '', // Title of the Step
			completed: false, // Whether step has been completed yet
			shortDescription: '', // 2 sentence max description of step (Plain text)
			longDescription: '', // Long description of step (HTML)
			otherResources: '', // Links outward to other resources related to this step (HTML)
			model: '' // name of model -- MUST HAVE SCHEMA object defined re: backbone-forms
		},

		initialize : function() {
			//	if (this.isNew()) this.set('created', Date.now());
		}

		//	toggle  : function() {
		//		return this.set('completed', !this.get('completed'));
		//	}
	});
});


text:
#include <uve/test/prouter_uve_table_test.h>

ProuterUveTableTest::ProuterUveTableTest(Agent *agent, uint32_t default_intvl) :
    ProuterUveTable(agent, default_intvl) {
}

ProuterUveTableTest::~ProuterUveTableTest() {
}

void ProuterUveTableTest::DispatchProuterMsg(const ProuterData &uve) {
    send_count_++;
    if (uve.get_deleted()) {
        delete_count_++;
    }
    uve_ = uve;
}

void ProuterUveTableTest::ClearCount() {
    send_count_ = 0;
    delete_count_ = 0;
    pi_send_count_ = 0;
    pi_delete_count_ = 0;
    li_send_count_ = 0;
    li_delete_count_ = 0;
}

void ProuterUveTableTest::DispatchPhysicalInterfaceMsg
    (const UvePhysicalInterfaceAgent &uve) {
    pi_send_count_++;
    if (uve.get_deleted()) {
        pi_delete_count_++;
    }
}

void ProuterUveTableTest::DispatchLogicalInterfaceMsg
    (const UveLogicalInterfaceAgent &uve) {
    li_send_count_++;
    if (uve.get_deleted()) {
        li_delete_count_++;
    }
    li_uve_ = uve;
}

uint32_t ProuterUveTableTest::PhysicalIntfListCount() const {
    return uve_phy_interface_map_.size();
}

uint32_t ProuterUveTableTest::LogicalIntfListCount() const {
    return uve_logical_interface_map_.size();
}

uint32_t ProuterUveTableTest::VMIListCount(const LogicalInterface *itf) const {
    LogicalInterfaceMap::const_iterator it = uve_logical_interface_map_.find
        (itf->GetUuid());
    if (it != uve_logical_interface_map_.end()) {
        LogicalInterfaceUveEntry *entry = it->second.get();
        return entry->vmi_list_.size();
    }
    return 0;
}


text:
<ivy-module version="1.0">
    <info organisation="net.sf.snpeff" module="snpeff" revision="2.0.5" status="release" />
</ivy-module>


text:
package net.anotheria.moskito.core.util;

import net.anotheria.moskito.core.predefined.ThreadStateStats;
import net.anotheria.moskito.core.producers.IStatsProducer;
import net.anotheria.moskito.core.registry.IProducerRegistry;
import net.anotheria.moskito.core.registry.ProducerRegistryFactory;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * This builtin producer monitors the thread states and how many threads are in each state i.e. BLOCKED, RUNNABLE etc.
 *
 * @author lrosenberg
 * @since 25.11.12 23:55
 */
	public class BuiltInThreadStatesProducer extends AbstractBuiltInProducer implements IStatsProducer<ThreadStateStats>, BuiltInProducer{
	/**
	 * Cumulated stats object.
	 */
	private ThreadStateStats cumulated;
	/**
	 * Stats objects as list.
	 */
	private List<ThreadStateStats> statsList;
	/**
	 * ThreadStateStats map.
	 */
	private Map<Thread.State, ThreadStateStats> statsMap;
	/**
	 * Reference to the jmx bean.
	 */
	private ThreadMXBean threadMxBean;
	/**
	 * Package protected constructor.
	 */
	BuiltInThreadStatesProducer(){

		cumulated = new ThreadStateStats("cumulated");

		statsMap = new HashMap<Thread.State, ThreadStateStats>();
		statsList = new CopyOnWriteArrayList<ThreadStateStats>();
		statsList.add(cumulated);
		for (Thread.State state : Thread.State.values()){
			ThreadStateStats statsObject = new ThreadStateStats(state.name());
			statsMap.put(state, statsObject);
			statsList.add(statsObject);
		}

		threadMxBean = ManagementFactory.getThreadMXBean();

		IProducerRegistry reg = ProducerRegistryFactory.getProducerRegistryInstance();
		reg.registerProducer(this);

		BuiltinUpdater.addTask(new TimerTask() {
			@Override
			public void run() {
				readThreads();
			}
		});
	}

	/**
	 * Reads and updates the thread info.
	 */
	private void readThreads(){
		long[] ids = threadMxBean.getAllThreadIds();

		HashMap<Thread.State, Long> count = new HashMap<Thread.State, Long>();
		for (int i = 0; i<ids.length; i++){
			long id = ids[i];
			ThreadInfo info = threadMxBean.getThreadInfo(id);
			if (info!=null){
				Thread.State state = info.getThreadState();

				Long old = count.get(state);
				if (old==null) {
					old = 0L;
				}
				count.put(state, old+1);
			}
		}

		long total = 0;
		for (Map.Entry<Thread.State, ThreadStateStats> entry : statsMap.entrySet()){
			Long c = count.get(entry.getKey());
			entry.getValue().updateCurrentValue(c==null ? 0 : c.longValue());
			if (c!=null)
				total += c.longValue();
		}
		cumulated.updateCurrentValue(total);

	}

	@Override
	public String getCategory() {
		return "threads";
	}

	@Override
	public String getProducerId() {
		return "ThreadStates";
	}

	@Override
	public List<ThreadStateStats> getStats() {
		return statsList;
	}

	@Override
	public String getSubsystem() {
		return SUBSYSTEM_BUILTIN;
	}
}


text:
#pragma once
#include <gtsam/geometry/Point3.h>
#include <gtsam/geometry/Pose3.h>
#include <gtsam/geometry/Pose2.h>
//#include <gtsam/linear/SharedDiagonal.h>
#include <gtsam/linear/NoiseModel.h>
#include <tf/tf.h>
#include <tf/transform_listener.h>

/*!
 *\brief Sees if the displacement between these two poses exceeds distance
 *
 * \param last_pose   The previous pose where a message from this sensor message was used to augment the map
 * \param curr_pose   The current pose of the robot
 * \param distance    The required displacement for the new message to be considered independent enough to incorporate into the map
 * \return true if this displacement is sufficient, meaning that this message should be used.  If this is false, then it shouldnt be used.  This method ignores rotation
 *
 */

bool CheckMoveFarEnough(const tf::StampedTransform& last_pose,
			const tf::StampedTransform& curr_pose,
			double distance,
			double rot_thresh);

/*!
 * \brief Makes a gtsam::Pose2 out of a TF stamped transform
 *
 *\param transform   The TF::StampedTransform where the robot is to get the pose from
 *
 * \return the gtsam::Pose2
 */

gtsam::Pose3 GetPose(const tf::StampedTransform& transform);

/*!
 * \brief Gets the relative pose between two transformations, used to compute the odometric pose between two map robot poses
 *
 *\param last_pose   The last (odometric)pose of the robot, where the prior message was used
 *\param curr_pose   The current (odometric)pose of the robot
 * \return the pose transforming last_pose into curr_pose, which is the measurement for the Pose2Factor
 */

gtsam::Pose3 GetRelativePose(const tf::StampedTransform& last_pose,
			     const tf::StampedTransform& curr_pose);

/*!
 *\brief   Takes an angle and wraps it to the range -M_PI:M_PI
 *
 *\param   in  an angle
 *\return  the angle in the range -M_PI:M_PI
 */
double WrapToPi(double in);

/*!
 * \brief Converts a Vector3 from TF to a Point3 for gtsam
 * \param vec   A Vector 3 from TF
 * \return a Point3 for GTSAM
 */
gtsam::Point3 btVectorToPoint3(const tf::Vector3& vec);

/*!
 *\brief Makes a GTSAM Pose3 out of a TF transform
 *
 *\param transform    A TF transform
 *\return the Pose3 equivalent for GTSAM
 */
gtsam::Pose3 btTransformToPose3(const tf::Transform& transform);

tf::Transform Pose3ToTransform(const gtsam::Pose3& ps);

gtsam::Pose3 TransformToPose3(const tf::Transform& t);

gtsam::Pose2 Pose3ToPose2(const gtsam::Pose3& p3);
gtsam::Pose3 Pose2ToPose3(const gtsam::Pose2& p2);

gtsam::noiseModel::Diagonal::shared_ptr
GetOdoCovariance( const gtsam::Pose3& odo,
		  double sroll, double spitch, double syaw,
		  double sx, double sy, double sz);
gtsam::Matrix CovarFromDiagonalNoiseModel(const gtsam::SharedDiagonal& diagonal);


text:
package org.xins.client.async;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.xins.client.AbstractCAPI;
import org.xins.client.AbstractCAPICallRequest;

/**
 * Class used to register the {@link CallListener}s and to call the API
 * asynchronously.
 *
 * @version $Revision$ $Date$
 * @author Anthony Goubard
 *
 * @since XINS 1.4.0
 */
public class AsynchronousCall {

   /**
    * List containing the registered {@link CallListener}.
    */
   private List _listeners = new ArrayList();

   /**
    * Adds a new listener for the call.
    *
    * @param listener
    *    the listener that will be notified of the result of the call.
    */
   public void addCallListener(CallListener listener) {
      _listeners.add(listener);
   }

   /**
    * Removes a listener for the call. If the listener was not previously added
    * nothing happens.
    *
    * @param listener
    *    the listener that will be notified of the result of the call.
    */
   public void removeCallListener(CallListener listener) {
      _listeners.remove(listener);
   }

   /**
    * Calls a function asynchronously. This function does not return anything as
    * the result and exception will be received by the registered {@link CallListener}.
    *
    * @param capi
    *    the CAPI to use to call the function.
    *
    * @param request
    *    the input parameters for this call.
    */
   public void call(AbstractCAPI capi, AbstractCAPICallRequest request) {
      CallNotifyThread thread = new CallNotifyThread(capi, request, _listeners);
      thread.start();
   }

   /**
    * Thread that executes the call to the function.
    *
    * @version $Revision$ $Date$
    * @author Anthony Goubard
    */
   private static class CallNotifyThread extends CallCAPIThread {

      /**
       * The listeners to notify.
       */
      private final List _listeners;

      /**
       * Calls a CAPI function on a separate thread and notifies the listeners
       * of the result.
       *
       * @param capi
       *    the CAPI to use to call the function.
       *
       * @param request
       *    the input parameters for this call.
       *
       * @param listeners
       *    the listeners to notify of the result of the call.
       */
      CallNotifyThread(AbstractCAPI capi, AbstractCAPICallRequest request, List listeners) {
         super(capi, request);

         // Notify the listeners registered at the moment of the call and not
         // when the result is received.
         _listeners = Collections.unmodifiableList(listeners);
      }

      public void run() {

         // Call the API
         super.run();

         // Get the result and notify the listeners
         if (getException() == null) {
            CallSucceededEvent event = new CallSucceededEvent(getCAPI(),
                  getRequest(), getDuration(), getResult());
            Iterator itListeners = _listeners.iterator();
            while (itListeners.hasNext()) {
               CallListener listener = (CallListener) itListeners.next();
               listener.callSucceeded(event);
            }
         } else {
            CallFailedEvent event = new CallFailedEvent(getCAPI(),
                  getRequest(), getDuration(), getException());
            Iterator itListeners = _listeners.iterator();
            while (itListeners.hasNext()) {
               CallListener listener = (CallListener) itListeners.next();
               listener.callFailed(event);
            }
         }
      }
   }
}


text: google-site-verification: googlee6ac195426fef3bb.html


text:
:orphan:

.. include:: links.inc
.. _scikit-beam-fix-example:

====================================================
 Contributing code to Scikit-beam, a worked example
====================================================

.. warning::

   This still needs to be adapted for skbeam

This example is based on fixing `Issue 1761`_ from the list
of `Scikit-beam issues on GitHub <https://github.com/scikit-beam/scikit-beam/issues>`_.
It resulted in `pull request 1917`_.

The issue title was "len() does not work for coordinates" with description
"It would be nice to be able to use ``len`` on coordinate arrays to know how
many coordinates are present."

This particular example was chosen because it was tagged as easy in GitHub;
seemed like the best place to start out!

Short on time? Don't want to read a long tutorial?
==================================================

There is a minimalist, command-only version of this at :ref:`command_history`.
You should  have `pull request 1917`_ open as you read the commands so you can
see the edits made to the code.

There is also a very exciting terminal-cast at :ref:`terminal_cast`.

Before you begin
================

Make sure you have a local copy of scikit-beam set up as described in
:ref:`get_devel`. In a nutshell, the output of ``git remote -v``, run in the
directory where your local of Scikit-beam resides, should be something like this::

    scikit-beam   git://github.com/scikit-beam/scikit-beam.git (fetch)
    scikit-beam   git://github.com/scikit-beam/scikit-beam.git (push)
    your-user-name     git@github.com:your-user-name/scikit-beam.git (fetch)
    your-user-name     git@github.com:your-user-name/scikit-beam.git (push)

The precise form of the URLs for ``your-user-name`` depends on the
authentication method you set up with GitHub.

The important point is that ``scikit-beam`` should point to the official Scikit-beam
repo and ``your-user-name`` should point to *your* copy of Scikit-beam on GitHub.

Grab the latest updates to scikit-beam
======================================

A few steps in this tutorial take only a single command. They are broken out
separately to outline the process in words as well as code.

Inform your local copy of Scikit-beam about the latest changes in the development
version with::

    git fetch scikit-beam

Set up an isolated workspace
============================
+ Make a new `git`_ branch for fixing this issue, check it out, and let my
  GitHub account know about this branch::

    git branch fix-1761 scikit-beam/master   # branch based on latest from GitHub
    git checkout fix-1761                   # switch to this branch
    git push --set-upstream origin fix-1761 # tell my github acct about it

+ Make a python environment just for this fix and switch to that environment.
  The example below shows the necessary steps in the Anaconda python
  distribution::

        conda create -n apy-1761 --clone root  # Anaconda distribution only
        source activate apy-1761

  If you are using a different distribution, see :ref:`virtual_envs` for
  instructions for creating and activating a new environment.
+ Install our branch in this environment (will not work in python 3) with::

    python setup.py develop

Do you really have to set up a separate python environment for each fix? No,
but you definitely want to have a python environment for your work on code
contributions. Making new environments is fast, doesn't take much space and
provide a way to keep your work organized.

Tests first, please
===================

It would be hard to overstate the importance of testing to Scikit-beam. Tests are
what gives you confidence that new code does what it should and that it
doesn't break old code.

You should at least run the relevant tests before you make any changes to make
sure that your python environment is set up properly.

The first challenge is figuring out where to look for relevant tests. `Issue
1761`_ is a problem in the :obj:`~scikit-beam.coordinates` package, so the tests for
it are in ``scikit-beam/coordinates/tests``. The rest of Scikit-beam has a similar
layout, described at :ref:`testing-guidelines`.

Change to that directory and run the current tests with::

    cd scikit-beam/coordinates/test
    py.test

The tests all pass, so I need to write a new test to expose this bug.

There are several files with tests in them, though::

    $ ls
    test_angles.py
    test_angular_separation.py
    test_api.py
    test_arrays.py
    test_distance.py
    test_formatting.py
    test_matching.py
    test_name_resolve.py
    test_transformations.py

`Issue 1761`_ affects arrays of coordinates, so it seems sensible to put the
new test in ``test_arrays.py``. As with all of the steps, if you are not
sure, ask on the scikit-beam-dev mailing list.

The goal at this point may be a little counter-intuitive: write a test that we
know will fail with the current code. This test allows Scikit-beam to check,
in an automated way, whether our fix actually works and to make sure future
changes to code do not break our fix.

Looking over the existing code in ``test_arrays.py``, each test is a function
whose name starts with ``test_``; the last test in the file is
``test_array_indexing`` so an appropriate place to add the test is right after
that.

Give the test a reasonably clear name; I chose: ``test_array_len``. The
easiest way to figure out what you need to import and how to set up the test
is to look at other tests. The full test is in the traceback below and in
`pull request 1917`_

Write the test, then see if it works as expected--remember, in this case we
expect to *fail*. Running ``py.test test_arrays.py`` gives the expected
result; an excerpt from the output is::

    ================= FAILURES =============================
    ______________ test_array_len __________________________

        def test_array_len():
            from .. import ICRS

            input_length = 5
            ra = np.linspace(0, 360, input_length)
            dec = np.linspace(0, 90, input_length)

            c = ICRS(ra, dec, unit=(u.degree, u.degree))

    >       assert len(c) == input_length
    E       TypeError: object of type 'ICRS' has no len()

    test_arrays.py:291: TypeError

Success!

Add this test to your local `git`_ repo
=======================================

Keep `git`_ commits small and focused on one logical piece at a time. The test
we just wrote is one logical change, so we will commit it. You could, if you
prefer, wait and commit this test along with your fix.

For this tutorial I'll commit the test separately. If you aren't sure what to
do, ask on scikit-beam-dev mailing list.

Check what was changed
----------------------

We can see what has changed with ``git status``::

    $ git status
    On branch fix-1761
    Your branch is up-to-date with 'origin/fix-1761'.

    Changes not staged for commit:
      (use "git add <file>..." to update what will be committed)
      (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   test_arrays.py

    no changes added to commit (use "git add" and/or "git commit -a")

There are two bits of information here:

+ one file changed, ``test_arrays.py``
+ We have not added our changes to git yet, so it is listed under ``Changes
  not staged for commit``.

For more extensive changes it can be useful to use ``git diff`` to see what
changes have been made::

    $ git diff
    diff --git a/scikit-beam/coordinates/tests/test_arrays.py b/scikit-beam/coordinates/test
    index 2785b59..7eecfbb 100644
    --- a/scikit-beam/coordinates/tests/test_arrays.py
    +++ b/scikit-beam/coordinates/tests/test_arrays.py
    @@ -278,3 +278,14 @@ def test_array_indexing():
         assert c2.equinox == c1.equinox
         assert c3.equinox == c1.equinox
         assert c4.equinox == c1.equinox
    +
    +def test_array_len():
    +    from .. import ICRS
    +
    +    input_length = 5
    +    ra = np.linspace(0, 360, input_length)
    +    dec = np.linspace(0, 90, input_length)
    +
    +    c = ICRS(ra, dec, unit=(u.degree, u.degree))
    +
    +    assert len(c) == input_length

A graphical interface to git makes keeping track of these sorts of changes
even easier; see :ref:`git_gui_options` if you are interested.

Stage the change
----------------

`git`_ requires you to add changes in two steps:

+ stage the change with ``git add test_arrays.py``; this adds the file to
  the list of items that will be added to the repo when you are ready to
  commit.
+ commit the change with ``git commit``; this actually adds the changes to
  your repo.

These can be combined into one step; the advantage of doing it in two steps
is that it is easier to undo staging than committing. As we will see later,
``git status`` even tells you how to do it.

Staging can be very handy if you are making changes in a couple of different
places that you want to commit at the same time. Make your first changes,
stage it, then make your second change and stage that. Once everything is
staged, commit the changes as one commit.

In this case, first stage the change::

    git add test_arrays.py

You get no notice at the command line that anything has changed, but
``git status`` will let you know::

    $ git status
    On branch fix-1761
    Your branch is up-to-date with 'origin/fix-1761'.

    Changes to be committed:
      (use "git reset HEAD <file>..." to unstage)

        modified:   test_arrays.py

Note that `git`_ helpfully includes the command necessary to unstage the
change if you want to.

Commit your change
------------------

I prefer to make commits frequently, so I'll commit the test without the fix::

    $ git commit -m'Add test for array coordinate length (issue #1761)'
    [fix-1761 dd4ef8c] Add test for array coordinate length (issue #1761)
     1 file changed, 11 insertions(+)

Commit messages should be short and descriptive. Including the GitHub issue
number allows GitHub to automatically create links to the relevant issue.

Use ``git status`` to get a recap of where we are so far::

    $ git status
    On branch fix-1761
    Your branch is ahead of 'origin/fix-1761' by 1 commit.
      (use "git push" to publish your local commits)

    nothing to commit, working directory clean

In other words, we have made a change to our local copy of scikit-beam but we
have not pushed (transferred) that change to our GitHub account.

Fix the issue
=============

Write the code
--------------

Now that we have a test written, we'll fix the issue. A full discussion of
the fix is beyond the scope of this tutorial, but the fix is to add a
``__len__`` method to ``scikit-beam.coordinates.SphericalCoordinatesBase`` in
``coordsystems.py``. All of the spherical coordinate systems inherit from
this base class and it is this base class that implements the
``__getitem__`` method that allows indexing of coordinate arrays.

See `pull request 1917`_ to view the changes to the code.

.. _test_changes:

Test your change
----------------

There are a few levels at which you want to test:

+ Does this code change make the test we wrote succeed now? Check
  by running ``py.test tests/test_arrays.py`` in the ``coordinates``
  directory. In this case, yes!
+ Do the rest of the coordinate tests still pass? Check by running ``py.test``
  in the ``coordinates`` directory. In this case, yes--we have not broken
  anything!
+ Do all of the scikit-beam tests still succeed? Check by moving to the top level
  directory (the one that contains ``setup.py``) and run ``python setup.py
  test``. This may take several minutes depending on the speed of your system.
  Success again!

.. note::
    Tests that are skipped or xfailed are fine. A fail or an error is not
    fine. If you get stuck, ask on scikit-beam-dev mailing list for help!

Stage and commit your change
----------------------------

Add the file to your git repo in two steps: stage, then commit.

To make this a little different than the commit we did above, make sure you
are still in the top level directory and check the ``git status``::

    $ git status
    On branch fix-1761
    Your branch is ahead of 'origin/fix-1761' by 1 commit.
      (use "git push" to publish your local commits)

    Changes not staged for commit:
      (use "git add <file>..." to update what will be committed)
      (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   scikit-beam/coordinates/coordsystems.py

    no changes added to commit (use "git add" and/or "git commit -a")

Note that git knows what has changed no matter what directory you are in (as
long as you are in one of the directories in the repo, that is).

Stage the change with::

    git add scikit-beam/coordinates/coordsystems.py

For this commit it is helpful to use a multi-line commit message that will
automatically close the issue on GitHub when this change is accepted. The
snippet below accomplishes that in bash (and similar shells)::

    $ git commit -m"
    > Add len() to coordinates
    >
    > Closes #1761"
    [fix-1761 f196771] Add len() to coordinates
     1 file changed, 4 insertions(+)

If this was not a tutorial I would write the commit message in a git gui or
run ``git commit`` without a message and git would put me in an editor.

However you do it, the message after committing should look like this::

    Add len() to coordinates

    Closes #1761

You can check the commit messages by running ``git log``. If the commit
message doesn't look right, ask about fixing it at scikit-beam-dev mailing list.

Push your changes to your GitHub fork of scikit-beam
====================================================

This one is easy: ``git push``

This copies the changes made on your computer to your copy of Scikit-beam on
GitHub. At this point none of the Scikit-beam maintainers know anything about
your change.

We'll take care of that in a moment with a "pull request", but first...

Stop and think: any more tests or other changes?
================================================

It never hurts to pause at this point and review whether your proposed
changes are complete. In this case I realized there were some tests I could
have included but didn't:

+ What happens when ``len()`` is called on a coordinate that is *not* an
  array?
+ Does ``len()`` work when the coordinate is an array with one entry?

Both of these are mentioned in the pull request so it doesn't hurt to check
them. In this case they also provide an opportunity to illustrate a feature
of the `py.test`_ framework.

I'll move back to the directory containing the tests with
``cd scikit-beam/coordinates/tests`` to make it a bit easier to run just the test
I want.

The second case is easier, so I'll handle that one first following the cycle
we used above:

+ Make the change in ``test_arrays.py``
+ Test the change

The test passed; rather than committing this one change I'll also implement
the check for the scalar case.

One could imagine two different desirable outcomes here:

+ ``len(scalar_coordinate)`` behaves just like ``len(scalar_angle)``, raising
  a `TypeError` for a scalar coordinate.
+ ``len(scalar_coordinate)`` returns 1 since there is one coordinate.

If you encounter a case like this and are not sure what to do, ask. The best
place to ask is in GitHub on the page for the issue you are fixing.

Alternatively, make a choice and be clear in your pull request on GitHub what
you chose and why; instructions for that are below.

Testing for an expected error
-----------------------------

In this case I opted for raising a `TypeError`, because
the user needs to know that the coordinate they created is not going to
behave like an array of one coordinate if they try to index it later on. It
also provides an opportunity to demonstrate a test when the desired result
is an error.

The `py.test`_ framework makes testing for an exception relatively
easy; you put the code you expect to fail in a ``with`` block::

    with pytest.raises(TypeError):
        c = ICRS(0, 0, unit=(u.degree, u.degree))
        len(c)

I added this to ``test_array_len`` in ``test_arrays.py`` and re-ran the test
to make sure it works as desired.

Aside: Python lesson--let others do your work
---------------------------------------------

The actual fix to this issue was very, very short. In ``coordsystems.py`` two
lines were added::

    def __len__(self):
        return len(self.lonangle)

``lonangle`` contains the ``Angle``s that represent longitude (sometimes this
is an RA, sometimes a longitude). By simply calling ``len()`` on one of the
angles in the array you get, for free, whatever behavior has been defined in
the ``Angle`` class for handling the case of a scalar.

Adding an explicit check for the case of a scalar here would have the very
big downside of having two things that need to be kept in sync: handling of
scalars in ``Angle`` and in coordinates.

Commit any additional changes
=============================

Follow the cycle you saw above:

+ Check that **all** Scikit-beam tests still pass; see :ref:`test_changes`
+ ``git status`` to see what needs to be staged and committed
+ ``git add`` to stage the changes
+ ``git commit`` to commit the changes

The `git`_ commands, without their output, are::

    git status
    git add scikit-beam/coordinates/tests/test_arrays.py
    git commit -m"Add tests of len() for scalar coordinate and length 1 coordinate"

Edit the changelog
==================

Keeping the list of changes up to date is nearly impossible unless each
contributor makes the appropriate updates as they propose changes.

Changes are in the file ``CHANGES.rst`` in the top-level directory (the
directory where ``setup.py`` is). Put the change under the list that matches
the milestone (aka release) that is set for the issue in GitHub. If you are
proposing a new feature in a pull request you may need to wait on this change
until the pull request is discussed.

This issue was tagged for 0.3.1, as shown in the image below, so the changelog
entry went there.

    .. image:: milestone.png

The entry in ``CHANGES.rst`` should summarize was you did and include the
issue number. For writing changelog entries you don't need to know much about
the markup language being used (though you can read as much as you want about
it at the `Sphinx primer`_); look at other entries and imitate.

For this issue the entry was the line that starts ``- Implemented``::

    - ``scikit-beam.coordinates``

      - Implemented `len()` for coordinate objects. [#1761]

Starting the line with a ``-`` makes a bulleted list item, indenting it makes
it a sublist of ``scikit-beam.coordinates`` and putting ``len()`` in single
backticks makes that text render in a typewriter font.

Commit your changes to the CHANGES.rst
--------------------------------------

You can use ``git status`` as above or jump right to staging and committing::

    git add CHANGES.rst
    git commit -m"Add changelog entry for 1761"

Push your changes to GitHub
===========================

One last push to GitHub with these changes before asking for the changes to
be reviewed::

    git push

Ask for your changes to be merged with a pull request
=====================================================

This stage requires to go to your GitHub account and navigate to *your* copy
of scikit-beam; the url will be something like
``https://github.com/your-user-name/scikit-beam``.

Once there, select the branch that contains your fix from the branches
dropdown:

    .. image:: worked_example_switch_branch.png

After selecting the correct branch click on the "Pull Request" button, like
that in the image below:

    .. image:: pull_button.png

Name your pull request something sensible. Include the issue number with a
leading ``#`` in the description of the pull request so that a link is
created to the original issue.

Please see `pull request 1917`_ for the pull request from this example.

Revise and push as necessary
============================

You may be asked to make changes in the discussion of the pull request. Make
those changes in your local copy, commit them to your local repo and push them
to GitHub. GitHub will automatically update your pull request.

.. _Issue 1761: https://github.com/scikit-beam/scikit-beam/issues/1917
.. _pull request 1917: https://github.com/scikit-beam/scikit-beam/issues/1917
.. _Sphinx primer: http://sphinx-doc.org/rest.html
.. _test commit: https://github.com/mwcraig/scikit-beam/commit/cf7d5ac15d7c63ae28dac638c6484339bac5f8de


text:
package co.ledger.wallet.app.base

import android.app.{DialogFragment, Dialog}
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.Window

import co.ledger.wallet.R
import co.ledger.wallet.core.utils.TR

class BaseDialogFragment extends DialogFragment with RichFragment {

  implicit lazy val dialog = this

  override def onCreateDialog(savedInstanceState: Bundle): Dialog = {
    val dialog = super.onCreateDialog(savedInstanceState)
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.getWindow.setBackgroundDrawable(TR(R.drawable.bg_dialog).as[Drawable])
    dialog
  }
}