text:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Text;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.CLR.Utils;

namespace ILRuntime.Runtime.CLRBinding
{
    static class MethodBindingGenerator
    {
        static string GenerateParameterTypes(MethodInfo i, bool needBracket)
        {
            string clsName, realClsName;
            bool isByRef;
            var param = i.GetParameters();
            StringBuilder sb2 = new StringBuilder();
            if (needBracket)
                sb2.Append("{");
            bool first = true;
            foreach (var j in param)
            {
                if (first)
                    first = false;
                else
                    sb2.Append(", ");
                sb2.Append("typeof(");
                j.ParameterType.GetClassName(out clsName, out realClsName, out isByRef);
                sb2.Append(realClsName);
                sb2.Append(")");
                if (isByRef)
                    sb2.Append(".MakeByRefType()");
            }
            if (needBracket)
                sb2.Append("}");
            return sb2.ToString();
        }
        internal static string GenerateMethodRegisterCode(this Type type, MethodInfo[] methods, HashSet<MethodBase> excludes, out bool needMethods)
        {
            needMethods = false;
            MethodInfo[] allMethods = type.GetMethods();

            StringBuilder sb = new StringBuilder();
            int idx = 0;
            bool isMethodsGot = false;
            foreach (var i in methods)
            {
                if (excludes != null && excludes.Contains(i))
                    continue;
                if (type.ShouldSkipMethod(i))
                    continue;

                if (i.IsGenericMethod)
                {
                    if (!isMethodsGot)
                    {
                        sb.AppendLine(@"            Dictionary<string, List<MethodInfo>> genericMethods = new Dictionary<string, List<MethodInfo>>();
            List<MethodInfo> lst = null;
            foreach(var m in type.GetMethods())
            {
                if(m.IsGenericMethodDefinition)
                {
                    if (!genericMethods.TryGetValue(m.Name, out lst))
                    {
                        lst = new List<MethodInfo>();
                        genericMethods[m.Name] = lst;
                    }
                    lst.Add(m);
                }
            }");
                        isMethodsGot = true;
                    }

                    var param = i.GetGenericArguments();
                    StringBuilder sb2 = new StringBuilder();
                    sb2.Append("{");
                    bool first = true;
                    string clsName, realClsName;
                    bool isByRef;
                    foreach (var j in param)
                    {
                        if (first)
                            first = false;
                        else
                            sb2.Append(", ");
                        sb2.Append("typeof(");
                        j.GetClassName(out clsName, out realClsName, out isByRef);
                        sb2.Append(realClsName);
                        sb2.Append(")");
                        if (isByRef)
                            sb2.Append(".MakeByRefType()");
                    }
                    sb2.Append("}");
                    sb.AppendLine(string.Format("            args = new Type[]{0};", sb2));
                    sb.AppendLine(string.Format("            if (genericMethods.TryGetValue(\"{0}\", out lst))", i.Name));
                    sb.Append(@"            {
                foreach(var m in lst)
                {
                    if(m.MatchGenericParameters(args, ");
                    if (i.ReturnType != typeof(void))
                    {
                        sb.Append("typeof(");
                        i.ReturnType.GetClassName(out clsName, out realClsName, out isByRef);
                        sb.Append(realClsName);
                        sb.Append(")");
                    }
                    else
                        sb.Append("typeof(void)");
                    if (i.GetParameters().Length > 0)
                    {
                        sb.Append(", ");
                        sb.Append(GenerateParameterTypes(i, false));
                    }
                    sb.Append(@"))
                    {
                        method = m.MakeGenericMethod(args);
                        app.RegisterCLRMethodRedirection(method, ");
                    sb.AppendLine(string.Format("{0}_{1});", i.Name, idx));
                    sb.AppendLine(@"
                        break;
                    }
                }
            }");
                }
                else
                {
                    string clsName, realClsName;
                    bool isByRef;
                    var param = i.GetParameters();
                    string sb2 = GenerateParameterTypes(i, true);
                    sb.AppendLine(string.Format("            args = new Type[]{0};", sb2));

                    i.ReturnType.GetClassName(out clsName, out realClsName, out isByRef);
                    if ((i.Name.Equals("op_Implicit") || i.Name.Equals("op_Explicit")) && allMethods.Count(m => m.Name.Equals(i.Name)) > 1)
                    {
                        // Type conversions can have different return types
                        needMethods = true;
                        sb.AppendLine(string.Format("            method = methods.Where(t => t.Name.Equals(\"{0}\") && t.ReturnType == typeof({1}) && t.CheckMethodParams(args)).Single();", i.Name, realClsName));
                    }
                    else if (allMethods.Any(m => m.IsGenericMethod && m.Name.Equals(i.Name) && m.CheckMethodParams(param)))
                    {
                        // Check for a generic method with the same name and params
                        needMethods = true;
                        sb.AppendLine(string.Format("            method = methods.Where(t => t.Name.Equals(\"{0}\") && t.CheckMethodParams(args)).Single();", i.Name));
                    } else
                        sb.AppendLine(string.Format("            method = type.GetMethod(\"{0}\", flag, null, args, null);", i.Name));

                    sb.AppendLine(string.Format("            app.RegisterCLRMethodRedirection(method, {0}_{1});", i.Name, idx));
                }

                idx++;
            }
            return sb.ToString();
        }

        internal static string GenerateMethodWraperCode(this Type type, MethodInfo[] methods, string typeClsName, HashSet<MethodBase> excludes, List<Type> valueTypeBinders, Enviorment.AppDomain domain)
        {
            StringBuilder sb = new StringBuilder();
            bool isMultiArr = type.IsArray && type.GetArrayRank() > 1;
            int idx = 0;
            foreach (var i in methods)
            {
                if (excludes != null && excludes.Contains(i))
                    continue;
                if (type.ShouldSkipMethod(i))
                    continue;
                bool isProperty = i.IsSpecialName;
                var param = i.GetParameters();
                int paramCnt = param.Length;
                if (!i.IsStatic)
                    paramCnt++;
                sb.AppendLine(string.Format("        static StackObject* {0}_{1}(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)", i.Name, idx));
                sb.AppendLine("        {");
                sb.AppendLine("            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;");
                if (param.Length != 0 || !i.IsStatic)
                    sb.AppendLine("            StackObject* ptr_of_this_method;");
                sb.AppendLine(string.Format("            StackObject* __ret = ILIntepreter.Minus(__esp, {0});", paramCnt));
                sb.AppendLine();
                bool hasByRef = param.HasByRefParam();
                string shouldFreeParam = hasByRef ? "false" : "true";
                for (int j = param.Length; j > 0; j--)
                {
                    var p = param[j - 1];
                    sb.AppendLine(string.Format("            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});", param.Length - j + 1));
                    string clsName, realClsName;
                    bool isByRef;
                    p.ParameterType.GetClassName(out clsName, out realClsName, out isByRef);
                    var pt = p.ParameterType.IsByRef ? p.ParameterType.GetElementType() : p.ParameterType;
                    if (pt.IsValueType && !pt.IsPrimitive && valueTypeBinders != null && valueTypeBinders.Contains(pt))
                    {
                        if (isMultiArr)
                            sb.AppendLine(string.Format("            {0} a{1} = new {0}();", realClsName, j));
                        else
                            sb.AppendLine(string.Format("            {0} @{1} = new {0}();", realClsName, p.Name));

                        sb.AppendLine(string.Format("            if (ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder != null) {{", clsName));

                        if (isMultiArr)
                            sb.AppendLine(string.Format("                ILRuntime.Runtime.Generated.CLRBindings.s_{1}_Binder.ParseValue(ref a{0}, __intp, ptr_of_this_method, __mStack, {2});", j, clsName, shouldFreeParam));
                        else
                            sb.AppendLine(string.Format("                ILRuntime.Runtime.Generated.CLRBindings.s_{1}_Binder.ParseValue(ref @{0}, __intp, ptr_of_this_method, __mStack, {2});", p.Name, clsName, shouldFreeParam));

                        sb.AppendLine("            } else {");

                        if (isByRef)
                            sb.AppendLine("                ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);");
                        if (isMultiArr)
                            sb.AppendLine(string.Format("                a{0} = {1};", j, p.ParameterType.GetRetrieveValueCode(realClsName)));
                        else
                            sb.AppendLine(string.Format("                @{0} = {1};", p.Name, p.ParameterType.GetRetrieveValueCode(realClsName)));
                        if (!hasByRef)
                            sb.AppendLine("                __intp.Free(ptr_of_this_method);");

                        sb.AppendLine("            }");
                    }
                    else
                    {
                        if (isByRef)
                        {
                            if (p.ParameterType.GetElementType().IsPrimitive)
                            {
                                if (pt == typeof(int) || pt == typeof(uint) || pt == typeof(short) || pt == typeof(ushort) || pt == typeof(byte) || pt == typeof(sbyte) || pt == typeof(char))
                                {
                                    if (pt == typeof(int))
                                        sb.AppendLine(string.Format("            {0} @{1} = __intp.RetriveInt32(ptr_of_this_method, __mStack);", realClsName, p.Name));
                                    else
                                        sb.AppendLine(string.Format("            {0} @{1} = ({0})__intp.RetriveInt32(ptr_of_this_method, __mStack);", realClsName, p.Name));
                                }
                                else if (pt == typeof(long) || pt == typeof(ulong))
                                {
                                    if (pt == typeof(long))
                                        sb.AppendLine(string.Format("            {0} @{1} = __intp.RetriveInt64(ptr_of_this_method, __mStack);", realClsName, p.Name));
                                    else
                                        sb.AppendLine(string.Format("            {0} @{1} = ({0})__intp.RetriveInt64(ptr_of_this_method, __mStack);", realClsName, p.Name));
                                }
                                else if (pt == typeof(float))
                                {
                                    sb.AppendLine(string.Format("            {0} @{1} = __intp.RetriveFloat(ptr_of_this_method, __mStack);", realClsName, p.Name));
                                }
                                else if (pt == typeof(double))
                                {
                                    sb.AppendLine(string.Format("            {0} @{1} = __intp.RetriveDouble(ptr_of_this_method, __mStack);", realClsName, p.Name));
                                }
                                else if (pt == typeof(bool))
                                {
                                    sb.AppendLine(string.Format("            {0} @{1} = __intp.RetriveInt32(ptr_of_this_method, __mStack) == 1;", realClsName, p.Name));
                                }
                                else
                                    throw new NotSupportedException();
                            }
                            else
                            {
                                sb.AppendLine(string.Format("            {0} @{1} = ({0})typeof({0}).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack));", realClsName, p.Name));
                            }

                        }
                        else
                        {
                            if (isMultiArr)
                                sb.AppendLine(string.Format("            {0} a{1} = {2};", realClsName, j, p.ParameterType.GetRetrieveValueCode(realClsName)));
                            else
                                sb.AppendLine(string.Format("            {0} @{1} = {2};", realClsName, p.Name, p.ParameterType.GetRetrieveValueCode(realClsName)));
                            if (!hasByRef && !p.ParameterType.IsPrimitive)
                                sb.AppendLine("            __intp.Free(ptr_of_this_method);");

                        }
                    }
                    sb.AppendLine();
                }
                if (!i.IsStatic)
                {
                    sb.AppendLine(string.Format("            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});", paramCnt));
                    if (type.IsPrimitive)
                        sb.AppendLine(string.Format("            {0} instance_of_this_method = GetInstance(__domain, ptr_of_this_method, __mStack);", typeClsName));
                    else if (type.IsValueType && !type.IsPrimitive && valueTypeBinders != null && valueTypeBinders.Contains(type))
                    {
                        string clsName, realClsName;
                        bool isByRef;
                        type.GetClassName(out clsName, out realClsName, out isByRef);

                        sb.AppendLine(string.Format("            {0} instance_of_this_method = new {0}();", realClsName));

                        sb.AppendLine(string.Format("            if (ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder != null) {{", clsName));

                        sb.AppendLine(string.Format("                ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder.ParseValue(ref instance_of_this_method, __intp, ptr_of_this_method, __mStack, false);", clsName));

                        sb.AppendLine("            } else {");

                        if (type.IsValueType)
                            sb.AppendLine("                ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);");
                        sb.AppendLine(string.Format("                instance_of_this_method = {0};", type.GetRetrieveValueCode(typeClsName)));
                        if (!type.IsValueType && !hasByRef)
                            sb.AppendLine("                __intp.Free(ptr_of_this_method);");

                        sb.AppendLine("            }");
                    }
                    else
                    {
                        if (type.IsValueType)
                            sb.AppendLine("            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);");
                        sb.AppendLine(string.Format("            {0} instance_of_this_method = {1};", typeClsName, type.GetRetrieveValueCode(typeClsName)));
                        if (!type.IsValueType && !hasByRef)
                            sb.AppendLine("            __intp.Free(ptr_of_this_method);");
                    }
                }
                sb.AppendLine();
                if (i.ReturnType != typeof(void))
                {
                    sb.Append("            var result_of_this_method = ");
                }
                else
                    sb.Append("            ");
                string genericArguments = "";
                if (i.IsGenericMethod)
                {
                    var p = i.GetGenericArguments();
                    StringBuilder sb2 = new StringBuilder();
                    bool first = true;
                    sb2.Append('<');
                    foreach (var j in p)
                    {
                        if (first)
                            first = false;
                        else
                            sb2.Append(", ");
                        string clsName, realClsName;
                        bool isByRef;
                        j.GetClassName(out clsName, out realClsName, out isByRef);
                        sb2.Append(realClsName);
                    }
                    sb2.Append('>');
                    genericArguments = sb2.ToString();
                }
                if (i.IsStatic)
                {
                    if (isProperty)
                    {
                        string[] t = new string[2];
                        int firstUnderlineIndex = i.Name.IndexOf("_");
                        t[0] = i.Name.Substring(0, firstUnderlineIndex);
                        t[1] = i.Name.Substring(firstUnderlineIndex + 1);
                        string propType = t[0];

                        if (propType == "get")
                        {
                            bool isIndexer = param.Length > 0;
                            if (isIndexer)
                            {
                                sb.AppendLine(string.Format("{1}[{0}];", param[0].Name, typeClsName));
                            }
                            else
                                sb.AppendLine(string.Format("{1}.{0};", t[1], typeClsName));
                        }
                        else if (propType == "set")
                        {
                            bool isIndexer = param.Length > 1;
                            if (isIndexer)
                            {
                                sb.AppendLine(string.Format("{2}[{0}] = {1};", param[0].Name, param[1].Name, typeClsName));
                            }
                            else
                                sb.AppendLine(string.Format("{2}.{0} = {1};", t[1], param[0].Name, typeClsName));
                        }
                        else if (propType == "op")
                        {
                            switch (t[1])
                            {
                                case "Equality":
                                    sb.AppendLine(string.Format("{0} == {1};", param[0].Name, param[1].Name));
                                    break;
                                case "Inequality":
                                    sb.AppendLine(string.Format("{0} != {1};", param[0].Name, param[1].Name));
                                    break;
                                case "Addition":
                                    sb.AppendLine(string.Format("{0} + {1};", param[0].Name, param[1].Name));
                                    break;
                                case "Subtraction":
                                    sb.AppendLine(string.Format("{0} - {1};", param[0].Name, param[1].Name));
                                    break;
                                case "Multiply":
                                    sb.AppendLine(string.Format("{0} * {1};", param[0].Name, param[1].Name));
                                    break;
                                case "Division":
                                    sb.AppendLine(string.Format("{0} / {1};", param[0].Name, param[1].Name));
                                    break;
                                case "GreaterThan":
                                    sb.AppendLine(string.Format("{0} > {1};", param[0].Name, param[1].Name));
                                    break;
                                case "GreaterThanOrEqual":
                                    sb.AppendLine(string.Format("{0} >= {1};", param[0].Name, param[1].Name));
                                    break;
                                case "LessThan":
                                    sb.AppendLine(string.Format("{0} < {1};", param[0].Name, param[1].Name));
                                    break;
                                case "LessThanOrEqual":
                                    sb.AppendLine(string.Format("{0} <= {1};", param[0].Name, param[1].Name));
                                    break;
                                case "UnaryNegation":
                                    sb.AppendLine(string.Format("-{0};", param[0].Name));
                                    break;
                                case "Modulus":
                                    sb.AppendLine(string.Format("{0} % {1};", param[0].Name, param[1].Name));
                                    break;
                                case "Implicit":
                                case "Explicit":
                                    {
                                        string clsName, realClsName;
                                        bool isByRef;
                                        i.ReturnType.GetClassName(out clsName, out realClsName, out isByRef);
                                        sb.AppendLine(string.Format("({1}){0};", param[0].Name, realClsName));
                                    }
                                    break;
                                default:
                                    throw new NotImplementedException(i.Name);
                            }
                        }
                        else
                            throw new NotImplementedException();
                    }
                    else
                    {
                        sb.Append(string.Format("{0}.{1}{2}(", typeClsName, i.Name, genericArguments));
                        param.AppendParameters(sb);
                        sb.AppendLine(");");
                    }
                }
                else
                {
                    if (isProperty)
                    {
                        string[] t = new string[2];
                        int firstUnderlineIndex = i.Name.IndexOf("_");
                        t[0] = i.Name.Substring(0, firstUnderlineIndex);
                        t[1] = i.Name.Substring(firstUnderlineIndex + 1);
                        string propType = t[0];

                        if (propType == "get")
                        {
                            bool isIndexer = param.Length > 0;
                            if (isIndexer)
                            {
                                sb.AppendLine(string.Format("instance_of_this_method[{0}];", param[0].Name));
                            }
                            else
                                sb.AppendLine(string.Format("instance_of_this_method.{0};", t[1]));
                        }
                        else if (propType == "set")
                        {
                            bool isIndexer = param.Length > 1;
                            if (isIndexer)
                            {
                                sb.AppendLine(string.Format("instance_of_this_method[{0}] = {1};", param[0].Name, param[1].Name));
                            }
                            else
                                sb.AppendLine(string.Format("instance_of_this_method.{0} = {1};", t[1], param[0].Name));
                        }
                        else
                            throw new NotImplementedException();
                    }
                    else if (isMultiArr)
                    {
                        if (i.Name == "Get")
                        {
                            sb.Append("instance_of_this_method[");
                            param.AppendParameters(sb, true);
                            sb.AppendLine("];");
                        }
                        else
                        {
                            sb.Append("instance_of_this_method[");
                            param.AppendParameters(sb, true, 1);
                            sb.Append("]");
                            sb.Append(" = a");
                            sb.Append(param.Length);
                            sb.AppendLine(";");
                        }
                    }
                    else
                    {
                        sb.Append(string.Format("instance_of_this_method.{0}{1}(", i.Name, genericArguments));
                        param.AppendParameters(sb);
                        sb.AppendLine(");");
                    }
                }
                sb.AppendLine();

                //Ref/Out
                for (int j = param.Length; j > 0; j--)
                {
                    var p = param[j - 1];
                    if (!p.ParameterType.IsByRef && !hasByRef)
                    {
                        continue;
                    }
                    string clsName, realClsName;
                    bool isByRef;
                    var pt = p.ParameterType.IsByRef ? p.ParameterType.GetElementType() : p.ParameterType;
                    pt.GetClassName(out clsName, out realClsName, out isByRef);
                    sb.AppendLine(string.Format("            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});", param.Length - j + 1));
                    if (p.ParameterType.IsByRef)
                    {
                        sb.AppendLine(@"            switch(ptr_of_this_method->ObjectType)
            {
                case ObjectTypes.StackObjectReference:
                    {
                        var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method);");

                        if (pt.IsValueType && !pt.IsPrimitive && valueTypeBinders != null && valueTypeBinders.Contains(pt))
                        {
                            sb.AppendLine(string.Format("                if (ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder != null) {{", clsName));

                            sb.AppendLine(string.Format("                        ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder.WriteBackValue(__domain, ptr_of_this_method, __mStack, ref {1});", clsName, p.Name));

                            sb.AppendLine("                } else {");

                            pt.GetRefWriteBackValueCode(sb, p.Name);

                            sb.AppendLine("                }");
                        }
                        else
                        {
                            pt.GetRefWriteBackValueCode(sb, p.Name);
                        }

                        sb.Append(@"                    }
                    break;
                case ObjectTypes.FieldReference:
                    {
                        var ___obj = __mStack[ptr_of_this_method->Value];
                        if(___obj is ILTypeInstance)
                        {
                            ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @");
                        sb.Append(p.Name);
                        sb.Append(@";
                        }
                        else
                        {
                            var ___type = __domain.GetType(___obj.GetType()) as CLRType;
                            ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @");
                        sb.Append(p.Name);
                        sb.Append(@");
                        }
                    }
                    break;
                case ObjectTypes.StaticFieldReference:
                    {
                        var ___type = __domain.GetType(ptr_of_this_method->Value);
                        if(___type is ILType)
                        {
                            ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @");
                        sb.Append(p.Name);
                        sb.Append(@";
                        }
                        else
                        {
                            ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @");
                        sb.Append(p.Name);
                        sb.Append(@");
                        }
                    }
                    break;
                 case ObjectTypes.ArrayReference:
                    {
                        var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as ");
                        sb.Append(realClsName);
                        sb.Append(@"[];
                        instance_of_arrayReference[ptr_of_this_method->ValueLow] = @");
                        sb.Append(p.Name);
                        sb.AppendLine(@";
                    }
                    break;
            }");
                        sb.AppendLine();
                    }
                    else if(pt.IsValueType && !pt.IsPrimitive)
                    {
                        sb.AppendLine("            __intp.FreeStackValueType(ptr_of_this_method);");
                    }

                    sb.AppendLine("            __intp.Free(ptr_of_this_method);");
                }

                if (!i.IsStatic && ((type.IsValueType && !type.IsPrimitive) || hasByRef))//need to write back value type instance
                {
                    sb.AppendLine(string.Format("            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});", paramCnt));

                    if (type.IsValueType && !type.IsPrimitive)
                    {
                        if (valueTypeBinders != null && valueTypeBinders.Contains(type))
                        {
                            string clsName, realClsName;
                            bool isByRef;
                            type.GetClassName(out clsName, out realClsName, out isByRef);

                            sb.AppendLine(string.Format("            if (ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder != null) {{", clsName));

                            sb.AppendLine(string.Format("                ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder.WriteBackValue(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);", clsName));

                            sb.AppendLine("            } else {");

                            sb.AppendLine("                WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);");

                            sb.AppendLine("            }");
                        }
                        else
                        {
                            sb.AppendLine("            WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);");
                        }
                        sb.AppendLine();
                    }
                    sb.AppendLine("            __intp.Free(ptr_of_this_method);");
                }

                if (i.ReturnType != typeof(void))
                {
                    if (i.ReturnType.IsValueType && !i.ReturnType.IsPrimitive && valueTypeBinders != null && valueTypeBinders.Contains(i.ReturnType))
                    {
                        string clsName, realClsName;
                        bool isByRef;
                        i.ReturnType.GetClassName(out clsName, out realClsName, out isByRef);

                        sb.AppendLine(string.Format("            if (ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder != null) {{", clsName));

                        sb.AppendLine(string.Format("                ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder.PushValue(ref result_of_this_method, __intp, __ret, __mStack);", clsName));
                        sb.AppendLine("                return __ret + 1;");

                        sb.AppendLine("            } else {");

                        i.ReturnType.GetReturnValueCode(sb, domain);

                        sb.AppendLine("            }");
                    }
                    else
                    {
                        i.ReturnType.GetReturnValueCode(sb, domain);
                    }
                }
                else
                    sb.AppendLine("            return __ret;");
                sb.AppendLine("        }");
                sb.AppendLine();
                idx++;
            }

            return sb.ToString();
        }
    }
}


text:
import { Injectable } from '@angular/core';
import {
  CanActivate, Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private afAuth: AngularFireAuth, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.checkLogin();
  }

  checkLogin(): Observable<boolean> {
    return this.afAuth.authState
      .pipe(
        map(user => {
            if (user) {
                return true;
            }
            this.router.navigate(['/admin/login']);
            return false;
        })
      );
  }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef __CPUPOWER_BITMASK__
#define __CPUPOWER_BITMASK__

/* Taken over from libbitmask, a project initiated from sgi:
 * Url:            http://oss.sgi.com/projects/cpusets/
 * Unfortunately it's not very widespread, therefore relevant parts are
 * pasted here.
 */

struct bitmask {
	unsigned int size;
	unsigned long *maskp;
};

struct bitmask *bitmask_alloc(unsigned int n);
void bitmask_free(struct bitmask *bmp);

struct bitmask *bitmask_setbit(struct bitmask *bmp, unsigned int i);
struct bitmask *bitmask_setall(struct bitmask *bmp);
struct bitmask *bitmask_clearall(struct bitmask *bmp);

unsigned int bitmask_first(const struct bitmask *bmp);
unsigned int bitmask_next(const struct bitmask *bmp, unsigned int i);
unsigned int bitmask_last(const struct bitmask *bmp);
int bitmask_isallclear(const struct bitmask *bmp);
int bitmask_isbitset(const struct bitmask *bmp, unsigned int i);

int bitmask_parselist(const char *buf, struct bitmask *bmp);
int bitmask_displaylist(char *buf, int len, const struct bitmask *bmp);

#endif /*__CPUPOWER_BITMASK__ */


text:
window.project = true;

// Project Shader Store

// Browser Window Services

//////////////////////////////////////////////
// Babylon Toolkit - Browser Window Services
//////////////////////////////////////////////

/** Firelight Audio Shims */
window.firelightAudio = 0;
window.firelightDebug = false;
if (window.firelightAudio === 1 || window.firelightAudio === 2) {
	var fmodjs = "scripts/fmodstudio.js";
	if (window.firelightDebug === true) {
		fmodjs = ("scripts/" + (window.firelightAudio === 1) ? "fmodstudioL.js" : "fmodL.js");
	} else {
		fmodjs = ("scripts/" + (window.firelightAudio === 1) ? "fmodstudio.js" : "fmod.js");
	}
	var script2 = document.createElement('script');
	script2.setAttribute("type","text/javascript");
	script2.setAttribute("src", fmodjs);
	if (document.head != null) {
		document.head.appendChild(script2);
	} else if (document.body != null) {
		document.body.appendChild(script2);
	}
}

/** Windows Launch Mode */
window.preferredLaunchMode = 0;
if (typeof Windows !== "undefined" && typeof Windows.UI !== "undefined" && typeof Windows.UI.ViewManagement !== "undefined" &&typeof Windows.UI.ViewManagement.ApplicationView !== "undefined") {
	Windows.UI.ViewManagement.ApplicationView.preferredLaunchWindowingMode = (window.preferredLaunchMode === 1) ? Windows.UI.ViewManagement.ApplicationViewWindowingMode.fullScreen : Windows.UI.ViewManagement.ApplicationViewWindowingMode.auto;
}

/** Xbox Full Screen Shims */
document.querySelector('style').textContent += "@media (max-height: 1080px) { @-ms-viewport { height: 1080px; } }";

/** Xbox Live Plugin Shims */
window.xboxLiveServices = false;
window.isXboxLivePluginEnabled = function() {
	var isXboxLive = (typeof Windows !== "undefined" && typeof Microsoft !== "undefined" && typeof Microsoft.Xbox !== "undefined" && typeof Microsoft.Xbox.Services !== "undefined");
	var hasToolkit = (typeof BabylonToolkit !== "undefined" && typeof BabylonToolkit.XboxLive !== "undefined" && typeof BabylonToolkit.XboxLive.Plugin !== "undefined");
	return (window.xboxLiveServices === true && isXboxLive === true && hasToolkit === true);
}

/** Generic Promise Shims */
window.createGenericPromise = function(resolveRejectHandler) {
	return new Promise(resolveRejectHandler);
}
window.resolveGenericPromise = function(resolveObject) {
    return Promise.resolve(resolveObject);
}

// RotatingCube.ts
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
/* Babylon Mesh Component Template */
var PROJECT;
/* Babylon Mesh Component Template */
(function (PROJECT) {
    var Rotate = /** @class */ (function (_super) {
        __extends(Rotate, _super);
        function Rotate(owner, scene, tick, propertyBag) {
            if (tick === void 0) { tick = true; }
            if (propertyBag === void 0) { propertyBag = {}; }
            return _super.call(this, owner, scene, tick, propertyBag) || this;
        }
        Rotate.prototype.ready = function () {
            // Scene execute when ready
        };
        Rotate.prototype.start = function () {
            /* Start render loop function */
            // Create the gizmo and attach to the box
            this.gizmo = new BABYLON.RotationGizmo();
            this.gizmo.attachedMesh = this.mesh;
            // Keep the gizmo fixed to world rotation
            this.gizmo.updateGizmoRotationToMatchAttachedMesh = false;
            this.gizmo.updateGizmoPositionToMatchAttachedMesh = true;
        };
        Rotate.prototype.update = function () {
            /* Update render loop function */
            var _this = this;
            // Toggle gizmo on keypress
            document.onkeydown = function () {
                _this.gizmo.attachedMesh = !_this.gizmo.attachedMesh ? _this.mesh : null;
            };
        };
        return Rotate;
    }(BABYLON.MeshComponent));
    PROJECT.Rotate = Rotate;
})(PROJECT || (PROJECT = {}));


text:
require 'spec_helper'

describe Gitmine::Branch do
  before do
    Gitmine::Git.stub!(:local_branches) { <<-GIT_OUTPUT
  2632-invoice-should-accept-date
  2675
  * 2869-BUG-accepted-by-not-set
  master
  production
GIT_OUTPUT
    }

    Gitmine::Git.stub!(:remote_branches) { <<-GIT_OUTPUT
  origin/2890-email-aliases
  origin/2915-sanitize-eft-fields
  origin/HEAD -> origin/master
  origin/master
  origin/production
GIT_OUTPUT
    }

    Gitmine::Git.stub!(:fetch)
  end

  describe "#local_branches" do
    it "should return an array of branches starting with digits only" do
      Gitmine::Branch.local_branches.
        should == %w(2632-invoice-should-accept-date 2675 2869-BUG-accepted-by-not-set)
    end
  end

  describe "#remote_branches" do
    it "should return an array of branches starting with digits only" do
      Gitmine::Branch.remote_branches.
        should == %w( 2890-email-aliases 2915-sanitize-eft-fields )
    end
  end

  describe "find_local(issue_id)" do
    context "when the branch exists" do
      it "should return the branch name" do
        Gitmine::Branch.find_local('2632').
          should == '2632-invoice-should-accept-date'
      end
    end

    context "when the does not exists" do
      it "should return nil" do
        Gitmine::Branch.find_local('9999').
          should == nil
      end
    end
  end

  describe "find_remote(issue_id)" do
    context "when the branch exists" do
      it "should return the branch name" do
        Gitmine::Branch.find_remote('2890').
          should == '2890-email-aliases'
      end
    end

    context "when the does not exists" do
      it "should return nil" do
        Gitmine::Branch.find_remote('9999').
          should == nil
      end
      it "should fetch and retry" do
        Gitmine::Git.should_receive(:fetch)
        Gitmine::Branch.should_receive(:clear_memoized_remote_branches!)
        # can't test the recursive call
        Gitmine::Branch.find_remote('9999')
      end
    end
  end

end


text:
using namespace sf1r;

bool CustomRanker::parse(izenelib::util::UString& ustrExp)
{
    string strExp;
    ustrExp.convertString(strExp, izenelib::util::UString::UTF_8);

    return parse(strExp);
}

bool CustomRanker::parse(std::string& strExp)
{
    trim(strExp); // important

    if (strExp.empty())
    {
        errorInfo_ = "Fialed to parse custom_rank[expression], it's empty.";
        return false;
    }

    if (strExp_ != strExp)
        strExp_ = strExp;

    tree_parse_info<> info = ast_parse(strExp.c_str(), customRankTreeParser_, space_p);
    //showBoostAST(info.trees, 0); // test

    if (!info.full)
    {
        errorInfo_ = "Failed to parse custom_rank[expression], error at \"" + std::string(strExp.c_str(), info.stop) +"^\"";
        return false;
    }

    ESTree_->children_.clear();
    return buildExpSyntaxTree(info.trees, ESTree_);
}

/// private ////////////////////////////////////////////////////////////////////

bool CustomRanker::buildExpSyntaxTree(const ast_info_trees& astrees, ExpSyntaxTreePtr& estree)
{
    for (ast_info_trees::const_iterator iter = astrees.begin(); iter != astrees.end(); ++iter)
    {
        // value in AST
        ExpSyntaxTree::NodeType type = static_cast<ExpSyntaxTree::NodeType>(iter->value.id().to_long());
        ExpSyntaxTreePtr child(new ExpSyntaxTree(type));
        switch (type)
        {
        case ExpSyntaxTree::CONSTANT:
        {
            string v(iter->value.begin(), iter->value.end());
            trim(v);
            //child->value_ = atof(v.c_str());
            if(!str2real(v, child->value_))
            {
                errorInfo_ = "Failed to parse \"" + v + "\" in custom_rank[expression], as a real number. ";
                return false;
            }
            break;
        }
        case ExpSyntaxTree::PARAMETER:
        {
            // parameter name
            string param(iter->value.begin(), iter->value.end());
            trim(param);

            // parameter value is constant value set by user, or is proptery name
            std::map<std::string, double>::iterator dbIter;
            std::map<std::string, std::string>::iterator proIter;
            if ((dbIter = paramConstValueMap_.find(param)) != paramConstValueMap_.end())
            {
                // param value is constant
                child->value_ = dbIter->second;
                child->type_ = ExpSyntaxTree::CONSTANT;
            }
            else if((proIter = paramPropertyValueMap_.find(param)) != paramPropertyValueMap_.end())
            {
                // param value is property name
                child->name_ = proIter->second;
                propertyDataTypeMap_.insert(std::make_pair(child->name_, UNKNOWN_DATA_PROPERTY_TYPE));
            }
            else
            {
                // value of param did not found in custom_rank[params],
                // assume parameter it self is a property name,
                // all property names will be checked later.
                child->name_ = param;
                propertyDataTypeMap_.insert(std::make_pair(child->name_, UNKNOWN_DATA_PROPERTY_TYPE));
            }
            break;
        }
        case ExpSyntaxTree::SUM:
        case ExpSyntaxTree::SUB:
        case ExpSyntaxTree::PRODUCT:
        case ExpSyntaxTree::DIV:
        case ExpSyntaxTree::LOG:
        case ExpSyntaxTree::POW:
        case ExpSyntaxTree::SQRT:
            break;
        default:
            break;
        }

        // children in AST
        if (!buildExpSyntaxTree(iter->children, child))
        {
            return false;
        }

        // add to children of EST
        estree->children_.push_back(child);
    }

    return true;
}

bool CustomRanker::setPropertyData(NumericPropertyTableBuilder* numericTableBuilder)
{
    cout << "[CustomRanker] setting PropertyData ..." << endl;

    if (!numericTableBuilder)
    {
        errorInfo_ = "NumericPropertyTableBuilder is NULL";
        return false;
    }

    return setInnerPropertyData(ESTree_, *numericTableBuilder);
}

bool CustomRanker::setInnerPropertyData(
    ExpSyntaxTreePtr& estree,
    NumericPropertyTableBuilder& numericTableBuilder)
{
    if (estree->type_ == ExpSyntaxTree::PARAMETER)
    {
        estree->propertyData_ =
            numericTableBuilder.createPropertyTable(estree->name_);

        if (!estree->propertyData_)
        {
            PropertyDataType dataType = propertyDataTypeMap_[estree->name_];
            stringstream ss;
            ss << "Failed to get sort data for property: " << estree->name_
               << " with data type: " << dataType << endl;
            errorInfo_ = ss.str();
            return false;
        }
    }

    for (est_iterator iter = estree->children_.begin(); iter != estree->children_.end(); iter++)
    {
        if (!setInnerPropertyData(*iter, numericTableBuilder))
            return false;
    }

    return true;
}

bool CustomRanker::sub_evaluate(ExpSyntaxTreePtr& estree, docid_t& docid)
{
    ExpSyntaxTree::NodeType type = estree->type_;

    switch (type)
    {
    case ExpSyntaxTree::ROOT:
    {
        sub_evaluate(estree->children_[0], docid);
        estree->value_ = estree->children_[0]->value_;
        break;
    }
    case ExpSyntaxTree::CONSTANT:
    {
        // constant value has been set already
        return true;
    }
    case ExpSyntaxTree::PARAMETER:
    {
        if (! estree->propertyData_)
            break;

        estree->propertyData_->getDoubleValue(docid, estree->value_);
        //cout << "CustomRanker::sub_evaluate docid(" << docid << ") get property \"" << estree->name_ << "\" data value: " << estree->value_ <<endl;
        break;
    }
    case ExpSyntaxTree::SUM:
    {
        sub_evaluate(estree->children_[0], docid);
        estree->value_ = estree->children_[0]->value_;
        sub_evaluate(estree->children_[1], docid);
        estree->value_ += estree->children_[1]->value_;
        break;
    }
    case ExpSyntaxTree::SUB:
    {
        sub_evaluate(estree->children_[0], docid);
        estree->value_ = estree->children_[0]->value_;
        sub_evaluate(estree->children_[1], docid);
        estree->value_ -= estree->children_[1]->value_;
        break;
    }
    case ExpSyntaxTree::PRODUCT:
    {
        sub_evaluate(estree->children_[0], docid);
        estree->value_ = estree->children_[0]->value_;
        sub_evaluate(estree->children_[1], docid);
        estree->value_ *= estree->children_[1]->value_;
        break;
    }
    case ExpSyntaxTree::DIV:
    {
        sub_evaluate(estree->children_[0], docid);
        estree->value_ = estree->children_[0]->value_;
        sub_evaluate(estree->children_[1], docid);
        if (estree->children_[1]->value_ < 1e-8 && estree->children_[1]->value_ > -1e-8)
        {
            errorInfo_ = "*Waring: division by zero, got zero from \"" + estree->children_[1]->name_ + "\"";
            cout << errorInfo_ << endl;
        }
        estree->value_ /= estree->children_[1]->value_;
        break;
    }
    case ExpSyntaxTree::LOG:
    {
        sub_evaluate(estree->children_[0], docid);
        estree->value_ = std::log(estree->children_[0]->value_);
        break;
    }
    case ExpSyntaxTree::POW:
    {
        sub_evaluate(estree->children_[0], docid);
        sub_evaluate(estree->children_[1], docid);
        estree->value_ = std::pow(estree->children_[0]->value_, estree->children_[1]->value_);
        break;
    }
    case ExpSyntaxTree::SQRT:
    {
        sub_evaluate(estree->children_[0], docid);
        estree->value_ = std::sqrt(estree->children_[0]->value_);
        break;
    }
    default:
        break;
    }

    return true;
}

void CustomRanker::showBoostAST(const ast_info_trees& trees, int level)
{
    if (level == 0)
    {
        cout << "[ AST (Syntax Tree): ]" << endl;
    }

    for (ast_info_trees::const_iterator iter = trees.begin(); iter != trees.end(); ++iter)
    {
        //tree_node<T>: value, children
        cout << string(level*4, ' ') << "|--["
             << string(iter->value.begin(), iter->value.end()) << " : "
             << ExpSyntaxTree::getTypeString(iter->value.id().to_long()) << "]" << endl;
        showBoostAST(iter->children, level+1);
    }
}

void CustomRanker::showEST(est_trees& trees, int level)
{
    for (est_iterator iter = trees.begin(); iter != trees.end(); iter++)
    {
        stringstream ss;
        ss << string(" : ") << iter->get()->name_ << " : &data = " << iter->get()->propertyData_.get();

        cout << string(level*4, ' ') << "|--["
             << ExpSyntaxTree::getTypeString(iter->get()->type_) << " : " << iter->get()->value_
             << ((iter->get()->type_ == ExpSyntaxTree::PARAMETER) ? ss.str() : "")
             << "]" << endl;

        showEST(iter->get()->children_, level+1);
    }
}

void CustomRanker::printESTree()
{
    cout << "[ EST (Expression Syntax Tree): ]" << endl;
    showEST(ESTree_->children_);
}


text:
import template from './postalAddress.html';
import controller from './postalAddress.controller';
import './postalAddress.styl';

let postalAddressComponent = {
  restrict: 'E',
  bindings: {isValid :'=?'},
  template,
  controller
};

export default postalAddressComponent;


text:
package fi.kela.kanta.util;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hl7.v3.POCDMT000040ClinicalDocument;

public class JaxbUtil {

    private static final Logger LOGGER = LogManager.getLogger(JaxbUtil.class);

    private JAXBContext jaxbContext = null;

    private JaxbUtil() throws JAXBException {
        jaxbContext = JAXBContext.newInstance(POCDMT000040ClinicalDocument.class);
    }

    private static JaxbUtil instance = null;

    public static JaxbUtil getInstance() throws JAXBException {
        if ( instance == null ) {
            instance = new JaxbUtil();
        }
        return instance;
    }

    public String marshalloi(POCDMT000040ClinicalDocument clinicalDocument) throws JAXBException {
        return marshalloi(clinicalDocument, null);
    }

    public String marshalloi(POCDMT000040ClinicalDocument clinicalDocument, String schemaLocation)
            throws JAXBException {
        long start = 0;
        if ( LOGGER.isDebugEnabled() ) {
            start = System.currentTimeMillis();
        }

        StringWriter out = new StringWriter();
        String s = null;
        try {
            JAXBElement<POCDMT000040ClinicalDocument> jaxbElement = new JAXBElement<POCDMT000040ClinicalDocument>(
                    new QName("urn:hl7-org:v3", "ClinicalDocument"), POCDMT000040ClinicalDocument.class,
                    clinicalDocument);
            Marshaller m = jaxbContext.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            if ( schemaLocation != null ) {
                m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, schemaLocation);
            }
            m.marshal(jaxbElement, out);
            s = out.toString();
        }
        catch (JAXBException e) {
            LOGGER.error("Marshallointi epäonnistui.", e);
            throw e;
        }

        if ( LOGGER.isDebugEnabled() ) {
            long end = System.currentTimeMillis();
            LOGGER.debug("Unmarshalling took " + (end - start) + " ms.");
        }

        return s;
    }

    public String arkistomarshalloi(POCDMT000040ClinicalDocument clinicalDocument, String schemaLocation)
            throws JAXBException {
        long start = 0;
        if ( LOGGER.isDebugEnabled() ) {
            start = System.currentTimeMillis();
        }

        StringWriter out = new StringWriter();
        String s = null;
        try {
            JAXBElement<POCDMT000040ClinicalDocument> jaxbElement = new JAXBElement<POCDMT000040ClinicalDocument>(
                    new QName("urn:hl7-org:v3", "ClinicalDocument"), POCDMT000040ClinicalDocument.class,
                    clinicalDocument);
            Marshaller m = jaxbContext.createMarshaller();
            m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new ArkistoNamespacePrefixMapper());
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            if ( schemaLocation != null ) {
                m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, schemaLocation);
            }
            m.marshal(jaxbElement, out);
            s = out.toString();
        }
        catch (JAXBException e) {
            LOGGER.error("Marshallointi epäonnistui.", e);
            throw e;
        }

        if ( LOGGER.isDebugEnabled() ) {
            long end = System.currentTimeMillis();
            LOGGER.debug("Unmarshalling took " + (end - start) + " ms.");
        }

        return s;
    }

    public POCDMT000040ClinicalDocument unmarshaller(String xml) throws JAXBException {
        long start = 0;
        if ( LOGGER.isDebugEnabled() ) {
            start = System.currentTimeMillis();
        }

        POCDMT000040ClinicalDocument result = null;
        try {
            StringReader reader = new StringReader(xml);
            Unmarshaller u = jaxbContext.createUnmarshaller();
            result = u.unmarshal(new StreamSource(reader), POCDMT000040ClinicalDocument.class).getValue();
        }
        catch (JAXBException e) {
            LOGGER.error("UnMarshallointi epäonnistui.", e.getMessage());
            throw e;
        }

        if ( LOGGER.isDebugEnabled() ) {
            long end = System.currentTimeMillis();
            LOGGER.debug("Unmarshalling took " + (end - start) + " ms.");
        }

        return result;
    }

}


text:
package lopes.br.basicproject;

import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject2;
import android.support.test.uiautomator.Until;
import android.widget.Button;
import android.widget.EditText;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import lopes.br.basicproject.ui.MainActivity;
import lopes.br.basicproject.util.Constants;
import lopes.br.basicproject.util.SharedPref;

@RunWith(AndroidJUnit4.class)
public class MainActivityUiAutomatorTest {

    private static SharedPref sharedPref;

    // Configure the Activity under test
    @Rule
    public ActivityTestRule<MainActivity> activityTestRule =
            new ActivityTestRule<>(MainActivity.class, false, false);

    @BeforeClass
    public static void setUpStatic() {
        sharedPref = SharedPref.getInstance();
    }

    @Before
    public void setUp() {
        // Clear all sharedPreferences
        sharedPref.clearSharedPref();
    }

    @Test
    public void success_login_test() {
        final String packageName = "lopes.br.basicproject";
        final String idUserResource = "lopes.br.basicproject:id/username";
        final String idPasswordResource = "lopes.br.basicproject:id/password";
        final String idButtonResource = "lopes.br.basicproject:id/btn_login";

        //Start Manually the Activity
        activityTestRule.launchActivity(null);

        // Get a reference of UIAutomator2
        UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

        // Type the text in User field
        final UiObject2 userObjectFound = uiDevice.wait(Until.findObject(By.clazz(EditText.class).pkg(packageName).res(idUserResource)), Constants.TIME_OUT_2_SECONDS);
        // Check if the user properly was found
        Assert.assertNotNull("Object user not found", userObjectFound);
        // Action
        userObjectFound.setText(Constants.USER);

        // Type the text in password field
        final UiObject2 passwordObjectFound = uiDevice.wait(Until.findObject(By.clazz(EditText.class).pkg(packageName).res(idPasswordResource)), Constants.TIME_OUT_2_SECONDS);
        // Check if the user properly was found
        Assert.assertNotNull("Object password not found", passwordObjectFound);
        // Action
        passwordObjectFound.setText(Constants.PASSWORD);

        // Find the Button object
        final UiObject2 buttonObjectFound = uiDevice.wait(Until.findObject(By.clazz(Button.class).pkg(packageName).res(idButtonResource)), Constants.TIME_OUT_2_SECONDS);
        // Check if the user properly was found
        Assert.assertNotNull("Object password not found", buttonObjectFound);
        // Action
        final Boolean result = buttonObjectFound.clickAndWait(Until.newWindow(), Constants.TIME_OUT_2_SECONDS);
        // Check for the result
        Assert.assertTrue("The new windows was not opened", result);
    }
}


text:
html{height:100%;background-color:#FFFFFF;}
body,td,th{font-family:Arial,Verdana,sans-serif;font-size: 12px;}
body{height:100%;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box;word-break:break-word;word-wrap:break-word;}

.editMode{margin:0px;padding:5px;overflow-y:auto;}
.editMode img:-moz-broken {-moz-force-broken-image-icon:1;height:24px;width:24px;}
.editMode table.xhe-border,.editMode table.xhe-border th,.editMode table.xhe-border td{border:1px dotted #d3d3d3;}
.editMode embed{display:inline-block;border:1px dashed #FF4E4E;}
.editMode embed[type="application/x-shockwave-flash"]{background:url(img/flash.gif) center center no-repeat;}
.editMode embed[type="application/x-mplayer2"]{background:url(img/wmp.gif) center center no-repeat;}
.editMode .xhe-paste{position:absolute;left:-1000px;overflow:hidden;width:1px;height:1px;}
.editMode .xhe-anchor{display:inline-block;background: url(img/anchor.gif) no-repeat;border: 1px dotted #0000FF;width:16px;height:15px;overflow:hidden;}

.sourceMode{margin:0px;padding:0px;overflow:hidden;height:100%;}
.sourceMode textarea{*position:absolute;border:0px;margin:0px;padding:0px;width:100%;height:100%;overflow-y:auto;font-family:'Courier New',Courier,monospace !important;font-size:10pt;}

.previewMode{margin:5px;padding:0px;}

.showBlocktag p,.showBlocktag h1,.showBlocktag h2,.showBlocktag h3,.showBlocktag h4,.showBlocktag h5,.showBlocktag h6,.showBlocktag pre,.showBlocktag address,.showBlocktag div{background:none no-repeat scroll right top;border:1px dotted gray;}
.showBlocktag p{background-image:url(img/tag-p.gif);}
.showBlocktag h1{background-image:url(img/tag-h1.gif);}
.showBlocktag h2{background-image:url(img/tag-h2.gif);}
.showBlocktag h3{background-image:url(img/tag-h3.gif);}
.showBlocktag h4{background-image:url(img/tag-h4.gif);}
.showBlocktag h5{background-image:url(img/tag-h5.gif);}
.showBlocktag h6{background-image:url(img/tag-h6.gif);}
.showBlocktag pre{background-image:url(img/tag-pre.gif);}
.showBlocktag address{background-image:url(img/tag-address.gif);}
.showBlocktag div{background-image:url(img/tag-div.gif);}


text:
using System;

using Foundation;
using UIKit;

namespace HelloXamarin
{
	public partial class ReminderListCell : UITableViewCell
	{
		public static readonly NSString Key = new NSString("ReminderListCell");
		public static readonly UINib Nib;
		public const long THR_DAYS = 3 * 24 * 60 * 60 * 1000L;
		public UIViewController mVc;

		static ReminderListCell()
		{
			Nib = UINib.FromName("ReminderListCell", NSBundle.MainBundle);
		}

		protected ReminderListCell(IntPtr handle) : base(handle)
		{
			// Note: this .ctor should not contain any initialization logic.
		}

		public void updateCell(ReminderData data, UIViewController vc) {

			mVc = vc;

			userNameLa.AdjustsFontSizeToFitWidth = false;
			userNameLa.Text = data.userName;

			bookNameLa.Lines = 2;
			bookNameLa.AdjustsFontSizeToFitWidth = false;
			bookNameLa.Text = data.bookName;

			emailLa.Lines = 3;
			emailLa.AdjustsFontSizeToFitWidth = false;
			emailLa.Text = data.userEmail;

			backView.Layer.CornerRadius = 9;

			timeLa.AdjustsFontSizeToFitWidth = false;
			timeLa.Text = TimeUtil.TransTime(data.returnTime);
			timeLa.TextColor = UIColor.White;
			timeLa.Layer.CornerRadius = 11;
			timeLa.Layer.MasksToBounds = true;

			switch (data.type) {
				case Constant.RE_TYPE_COMMON:
					backView.BackgroundColor = ColorUtil.geneRateColor(ColorUtil.RE_GREEN);
					timeLa.BackgroundColor = ColorUtil.geneRateColor(ColorUtil.RE_GREEN_D);
					break;
				case Constant.RE_TYPE_URGENCY:
					backView.BackgroundColor = ColorUtil.geneRateColor(ColorUtil.RE_OR);
					timeLa.BackgroundColor = ColorUtil.geneRateColor(ColorUtil.RE_OR_D);
					break;
				case Constant.RE_TYPE_OVERDUE:
					backView.BackgroundColor = ColorUtil.geneRateColor(ColorUtil.RE_RED);
					timeLa.BackgroundColor = ColorUtil.geneRateColor(ColorUtil.RE_RED_D);
					break;
			}

		}

	}
}


text:
"""
    appstructure.zc.buildout
    ~~~~~~~~~~~~~~~~~~~~~~~~

    Deploy using zc.buildout and PythonPaste
    http://flask.pocoo.org/snippets/27/
"""

"""
Deploy the application
First, you could save the buildout directory using your favorite DVCS, or create a tarball for future deployments.

Then bootstrap the buildout:

~/buildout_env $ python bootstrap.py --distribute
Adjust your settings in buildout.cfg, and build the application:

~/buildout_env $ bin/buildout
Run the tests:

~/buildout_env $ bin/test
Test rendered page. ... ok

------------------------------------------------------------
Ran 1 test in 0.055s

OK
~/buildout_env $
Now launch the server:

~/buildout_env $ bin/flask-ctl debug fg
bin/paster serve parts/etc/debug.ini --reload
Starting subprocess with file monitor
Starting server in PID 24862.
serving on http://127.0.0.1:5000
Visit http://127.0.0.1:5000 with your browser.
Visit http://127.0.0.1:5000/?broken to bring the Werkzeug Debugger. Quit the application with Ctrl+C.

Note: when you change the configuration in buildout.cfg, you need to rebuild the application using bin/buildout.

Further reading:

http://www.buildout.org
http://pythonpaste.org

"""


text:
<?php

namespace admin\filters;

class LargeThumbnail extends \admin\base\Filter
{
    public function identifier()
    {
        return 'large-thumbnail';
    }

    public function name()
    {
        return 'Thumbnail gross (800x800)';
    }

    public function chain()
    {
        return [
            [self::EFFECT_THUMBNAIL, [
                'width' => 800,
                'height' => 800,
            ]],
        ];
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Jace.Operations
{
    public class Division : Operation
    {
        public Division(DataType dataType, Operation dividend, Operation divisor)
            : base(dataType, dividend.DependsOnVariables || divisor.DependsOnVariables)
        {
            this.Dividend = dividend;
            this.Divisor = divisor;
        }

        public Operation Dividend { get; internal set; }
        public Operation Divisor { get; internal set; }
    }
}


text:
#ifndef ART_RUNTIME_GC_COLLECTOR_MARK_SWEEP_INL_H_
#define ART_RUNTIME_GC_COLLECTOR_MARK_SWEEP_INL_H_

#include "gc/collector/mark_sweep.h"

#include "gc/heap.h"
#include "mirror/art_field.h"
#include "mirror/class-inl.h"
#include "mirror/object_array-inl.h"
#include "mirror/reference.h"

namespace art {
namespace gc {
namespace collector {

template<typename MarkVisitor, typename ReferenceVisitor>
inline void MarkSweep::ScanObjectVisit(mirror::Object* obj, const MarkVisitor& visitor,
                                       const ReferenceVisitor& ref_visitor) {
  DCHECK(IsMarked(obj)) << "Scanning unmarked object " << obj << "\n" << heap_->DumpSpaces();
  obj->VisitReferences<false>(visitor, ref_visitor);
  if (kCountScannedTypes) {
    mirror::Class* klass = obj->GetClass<kVerifyNone>();
    if (UNLIKELY(klass == mirror::Class::GetJavaLangClass())) {
      ++class_count_;
    } else if (UNLIKELY(klass->IsArrayClass<kVerifyNone>())) {
      ++array_count_;
    } else {
      ++other_count_;
    }
  }
}

}  // namespace collector
}  // namespace gc
}  // namespace art

#endif  // ART_RUNTIME_GC_COLLECTOR_MARK_SWEEP_INL_H_


text:
package notification

import (
	"github.com/apache/servicecomb-service-center/pkg/gopool"
	"testing"
	"time"
)

type mockSubscriberChan struct {
	*BaseSubscriber
	job chan NotifyJob
}

func (s *mockSubscriberChan) OnMessage(job NotifyJob) {
	s.job <- job
}

func TestProcessor_Do(t *testing.T) {
	delay := 50 * time.Millisecond
	mock1 := &mockSubscriberChan{BaseSubscriber: NewSubscriber(INSTANCE, "s1", "g1"),
		job: make(chan NotifyJob, 1)}
	mock2 := &mockSubscriberChan{BaseSubscriber: NewSubscriber(INSTANCE, "s1", "g2"),
		job: make(chan NotifyJob, 1)}
	p := NewProcessor("p1", 0)
	gopool.Go(p.Do)
	if p.Name() != "p1" {
		t.Fatalf("TestProcessor_Do")
	}
	if p.Subjects(mock1.Subject()) != nil {
		t.Fatalf("TestProcessor_Do")
	}
	p.AddSubscriber(mock1)
	if p.Subjects(mock1.Subject()).Groups(mock1.Group()).Subscribers(mock1.Id()) != mock1 {
		t.Fatalf("TestProcessor_Do")
	}
	p.Remove(NewSubscriber(INSTANCE, "s2", "g1"))
	p.Remove(NewSubscriber(INSTANCE, "s1", "g2"))
	p.Remove(mock1)
	if p.Subjects(mock1.Subject()) != nil {
		t.Fatalf("TestProcessor_Do")
	}
	p.AddSubscriber(mock1)
	p.Clear()
	if p.Subjects(mock1.Subject()) != nil {
		t.Fatalf("TestProcessor_Do")
	}
	p.AddSubscriber(mock1)
	p.AddSubscriber(mock2)
	job := &BaseNotifyJob{group: "g1"}
	p.Accept(job)
	select {
	case <-mock1.job:
		t.Fatalf("TestProcessor_Do")
	case <-time.After(delay):
	}
	job.subject = "s1"
	job.group = "g3"
	p.Accept(job)
	select {
	case <-mock1.job:
		t.Fatalf("TestProcessor_Do")
	case <-time.After(delay):
	}
	job.subject = "s1"
	job.group = "g1"
	p.Accept(job)
	select {
	case j := <-mock1.job:
		if j != job {
			t.Fatalf("TestProcessor_Do")
		}
	case <-time.After(delay):
		t.Fatalf("TestProcessor_Do")
	}
	select {
	case <-mock2.job:
		t.Fatalf("TestProcessor_Do")
	case <-time.After(delay):
	}
	job.subject = "s1"
	job.group = ""
	p.Accept(job)
	select {
	case j := <-mock1.job:
		if j != job {
			t.Fatalf("TestProcessor_Do")
		}
	case <-time.After(delay):
		t.Fatalf("TestProcessor_Do")
	}
	select {
	case j := <-mock2.job:
		if j != job {
			t.Fatalf("TestProcessor_Do")
		}
	case <-time.After(delay):
		t.Fatalf("TestProcessor_Do")
	}
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Diagnostics
{
    internal sealed class DiagnosticDataLocation
    {
        public readonly DocumentId DocumentId;

        // text can be either given or calculated from original line/column
        public readonly TextSpan? SourceSpan;

        /// <summary>
        /// Null if path is not mapped and <see cref="OriginalFilePath"/> contains the actual path.
        /// Note that the value might be a relative path. In that case <see cref="OriginalFilePath"/> should be used
        /// as a base path for path resolution.
        /// </summary>
        public readonly string MappedFilePath;
        public readonly int MappedStartLine;
        public readonly int MappedStartColumn;
        public readonly int MappedEndLine;
        public readonly int MappedEndColumn;
        public readonly string OriginalFilePath;
        public readonly int OriginalStartLine;
        public readonly int OriginalStartColumn;
        public readonly int OriginalEndLine;
        public readonly int OriginalEndColumn;

        public DiagnosticDataLocation(
            DocumentId documentId = null,
            TextSpan? sourceSpan = null,
            string originalFilePath = null,
            int originalStartLine = 0,
            int originalStartColumn = 0,
            int originalEndLine = 0,
            int originalEndColumn = 0,
            string mappedFilePath = null,
            int mappedStartLine = 0,
            int mappedStartColumn = 0,
            int mappedEndLine = 0,
            int mappedEndColumn = 0)
        {
            DocumentId = documentId;
            SourceSpan = sourceSpan;
            MappedFilePath = mappedFilePath;
            MappedStartLine = mappedStartLine;
            MappedStartColumn = mappedStartColumn;
            MappedEndLine = mappedEndLine;
            MappedEndColumn = mappedEndColumn;
            OriginalFilePath = originalFilePath;
            OriginalStartLine = originalStartLine;
            OriginalStartColumn = originalStartColumn;
            OriginalEndLine = originalEndLine;
            OriginalEndColumn = originalEndColumn;
        }

        internal DiagnosticDataLocation WithCalculatedSpan(TextSpan newSourceSpan)
        {
            Contract.ThrowIfTrue(this.SourceSpan.HasValue);

            return new DiagnosticDataLocation(this.DocumentId,
                newSourceSpan, this.OriginalFilePath,
                this.OriginalStartLine, this.OriginalStartColumn,
                this.OriginalEndLine, this.OriginalEndColumn,
                this.MappedFilePath, this.MappedStartLine, this.MappedStartColumn,
                this.MappedEndLine, this.MappedEndColumn);
        }
    }

    internal sealed class DiagnosticData
    {
        public readonly string Id;
        public readonly string Category;

        public readonly string Message;
        public readonly string Description;
        public readonly string Title;
        public readonly string HelpLink;
        public readonly DiagnosticSeverity Severity;
        public readonly DiagnosticSeverity DefaultSeverity;
        public readonly bool IsEnabledByDefault;
        public readonly int WarningLevel;
        public readonly IReadOnlyList<string> CustomTags;
        public readonly ImmutableDictionary<string, string> Properties;
        public readonly bool IsSuppressed;

        public readonly string ENUMessageForBingSearch;

        public readonly Workspace Workspace;
        public readonly ProjectId ProjectId;
        public DocumentId DocumentId => this.DataLocation?.DocumentId;

        public readonly DiagnosticDataLocation DataLocation;
        public readonly IReadOnlyCollection<DiagnosticDataLocation> AdditionalLocations;

        public DiagnosticData(
            string id,
            string category,
            string message,
            string enuMessageForBingSearch,
            DiagnosticSeverity severity,
            bool isEnabledByDefault,
            int warningLevel,
            Workspace workspace,
            ProjectId projectId,
            DiagnosticDataLocation location = null,
            IReadOnlyCollection<DiagnosticDataLocation> additionalLocations = null,
            string title = null,
            string description = null,
            string helpLink = null,
            bool isSuppressed = false) :
                this(
                    id, category, message, enuMessageForBingSearch,
                    severity, severity, isEnabledByDefault, warningLevel,
                    ImmutableArray<string>.Empty, ImmutableDictionary<string, string>.Empty,
                    workspace, projectId, location, additionalLocations, title, description, helpLink, isSuppressed)
        {
        }

        public DiagnosticData(
            string id,
            string category,
            string message,
            string enuMessageForBingSearch,
            DiagnosticSeverity severity,
            DiagnosticSeverity defaultSeverity,
            bool isEnabledByDefault,
            int warningLevel,
            IReadOnlyList<string> customTags,
            ImmutableDictionary<string, string> properties,
            Workspace workspace,
            ProjectId projectId,
            DiagnosticDataLocation location = null,
            IReadOnlyCollection<DiagnosticDataLocation> additionalLocations = null,
            string title = null,
            string description = null,
            string helpLink = null,
            bool isSuppressed = false)
        {
            this.Id = id;
            this.Category = category;
            this.Message = message;
            this.ENUMessageForBingSearch = enuMessageForBingSearch;

            this.Severity = severity;
            this.DefaultSeverity = defaultSeverity;
            this.IsEnabledByDefault = isEnabledByDefault;
            this.WarningLevel = warningLevel;
            this.CustomTags = customTags;
            this.Properties = properties;

            this.Workspace = workspace;
            this.ProjectId = projectId;
            this.DataLocation = location;
            this.AdditionalLocations = additionalLocations;

            this.Title = title;
            this.Description = description;
            this.HelpLink = helpLink;
            this.IsSuppressed = isSuppressed;
        }

        public bool HasTextSpan { get { return (DataLocation?.SourceSpan).HasValue; } }

        /// <summary>
        /// return TextSpan if it exists, otherwise it will throw
        ///
        /// some diagnostic data such as created from build will have original line/column but not text span
        /// in those cases, use GetTextSpan method instead to calculate one from original line/column
        /// </summary>
        public TextSpan TextSpan { get { return (DataLocation?.SourceSpan).Value; } }

        public override bool Equals(object obj)
        {
            DiagnosticData other = obj as DiagnosticData;
            if (other == null)
            {
                return false;
            }

            return Id == other.Id &&
                    Category == other.Category &&
                    Message == other.Message &&
                    Severity == other.Severity &&
                    WarningLevel == other.WarningLevel &&
                    IsSuppressed == other.IsSuppressed &&
                    ProjectId == other.ProjectId &&
                    DocumentId == other.DocumentId &&
                    DataLocation?.OriginalStartLine == other?.DataLocation?.OriginalStartLine &&
                    DataLocation?.OriginalStartColumn == other?.DataLocation?.OriginalStartColumn;
        }

        public override int GetHashCode()
        {
            return Hash.Combine(this.Id,
                   Hash.Combine(this.Category,
                   Hash.Combine(this.Message,
                   Hash.Combine(this.WarningLevel,
                   Hash.Combine(this.IsSuppressed,
                   Hash.Combine(this.ProjectId,
                   Hash.Combine(this.DocumentId,
                   Hash.Combine(this.DataLocation?.OriginalStartLine ?? 0,
                   Hash.Combine(this.DataLocation?.OriginalStartColumn ?? 0, (int)this.Severity)))))))));
        }

        public override string ToString()
        {
            return string.Format("{0} {1} {2} {3} {4} {5} ({5}, {6}) [original: {7} ({8}, {9})]",
                Id,
                Severity,
                Message,
                ProjectId,
                DataLocation?.MappedFilePath ?? "",
                DataLocation?.MappedStartLine,
                DataLocation?.MappedStartColumn,
                DataLocation?.OriginalFilePath ?? "",
                DataLocation?.OriginalStartLine,
                DataLocation?.OriginalStartColumn);
        }

        public TextSpan GetExistingOrCalculatedTextSpan(SourceText text)
        {
            return HasTextSpan ? TextSpan : GetTextSpan(this.DataLocation, text);
        }

        public DiagnosticData WithCalculatedSpan(SourceText text)
        {
            Contract.ThrowIfNull(this.DocumentId);
            Contract.ThrowIfNull(this.DataLocation);
            Contract.ThrowIfTrue(HasTextSpan);

            var span = GetTextSpan(this.DataLocation, text);
            var newLocation = this.DataLocation.WithCalculatedSpan(span);
            return new DiagnosticData(this.Id, this.Category, this.Message, this.ENUMessageForBingSearch,
                this.Severity, this.DefaultSeverity, this.IsEnabledByDefault, this.WarningLevel,
                this.CustomTags, this.Properties, this.Workspace, this.ProjectId,
                newLocation, this.AdditionalLocations, this.Title, this.Description, this.HelpLink, this.IsSuppressed);
        }

        public async Task<Diagnostic> ToDiagnosticAsync(Project project, CancellationToken cancellationToken)
        {
            var location = await this.DataLocation.ConvertLocationAsync(project, cancellationToken).ConfigureAwait(false);
            var additionalLocations = await this.AdditionalLocations.ConvertLocationsAsync(project, cancellationToken).ConfigureAwait(false);

            return Diagnostic.Create(
                this.Id, this.Category, this.Message, this.Severity, this.DefaultSeverity,
                this.IsEnabledByDefault, this.WarningLevel, this.IsSuppressed, this.Title, this.Description, this.HelpLink,
                location, additionalLocations, customTags: this.CustomTags, properties: this.Properties);
        }

        public static TextSpan GetTextSpan(DiagnosticDataLocation dataLocation, SourceText text)
        {
            var lines = text.Lines;
            if (lines.Count == 0)
            {
                return default(TextSpan);
            }

            var originalStartLine = dataLocation?.OriginalStartLine ?? 0;
            if (originalStartLine >= lines.Count)
            {
                return new TextSpan(text.Length, 0);
            }

            int startLine, startColumn, endLine, endColumn;
            AdjustBoundaries(dataLocation, lines, out startLine, out startColumn, out endLine, out endColumn);

            var startLinePosition = new LinePosition(startLine, startColumn);
            var endLinePosition = new LinePosition(endLine, endColumn);
            SwapIfNeeded(ref startLinePosition, ref endLinePosition);

            var span = text.Lines.GetTextSpan(new LinePositionSpan(startLinePosition, endLinePosition));
            return TextSpan.FromBounds(Math.Min(Math.Max(span.Start, 0), text.Length), Math.Min(Math.Max(span.End, 0), text.Length));
        }

        private static void AdjustBoundaries(DiagnosticDataLocation dataLocation,
            TextLineCollection lines, out int startLine, out int startColumn, out int endLine, out int endColumn)
        {
            startLine = dataLocation?.OriginalStartLine ?? 0;
            var originalStartColumn = dataLocation?.OriginalStartColumn ?? 0;

            startColumn = Math.Max(originalStartColumn, 0);
            if (startLine < 0)
            {
                startLine = 0;
                startColumn = 0;
            }

            endLine = dataLocation?.OriginalEndLine ?? 0;
            var originalEndColumn = dataLocation?.OriginalEndColumn ?? 0;

            endColumn = Math.Max(originalEndColumn, 0);
            if (endLine < 0)
            {
                endLine = startLine;
                endColumn = startColumn;
            }
            else if (endLine >= lines.Count)
            {
                endLine = lines.Count - 1;
                endColumn = lines[endLine].EndIncludingLineBreak;
            }
        }

        private static void SwapIfNeeded(ref LinePosition startLinePosition, ref LinePosition endLinePosition)
        {
            if (endLinePosition < startLinePosition)
            {
                var temp = startLinePosition;
                startLinePosition = endLinePosition;
                endLinePosition = temp;
            }
        }

        public static DiagnosticData Create(Workspace workspace, Diagnostic diagnostic)
        {
            Contract.Requires(diagnostic.Location == null || !diagnostic.Location.IsInSource);

            return new DiagnosticData(
                diagnostic.Id,
                diagnostic.Descriptor.Category,
                diagnostic.GetMessage(CultureInfo.CurrentUICulture),
                diagnostic.GetBingHelpMessage(),
                diagnostic.Severity,
                diagnostic.DefaultSeverity,
                diagnostic.Descriptor.IsEnabledByDefault,
                diagnostic.WarningLevel,
                diagnostic.Descriptor.CustomTags.AsImmutableOrEmpty(),
                diagnostic.Properties,
                workspace,
                projectId: null,
                title: diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture),
                description: diagnostic.Descriptor.Description.ToString(CultureInfo.CurrentUICulture),
                helpLink: diagnostic.Descriptor.HelpLinkUri,
                isSuppressed: diagnostic.IsSuppressed);
        }

        public static DiagnosticData Create(Project project, Diagnostic diagnostic)
        {
            Contract.Requires(diagnostic.Location == null || !diagnostic.Location.IsInSource);

            return new DiagnosticData(
                diagnostic.Id,
                diagnostic.Descriptor.Category,
                diagnostic.GetMessage(CultureInfo.CurrentUICulture),
                diagnostic.GetBingHelpMessage(),
                diagnostic.Severity,
                diagnostic.DefaultSeverity,
                diagnostic.Descriptor.IsEnabledByDefault,
                diagnostic.WarningLevel,
                diagnostic.Descriptor.CustomTags.AsImmutableOrEmpty(),
                diagnostic.Properties,
                project.Solution.Workspace,
                project.Id,
                title: diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture),
                description: diagnostic.Descriptor.Description.ToString(CultureInfo.CurrentUICulture),
                helpLink: diagnostic.Descriptor.HelpLinkUri,
                isSuppressed: diagnostic.IsSuppressed);
        }

        private static DiagnosticDataLocation CreateLocation(Document document, Location location)
        {
            if (document == null)
            {
                return null;
            }

            TextSpan sourceSpan;
            FileLinePositionSpan mappedLineInfo;
            FileLinePositionSpan originalLineInfo;
            GetLocationInfo(document, location, out sourceSpan, out originalLineInfo, out mappedLineInfo);

            var mappedStartLine = mappedLineInfo.StartLinePosition.Line;
            var mappedStartColumn = mappedLineInfo.StartLinePosition.Character;
            var mappedEndLine = mappedLineInfo.EndLinePosition.Line;
            var mappedEndColumn = mappedLineInfo.EndLinePosition.Character;

            var originalStartLine = originalLineInfo.StartLinePosition.Line;
            var originalStartColumn = originalLineInfo.StartLinePosition.Character;
            var originalEndLine = originalLineInfo.EndLinePosition.Line;
            var originalEndColumn = originalLineInfo.EndLinePosition.Character;

            return new DiagnosticDataLocation(document.Id, sourceSpan,
                originalLineInfo.Path, originalStartLine, originalStartColumn, originalEndLine, originalEndColumn,
                mappedLineInfo.GetMappedFilePathIfExist(), mappedStartLine, mappedStartColumn, mappedEndLine, mappedEndColumn);
        }

        public static DiagnosticData Create(Document document, Diagnostic diagnostic)
        {
            var location = CreateLocation(document, diagnostic.Location);

            var additionalLocations = diagnostic.AdditionalLocations.Count == 0
                ? (IReadOnlyCollection<DiagnosticDataLocation>)SpecializedCollections.EmptyArray<DiagnosticDataLocation>()
                : diagnostic.AdditionalLocations.Where(loc => loc.IsInSource)
                                                .Select(loc => CreateLocation(document.Project.GetDocument(loc.SourceTree), loc))
                                                .WhereNotNull()
                                                .ToReadOnlyCollection();

            return new DiagnosticData(
                diagnostic.Id,
                diagnostic.Descriptor.Category,
                diagnostic.GetMessage(CultureInfo.CurrentUICulture),
                diagnostic.GetBingHelpMessage(),
                diagnostic.Severity,
                diagnostic.DefaultSeverity,
                diagnostic.Descriptor.IsEnabledByDefault,
                diagnostic.WarningLevel,
                diagnostic.Descriptor.CustomTags.AsImmutableOrEmpty(),
                diagnostic.Properties,
                document.Project.Solution.Workspace,
                document.Project.Id,
                location,
                additionalLocations,
                title: diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture),
                description: diagnostic.Descriptor.Description.ToString(CultureInfo.CurrentUICulture),
                helpLink: diagnostic.Descriptor.HelpLinkUri,
                isSuppressed: diagnostic.IsSuppressed);
        }

        private static void GetLocationInfo(Document document, Location location, out TextSpan sourceSpan, out FileLinePositionSpan originalLineInfo, out FileLinePositionSpan mappedLineInfo)
        {
            var diagnosticSpanMappingService = document.Project.Solution.Workspace.Services.GetService<IWorkspaceVenusSpanMappingService>();
            if (diagnosticSpanMappingService != null)
            {
                diagnosticSpanMappingService.GetAdjustedDiagnosticSpan(document.Id, location, out sourceSpan, out originalLineInfo, out mappedLineInfo);
                return;
            }

            sourceSpan = location.SourceSpan;
            originalLineInfo = location.GetLineSpan();
            mappedLineInfo = location.GetMappedLineSpan();
        }
    }
}


text:
if(process.env.NODE_ENV === 'production'){
  export default './container/root.js'
}else{
  export default './container/root.dev.js'
}


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

namespace RElmah.Common.Model
{
    public class Error
    {
        public string Id { get; set; }

        public string Host { get; set; }
        public string Type { get; set; }
        public string Message { get; set; }
        public string Detail { get; set; }
        public string User { get; set; }
        public string StatusCode { get; set; }
        public DateTime Time { get; set; }
        public string Url { get; set; }

        public string WebHostHtmlMessage { get; set; }
        public string Source { get; set; }
        public IDictionary<string, string> ServerVariables { get; set; }
        public IDictionary<string, string> Form { get; set; }
        public IDictionary<string, object> Cookies { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BrawlStageManager {
	public partial class EnterSizeDialog : Form {
		public Size SizeEntry {
			get {
				return new Size((int)nudWidth.Value, (int)nudHeight.Value);
			}
			set {
				nudWidth.Value = value.Width;
				nudHeight.Value = value.Height;
			}
		}

		public EnterSizeDialog() {
			InitializeComponent();
		}
	}
}


text:
import styled from '@emotion/styled';
import { Tile } from '@rocket.chat/fuselage';

export const Source = styled(Tile)`
  cursor: pointer;
  width: 150px;
  height: 150px;
  overflow: hidden;
  text-align: center;

  &:hover {
    background-color: #eaeaea;
  }
`;


text:
$('#scrollbar1').tinyscrollbar();
$('#scrollbar2').tinyscrollbar({ axis: 'x' });
$('#scrollbar3').tinyscrollbar({ size: 100 });
$('#scrollbar4').tinyscrollbar({ sizethumb: 15 });

var oScrollbar5 = $('#scrollbar5');
oScrollbar5.tinyscrollbar();

//some operation that changes the viewport content...

oScrollbar5.tinyscrollbar_update();

var oScroll6 = $('#scrollbar6');
oScroll6.tinyscrollbar();

//add a click event to a button
$('#scrollbar6-anchor').click(function () {
    oScroll6.tinyscrollbar_update(50);
    return false;
});

var oScrollbar = $('#scrollbar1');
oScrollbar.tinyscrollbar();

oScrollbar.tinyscrollbar_update();
oScrollbar.tinyscrollbar_update('bottom');


text:
package org.wso2.carbon.apimgt.internal.service.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.ArrayList;
import java.util.List;
import org.wso2.carbon.apimgt.internal.service.dto.ApplicationDTO;
import org.wso2.carbon.apimgt.internal.service.dto.PaginationDTO;
import javax.validation.constraints.*;

import io.swagger.annotations.*;
import java.util.Objects;

import javax.xml.bind.annotation.*;
import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope;
import com.fasterxml.jackson.annotation.JsonCreator;

public class ApplicationListDTO   {

    private Integer count = null;
    private List<ApplicationDTO> list = new ArrayList<>();
    private PaginationDTO pagination = null;

  /**
   * Number of Applications returned.
   **/
  public ApplicationListDTO count(Integer count) {
    this.count = count;
    return this;
  }

  @ApiModelProperty(example = "1", value = "Number of Applications returned. ")
  @JsonProperty("count")
  public Integer getCount() {
    return count;
  }
  public void setCount(Integer count) {
    this.count = count;
  }

  /**
   **/
  public ApplicationListDTO list(List<ApplicationDTO> list) {
    this.list = list;
    return this;
  }

  @ApiModelProperty(value = "")
  @JsonProperty("list")
  public List<ApplicationDTO> getList() {
    return list;
  }
  public void setList(List<ApplicationDTO> list) {
    this.list = list;
  }

  /**
   **/
  public ApplicationListDTO pagination(PaginationDTO pagination) {
    this.pagination = pagination;
    return this;
  }

  @ApiModelProperty(value = "")
  @JsonProperty("pagination")
  public PaginationDTO getPagination() {
    return pagination;
  }
  public void setPagination(PaginationDTO pagination) {
    this.pagination = pagination;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    ApplicationListDTO applicationList = (ApplicationListDTO) o;
    return Objects.equals(count, applicationList.count) &&
        Objects.equals(list, applicationList.list) &&
        Objects.equals(pagination, applicationList.pagination);
  }

  @Override
  public int hashCode() {
    return Objects.hash(count, list, pagination);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class ApplicationListDTO {\n");

    sb.append("    count: ").append(toIndentedString(count)).append("\n");
    sb.append("    list: ").append(toIndentedString(list)).append("\n");
    sb.append("    pagination: ").append(toIndentedString(pagination)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
<?php
/* SVN FILE: $Id: fb00_fb4f.php 6311 2008-01-02 06:33:52Z phpnut $ */
/**
 * Case Folding Properties.
 *
 * Provides case mapping of Unicode characters for code points U+FB00 through U+FB4F
 *
 * @see http://www.unicode.org/Public/UNIDATA/UCD.html
 * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt
 * @see http://www.unicode.org/reports/tr21/tr21-5.html
 *
 * PHP versions 4 and 5
 *
 * CakePHP(tm) :  Rapid Development Framework <http://www.cakephp.org/>
 * Copyright 2005-2008, Cake Software Foundation, Inc.
 *								1785 E. Sahara Avenue, Suite 490-204
 *								Las Vegas, Nevada 89104
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright		Copyright 2005-2008, Cake Software Foundation, Inc.
 * @link				http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
 * @package			cake
 * @subpackage		cake.cake.config.unicode.casefolding
 * @since			CakePHP(tm) v 1.2.0.5691
 * @version			$Revision: 6311 $
 * @modifiedby		$LastChangedBy: phpnut $
 * @lastmodified	$Date: 2008-01-02 00:33:52 -0600 (Wed, 02 Jan 2008) $
 * @license			http://www.opensource.org/licenses/mit-license.php The MIT License
 */
/**
 * The upper field is the decimal value of the upper case character
 *
 * The lower filed is an array of the decimal values that form the lower case version of a character.
 *
 *	The status field is:
 * C: common case folding, common mappings shared by both simple and full mappings.
 * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces.
 * S: simple case folding, mappings to single characters where different from F.
 * T: special case for uppercase I and dotted uppercase I
 *   - For non-Turkic languages, this mapping is normally not used.
 *   - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters.
 *     Note that the Turkic mappings do not maintain canonical equivalence without additional processing.
 *     See the discussions of case mapping in the Unicode Standard for more information.
 */
$config['fb00_fb4f'][] = array('upper' => 64256, 'status' => 'F', 'lower' => array(102, 102)); /* LATIN SMALL LIGATURE FF */
$config['fb00_fb4f'][] = array('upper' => 64257, 'status' => 'F', 'lower' => array(102, 105)); /* LATIN SMALL LIGATURE FI */
$config['fb00_fb4f'][] = array('upper' => 64258, 'status' => 'F', 'lower' => array(102, 108)); /* LATIN SMALL LIGATURE FL */
$config['fb00_fb4f'][] = array('upper' => 64259, 'status' => 'F', 'lower' => array(102, 102, 105)); /* LATIN SMALL LIGATURE FFI */
$config['fb00_fb4f'][] = array('upper' => 64260, 'status' => 'F', 'lower' => array(102, 102, 108)); /* LATIN SMALL LIGATURE FFL */
$config['fb00_fb4f'][] = array('upper' => 64261, 'status' => 'F', 'lower' => array(115, 116)); /* LATIN SMALL LIGATURE LONG S T */
$config['fb00_fb4f'][] = array('upper' => 64262, 'status' => 'F', 'lower' => array(115, 116)); /* LATIN SMALL LIGATURE ST */
$config['fb00_fb4f'][] = array('upper' => 64275, 'status' => 'F', 'lower' => array(1396, 1398)); /* ARMENIAN SMALL LIGATURE MEN NOW */
$config['fb00_fb4f'][] = array('upper' => 64276, 'status' => 'F', 'lower' => array(1396, 1381)); /* ARMENIAN SMALL LIGATURE MEN ECH */
$config['fb00_fb4f'][] = array('upper' => 64277, 'status' => 'F', 'lower' => array(1396, 1387)); /* ARMENIAN SMALL LIGATURE MEN INI */
$config['fb00_fb4f'][] = array('upper' => 64278, 'status' => 'F', 'lower' => array(1406, 1398)); /* ARMENIAN SMALL LIGATURE VEW NOW */
$config['fb00_fb4f'][] = array('upper' => 64279, 'status' => 'F', 'lower' => array(1396, 1389)); /* ARMENIAN SMALL LIGATURE MEN XEH */
?>


text:
package org.apache.wicket.atmosphere;

import com.google.common.base.Predicate;

/**
 * A filter that always returns true.
 *
 * @author papegaaij
 */
public class NoFilterPredicate implements Predicate<AtmosphereEvent>
{
	@Override
	public boolean apply(AtmosphereEvent input)
	{
		return true;
	}
}