// 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.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using Microsoft.CodeAnalysis.Collections;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis
{
    internal static class MetadataHelpers
    {
        public const char DotDelimiter = '.';
        public const string DotDelimiterString = ".";
        public const char GenericTypeNameManglingChar = '`';
        private const string GenericTypeNameManglingString = "`";
        public const int MaxStringLengthForParamSize = 22;
        public const int MaxStringLengthForIntToStringConversion = 22;
        public const string SystemString = "System";

        // These can appear in the interface name that precedes an explicit interface implementation member.
        public const char MangledNameRegionStartChar = '<';
        public const char MangledNameRegionEndChar = '>';

        internal struct AssemblyQualifiedTypeName
        {
            internal readonly string TopLevelType;
            internal readonly string[] NestedTypes;
            internal readonly AssemblyQualifiedTypeName[] TypeArguments;
            internal readonly int PointerCount;

            /// <summary>
            /// Rank equal 0 is used to denote an SzArray, rank equal 1 denotes multi-dimensional array of rank 1.
            /// </summary>
            internal readonly int[] ArrayRanks;
            internal readonly string AssemblyName;

            internal AssemblyQualifiedTypeName(
                string topLevelType,
                string[] nestedTypes,
                AssemblyQualifiedTypeName[] typeArguments,
                int pointerCount,
                int[] arrayRanks,
                string assemblyName)
            {
                this.TopLevelType = topLevelType;
                this.NestedTypes = nestedTypes;
                this.TypeArguments = typeArguments;
                this.PointerCount = pointerCount;
                this.ArrayRanks = arrayRanks;
                this.AssemblyName = assemblyName;
            }
        }

        internal static AssemblyQualifiedTypeName DecodeTypeName(string s)
        {
            var decoder = new SerializedTypeDecoder(s);
            return decoder.DecodeTypeName();
        }

        /// <summary>
        /// Decodes a serialized type name in its canonical form. The canonical name is its full type name, followed
        /// optionally by the assembly where it is defined, its version, culture and public key token.  If the assembly
        /// name is omitted, the type name is in the current assembly otherwise it is in the referenced assembly. The
        /// full type name is the fully qualified metadata type name.
        /// </summary>
        private struct SerializedTypeDecoder
        {
            private static readonly char[] s_typeNameDelimiters = { '+', ',', '[', ']', '*' };
            private readonly string _input;
            private int _offset;

            internal SerializedTypeDecoder(string s)
            {
                _input = s;
                _offset = 0;
            }

            private void Advance()
            {
                if (!EndOfInput)
                {
                    _offset++;
                }
            }

            private void AdvanceTo(int i)
            {
                if (i <= _input.Length)
                {
                    _offset = i;
                }
            }

            private bool EndOfInput
            {
                get
                {
                    return _offset >= _input.Length;
                }
            }

            private int Offset
            {
                get
                {
                    return _offset;
                }
            }

            private char Current
            {
                get
                {
                    return _input[_offset];
                }
            }

            /// <summary>
            /// Decodes a type name.  A type name is a string which is terminated by the end of the string or one of the
            /// delimiters '+', ',', '[', ']'. '+' separates nested classes. '[' and ']'
            /// enclosed generic type arguments.  ',' separates types.
            /// </summary>
            internal AssemblyQualifiedTypeName DecodeTypeName(bool isTypeArgument = false, bool isTypeArgumentWithAssemblyName = false)
            {
                Debug.Assert(!isTypeArgumentWithAssemblyName || isTypeArgument);

                string topLevelType = null;
                ArrayBuilder<string> nestedTypesBuilder = null;
                AssemblyQualifiedTypeName[] typeArguments = null;
                int pointerCount = 0;
                ArrayBuilder<int> arrayRanksBuilder = null;
                string assemblyName = null;
                bool decodingTopLevelType = true;
                bool isGenericTypeName = false;

                var pooledStrBuilder = PooledStringBuilder.GetInstance();
                StringBuilder typeNameBuilder = pooledStrBuilder.Builder;

                while (!EndOfInput)
                {
                    int i = _input.IndexOfAny(s_typeNameDelimiters, _offset);
                    if (i >= 0)
                    {
                        char c = _input[i];

                        // Found name, which could be a generic name with arity.
                        // Generic type parameter count, if any, are handled in DecodeGenericName.
                        string decodedString = DecodeGenericName(i);
                        Debug.Assert(decodedString != null);

                        // Type name is generic if the decoded name of the top level type OR any of the outer types of a nested type had the '`' character.
                        isGenericTypeName = isGenericTypeName || decodedString.IndexOf(GenericTypeNameManglingChar) >= 0;
                        typeNameBuilder.Append(decodedString);

                        switch (c)
                        {
                            case '*':
                                if (arrayRanksBuilder != null)
                                {
                                    // Error case, array shape must be specified at the end of the type name.
                                    // Process as a regular character and continue.
                                    typeNameBuilder.Append(c);
                                }
                                else
                                {
                                    pointerCount++;
                                }

                                Advance();
                                break;

                            case '+':
                                if (arrayRanksBuilder != null || pointerCount > 0)
                                {
                                    // Error case, array shape must be specified at the end of the type name.
                                    // Process as a regular character and continue.
                                    typeNameBuilder.Append(c);
                                }
                                else
                                {
                                    // Type followed by nested type. Handle nested class separator and collect the nested types.
                                    HandleDecodedTypeName(typeNameBuilder.ToString(), decodingTopLevelType, ref topLevelType, ref nestedTypesBuilder);
                                    typeNameBuilder.Clear();
                                    decodingTopLevelType = false;
                                }

                                Advance();
                                break;

                            case '[':
                                // Is type followed by generic type arguments?
                                if (isGenericTypeName && typeArguments == null)
                                {
                                    Advance();
                                    if (arrayRanksBuilder != null || pointerCount > 0)
                                    {
                                        // Error case, array shape must be specified at the end of the type name.
                                        // Process as a regular character and continue.
                                        typeNameBuilder.Append(c);
                                    }
                                    else
                                    {
                                        // Decode type arguments.
                                        typeArguments = DecodeTypeArguments();
                                    }
                                }
                                else
                                {
                                    // Decode array shape.
                                    DecodeArrayShape(typeNameBuilder, ref arrayRanksBuilder);
                                }

                                break;

                            case ']':
                                if (isTypeArgument)
                                {
                                    // End of type arguments.  This occurs when the last type argument is a type in the
                                    // current assembly.
                                    goto ExitDecodeTypeName;
                                }
                                else
                                {
                                    // Error case, process as a regular character and continue.
                                    typeNameBuilder.Append(c);
                                    Advance();
                                    break;
                                }

                            case ',':
                                // A comma may separate a type name from its assembly name or a type argument from
                                // another type argument.
                                // If processing non-type argument or a type argument with assembly name,
                                // process the characters after the comma as an assembly name.
                                if (!isTypeArgument || isTypeArgumentWithAssemblyName)
                                {
                                    Advance();
                                    if (!EndOfInput && Char.IsWhiteSpace(Current))
                                    {
                                        Advance();
                                    }

                                    assemblyName = DecodeAssemblyName(isTypeArgumentWithAssemblyName);
                                }
                                goto ExitDecodeTypeName;

                            default:
                                throw ExceptionUtilities.UnexpectedValue(c);
                        }
                    }
                    else
                    {
                        typeNameBuilder.Append(DecodeGenericName(_input.Length));
                        goto ExitDecodeTypeName;
                    }
                }

            ExitDecodeTypeName:
                HandleDecodedTypeName(typeNameBuilder.ToString(), decodingTopLevelType, ref topLevelType, ref nestedTypesBuilder);
                pooledStrBuilder.Free();

                return new AssemblyQualifiedTypeName(
                    topLevelType,
                    nestedTypesBuilder?.ToArrayAndFree(),
                    typeArguments,
                    pointerCount,
                    arrayRanksBuilder?.ToArrayAndFree(),
                    assemblyName);
            }

            private static void HandleDecodedTypeName(string decodedTypeName, bool decodingTopLevelType, ref string topLevelType, ref ArrayBuilder<string> nestedTypesBuilder)
            {
                if (decodedTypeName.Length != 0)
                {
                    if (decodingTopLevelType)
                    {
                        Debug.Assert(topLevelType == null);
                        topLevelType = decodedTypeName;
                    }
                    else
                    {
                        if (nestedTypesBuilder == null)
                        {
                            nestedTypesBuilder = ArrayBuilder<string>.GetInstance();
                        }

                        nestedTypesBuilder.Add(decodedTypeName);
                    }
                }
            }

            /// <summary>
            /// Decodes a generic name.  This is a type name followed optionally by a type parameter count
            /// </summary>
            private string DecodeGenericName(int i)
            {
                Debug.Assert(i == _input.Length || s_typeNameDelimiters.Contains(_input[i]));

                var length = i - _offset;
                if (length == 0)
                {
                    return String.Empty;
                }

                // Save start of name. The name should be the emitted name including the '`'  and arity.
                int start = _offset;
                AdvanceTo(i);

                // Get the emitted name.
                return _input.Substring(start, _offset - start);
            }

            private AssemblyQualifiedTypeName[] DecodeTypeArguments()
            {
                if (EndOfInput)
                {
                    return null;
                }

                var typeBuilder = ArrayBuilder<AssemblyQualifiedTypeName>.GetInstance();

                while (!EndOfInput)
                {
                    typeBuilder.Add(DecodeTypeArgument());

                    if (!EndOfInput)
                    {
                        switch (Current)
                        {
                            case ',':
                                // More type arguments follow
                                Advance();
                                if (!EndOfInput && Char.IsWhiteSpace(Current))
                                {
                                    Advance();
                                }
                                break;

                            case ']':
                                // End of type arguments
                                Advance();
                                return typeBuilder.ToArrayAndFree();

                            default:
                                throw ExceptionUtilities.UnexpectedValue(EndOfInput);
                        }
                    }
                }

                return typeBuilder.ToArrayAndFree();
            }

            private AssemblyQualifiedTypeName DecodeTypeArgument()
            {
                bool isTypeArgumentWithAssemblyName = false;
                if (Current == '[')
                {
                    isTypeArgumentWithAssemblyName = true;
                    Advance();
                }

                AssemblyQualifiedTypeName result = DecodeTypeName(isTypeArgument: true, isTypeArgumentWithAssemblyName: isTypeArgumentWithAssemblyName);

                if (isTypeArgumentWithAssemblyName)
                {
                    if (!EndOfInput && Current == ']')
                    {
                        Advance();
                    }
                }

                return result;
            }

            private string DecodeAssemblyName(bool isTypeArgumentWithAssemblyName)
            {
                if (EndOfInput)
                {
                    return null;
                }

                int i;
                if (isTypeArgumentWithAssemblyName)
                {
                    i = _input.IndexOf(']', _offset);
                    if (i < 0)
                    {
                        i = _input.Length;
                    }
                }
                else
                {
                    i = _input.Length;
                }

                string name = _input.Substring(_offset, i - _offset);
                AdvanceTo(i);
                return name;
            }

            /// <summary>
            /// Rank equal 0 is used to denote an SzArray, rank equal 1 denotes multi-dimensional array of rank 1.
            /// </summary>
            private void DecodeArrayShape(StringBuilder typeNameBuilder, ref ArrayBuilder<int> arrayRanksBuilder)
            {
                Debug.Assert(Current == '[');

                int start = _offset;
                int rank = 1;
                bool isMultiDimensionalIfRankOne = false;
                Advance();

                while (!EndOfInput)
                {
                    switch (Current)
                    {
                        case ',':
                            rank++;
                            Advance();
                            break;

                        case ']':
                            if (arrayRanksBuilder == null)
                            {
                                arrayRanksBuilder = ArrayBuilder<int>.GetInstance();
                            }

                            arrayRanksBuilder.Add(rank == 1 && !isMultiDimensionalIfRankOne ? 0 : rank);
                            Advance();
                            return;

                        case '*':
                            if (rank != 1)
                            {
                                goto default;
                            }

                            Advance();
                            if (Current != ']')
                            {
                                // Error case, process as regular characters
                                typeNameBuilder.Append(_input.Substring(start, _offset - start));
                                return;
                            }

                            isMultiDimensionalIfRankOne = true;
                            break;

                        default:
                            // Error case, process as regular characters
                            Advance();
                            typeNameBuilder.Append(_input.Substring(start, _offset - start));
                            return;
                    }
                }

                // Error case, process as regular characters
                typeNameBuilder.Append(_input.Substring(start, _offset - start));
            }
        }

        private static readonly string[] s_aritySuffixesOneToNine = { "`1", "`2", "`3", "`4", "`5", "`6", "`7", "`8", "`9" };

        internal static string GetAritySuffix(int arity)
        {
            Debug.Assert(arity > 0);
            return (arity <= 9) ? s_aritySuffixesOneToNine[arity - 1] : string.Concat(GenericTypeNameManglingString, arity.ToString(CultureInfo.InvariantCulture));
        }

        internal static string ComposeAritySuffixedMetadataName(string name, int arity)
        {
            return arity == 0 ? name : name + GetAritySuffix(arity);
        }

        internal static int InferTypeArityFromMetadataName(string emittedTypeName)
        {
            int suffixStartsAt;
            return InferTypeArityFromMetadataName(emittedTypeName, out suffixStartsAt);
        }

        private static short InferTypeArityFromMetadataName(string emittedTypeName, out int suffixStartsAt)
        {
            Debug.Assert(emittedTypeName != null, "NULL actual name unexpected!!!");
            int emittedTypeNameLength = emittedTypeName.Length;

            int indexOfManglingChar;
            for (indexOfManglingChar = emittedTypeNameLength; indexOfManglingChar >= 1; indexOfManglingChar--)
            {
                if (emittedTypeName[indexOfManglingChar - 1] == GenericTypeNameManglingChar)
                {
                    break;
                }
            }

            if (indexOfManglingChar < 2 ||
               (emittedTypeNameLength - indexOfManglingChar) == 0 ||
               emittedTypeNameLength - indexOfManglingChar > MaxStringLengthForParamSize)
            {
                suffixStartsAt = -1;
                return 0;
            }

            // Given a name corresponding to <unmangledName>`<arity>,
            // extract the arity.
            string stringRepresentingArity = emittedTypeName.Substring(indexOfManglingChar);

            int arity;
            bool nonNumericCharFound = !int.TryParse(stringRepresentingArity, NumberStyles.None, CultureInfo.InvariantCulture, out arity);

            if (nonNumericCharFound || arity < 0 || arity > short.MaxValue ||
                stringRepresentingArity != arity.ToString())
            {
                suffixStartsAt = -1;
                return 0;
            }

            suffixStartsAt = indexOfManglingChar - 1;
            return (short)arity;
        }

        internal static string InferTypeArityAndUnmangleMetadataName(string emittedTypeName, out short arity)
        {
            int suffixStartsAt;
            arity = InferTypeArityFromMetadataName(emittedTypeName, out suffixStartsAt);

            if (arity == 0)
            {
                Debug.Assert(suffixStartsAt == -1);
                return emittedTypeName;
            }

            Debug.Assert(suffixStartsAt > 0 && suffixStartsAt < emittedTypeName.Length - 1);
            return emittedTypeName.Substring(0, suffixStartsAt);
        }

        internal static string UnmangleMetadataNameForArity(string emittedTypeName, int arity)
        {
            Debug.Assert(arity > 0);

            int suffixStartsAt;
            if (arity == InferTypeArityFromMetadataName(emittedTypeName, out suffixStartsAt))
            {
                Debug.Assert(suffixStartsAt > 0 && suffixStartsAt < emittedTypeName.Length - 1);
                return emittedTypeName.Substring(0, suffixStartsAt);
            }

            return emittedTypeName;
        }

        /// <summary>
        /// An ImmutableArray representing the single string "System"
        /// </summary>
        private static readonly ImmutableArray<string> s_splitQualifiedNameSystem = ImmutableArray.Create(SystemString);

        internal static ImmutableArray<string> SplitQualifiedName(
              string name)
        {
            Debug.Assert(name != null);

            if (name.Length == 0)
            {
                return ImmutableArray<string>.Empty;
            }

            // PERF: Avoid String.Split because of the allocations. Also, we can special-case
            // for "System" if it is the first or only part.

            int dots = 0;
            foreach (char ch in name)
            {
                if (ch == DotDelimiter)
                {
                    dots++;
                }
            }

            if (dots == 0)
            {
                return name == SystemString ? s_splitQualifiedNameSystem : ImmutableArray.Create(name);
            }

            var result = ArrayBuilder<string>.GetInstance(dots + 1);

            int start = 0;
            for (int i = 0; dots > 0; i++)
            {
                if (name[i] == DotDelimiter)
                {
                    int len = i - start;
                    if (len == 6 && start == 0 && name.StartsWith(SystemString, StringComparison.Ordinal))
                    {
                        result.Add(SystemString);
                    }
                    else
                    {
                        result.Add(name.Substring(start, len));
                    }

                    dots--;
                    start = i + 1;
                }
            }

            result.Add(name.Substring(start));

            return result.ToImmutableAndFree();
        }

        internal static string SplitQualifiedName(
            string pstrName,
            out string qualifier)
        {
            Debug.Assert(pstrName != null);

            // In mangled names, the original unmangled name is frequently included,
            // surrounded by angle brackets.  The unmangled name may contain dots
            // (e.g. if it is an explicit interface implementation) or paired angle
            // brackets (e.g. if the explicitly implemented interface is generic).
            var angleBracketDepth = 0;
            var delimiter = -1;
            for (int i = 0; i < pstrName.Length; i++)
            {
                switch (pstrName[i])
                {
                    case MangledNameRegionStartChar:
                        angleBracketDepth++;
                        break;
                    case MangledNameRegionEndChar:
                        angleBracketDepth--;
                        break;
                    case DotDelimiter:
                        // If we see consecutive dots, the second is part of the method name
                        // (i.e. ".ctor" or ".cctor").
                        if (angleBracketDepth == 0 && (i == 0 || delimiter < i - 1))
                        {
                            delimiter = i;
                        }
                        break;
                }
            }
            Debug.Assert(angleBracketDepth == 0);

            if (delimiter < 0)
            {
                qualifier = string.Empty;
                return pstrName;
            }

            if (delimiter == 6 && pstrName.StartsWith(SystemString, StringComparison.Ordinal))
            {
                qualifier = SystemString;
            }
            else
            {
                qualifier = pstrName.Substring(0, delimiter);
            }

            return pstrName.Substring(delimiter + 1);
        }

        internal static string BuildQualifiedName(
            string qualifier,
            string name)
        {
            Debug.Assert(name != null);

            if (!string.IsNullOrEmpty(qualifier))
            {
                return String.Concat(qualifier, DotDelimiterString, name);
            }

            return name;
        }

        /// <summary>
        /// Calculates information about types and namespaces immediately contained within a namespace.
        /// </summary>
        /// <param name="isGlobalNamespace">
        /// Is current namespace a global namespace?
        /// </param>
        /// <param name="namespaceNameLength">
        /// Length of the fully-qualified name of this namespace.
        /// </param>
        /// <param name="typesByNS">
        /// The sequence of groups of TypeDef row ids for types contained within the namespace,
        /// recursively including those from nested namespaces. The row ids must be grouped by the
        /// fully-qualified namespace name in case-sensitive manner.
        /// Key of each IGrouping is a fully-qualified namespace name, which starts with the name of
        /// this namespace. There could be multiple groups for each fully-qualified namespace name.
        ///
        /// The groups must be sorted by the keys in a manner consistent with comparer passed in as
        /// nameComparer. Therefore, all types immediately contained within THIS namespace, if any,
        /// must be in several IGrouping at the very beginning of the sequence.
        /// </param>
        /// <param name="nameComparer">
        /// Equality comparer to compare namespace names.
        /// </param>
        /// <param name="types">
        /// Output parameter, never null:
        /// A sequence of groups of TypeDef row ids for types immediately contained within this namespace.
        /// </param>
        /// <param name="namespaces">
        /// Output parameter, never null:
        /// A sequence with information about namespaces immediately contained within this namespace.
        /// For each pair:
        ///   Key - contains simple name of a child namespace.
        ///   Value - contains a sequence similar to the one passed to this function, but
        ///           calculated for the child namespace.
        /// </param>
        /// <remarks></remarks>
        public static void GetInfoForImmediateNamespaceMembers(
            bool isGlobalNamespace,
            int namespaceNameLength,
            IEnumerable<IGrouping<string, TypeDefinitionHandle>> typesByNS,
            StringComparer nameComparer,
            out IEnumerable<IGrouping<string, TypeDefinitionHandle>> types,
            out IEnumerable<KeyValuePair<string, IEnumerable<IGrouping<string, TypeDefinitionHandle>>>> namespaces)
        {
            Debug.Assert(typesByNS != null);
            Debug.Assert(namespaceNameLength >= 0);
            Debug.Assert(!isGlobalNamespace || namespaceNameLength == 0);

            // A list of groups of TypeDef row ids for types immediately contained within this namespace.
            var nestedTypes = new List<IGrouping<string, TypeDefinitionHandle>>();

            // A list accumulating information about namespaces immediately contained within this namespace.
            // For each pair:
            //   Key - contains simple name of a child namespace.
            //   Value – contains a sequence similar to the one passed to this function, but
            //           calculated for the child namespace.
            var nestedNamespaces = new List<KeyValuePair<string, IEnumerable<IGrouping<string, TypeDefinitionHandle>>>>();
            bool possiblyHavePairsWithDuplicateKey = false;

            var enumerator = typesByNS.GetEnumerator();

            using (enumerator)
            {
                if (enumerator.MoveNext())
                {
                    var pair = enumerator.Current;

                    // Simple name of the last encountered child namespace.
                    string lastChildNamespaceName = null;

                    // A list accumulating information about types within the last encountered child namespace.
                    // The list is similar to the sequence passed to this function.
                    List<IGrouping<string, TypeDefinitionHandle>> typesInLastChildNamespace = null;

                    // if there are any types in this namespace,
                    // they will be in the first several groups if their key length
                    // is equal to namespaceNameLength.
                    while (pair.Key.Length == namespaceNameLength)
                    {
                        nestedTypes.Add(pair);

                        if (!enumerator.MoveNext())
                        {
                            goto DoneWithSequence;
                        }

                        pair = enumerator.Current;
                    }

                    // Account for the dot following THIS namespace name.
                    if (!isGlobalNamespace)
                    {
                        namespaceNameLength++;
                    }

                    do
                    {
                        pair = enumerator.Current;

                        string childNamespaceName = ExtractSimpleNameOfChildNamespace(namespaceNameLength, pair.Key);

                        int cmp = nameComparer.Compare(lastChildNamespaceName, childNamespaceName);
                        if (cmp == 0)
                        {
                            // We are still processing the same child namespace
                            typesInLastChildNamespace.Add(pair);
                        }
                        else
                        {
                            // This is a new child namespace
                            if (cmp > 0)
                            {
                                // The sort order is violated for child namespace names. Obfuscation is the likely reason for this.
                                Debug.Assert((object)lastChildNamespaceName != null);
                                possiblyHavePairsWithDuplicateKey = true;
                            }

                            // Preserve information about previous child namespace.
                            if (typesInLastChildNamespace != null)
                            {
                                Debug.Assert(typesInLastChildNamespace.Count != 0);
                                nestedNamespaces.Add(
                                    new KeyValuePair<string, IEnumerable<IGrouping<string, TypeDefinitionHandle>>>(
                                        lastChildNamespaceName, typesInLastChildNamespace));
                            }

                            typesInLastChildNamespace = new List<IGrouping<string, TypeDefinitionHandle>>();
                            lastChildNamespaceName = childNamespaceName;
                            Debug.Assert((object)lastChildNamespaceName != null);

                            typesInLastChildNamespace.Add(pair);
                        }
                    }
                    while (enumerator.MoveNext());

                    // Preserve information about last child namespace.
                    if (typesInLastChildNamespace != null)
                    {
                        Debug.Assert(typesInLastChildNamespace.Count != 0);
                        nestedNamespaces.Add(
                            new KeyValuePair<string, IEnumerable<IGrouping<string, TypeDefinitionHandle>>>(
                                lastChildNamespaceName, typesInLastChildNamespace));
                    }

                DoneWithSequence:
                    /*empty statement*/
                    ;
                }
            } // using

            types = nestedTypes;

            // Merge pairs with the same key
            if (possiblyHavePairsWithDuplicateKey)
            {
                var names = new Dictionary<string, int>(nestedNamespaces.Count, nameComparer);

                for (int i = nestedNamespaces.Count - 1; i >= 0; i--)
                {
                    names[nestedNamespaces[i].Key] = i;
                }

                if (names.Count != nestedNamespaces.Count) // nothing to merge otherwise
                {
                    for (int i = 1; i < nestedNamespaces.Count; i++)
                    {
                        var pair = nestedNamespaces[i];
                        int keyIndex = names[pair.Key];
                        if (keyIndex != i)
                        {
                            Debug.Assert(keyIndex < i);
                            var primaryPair = nestedNamespaces[keyIndex];
                            nestedNamespaces[keyIndex] = KeyValuePair.Create(primaryPair.Key, primaryPair.Value.Concat(pair.Value));
                            nestedNamespaces[i] = default(KeyValuePair<string, IEnumerable<IGrouping<string, TypeDefinitionHandle>>>);
                        }
                    }

                    int removed = nestedNamespaces.RemoveAll(pair => (object)pair.Key == null);
                    Debug.Assert(removed > 0);
                }
            }

            namespaces = nestedNamespaces;

            Debug.Assert(types != null);
            Debug.Assert(namespaces != null);
        }

        /// <summary>
        /// Extract a simple name of a top level child namespace from potentially qualified namespace name.
        /// </summary>
        /// <param name="parentNamespaceNameLength">
        /// Parent namespace name length plus the dot.
        /// </param>
        /// <param name="fullName">
        /// Fully qualified namespace name.
        /// </param>
        /// <returns>
        /// Simple name of a top level child namespace, the left-most name following parent namespace name
        /// in the fully qualified name.
        /// </returns>
        private static string ExtractSimpleNameOfChildNamespace(
            int parentNamespaceNameLength,
            string fullName)
        {
            int index = fullName.IndexOf('.', parentNamespaceNameLength);

            if (index < 0)
            {
                return fullName.Substring(parentNamespaceNameLength);
            }
            else
            {
                return fullName.Substring(parentNamespaceNameLength, index - parentNamespaceNameLength);
            }
        }

        /// <summary>
        /// Determines whether given string can be used as a non-empty metadata identifier (a NUL-terminated UTF8 string).
        /// </summary>
        internal static bool IsValidMetadataIdentifier(string str)
        {
            return !string.IsNullOrEmpty(str) && str.IsValidUnicodeString() && str.IndexOf('\0') == -1;
        }

        /// <summary>
        /// True if the string doesn't contain incomplete surrogates.
        /// </summary>
        internal static bool IsValidUnicodeString(string str)
        {
            return str == null || str.IsValidUnicodeString();
        }

        internal static bool IsValidAssemblyOrModuleName(string name)
        {
            return GetAssemblyOrModuleNameErrorArgumentResourceName(name) == null;
        }

        internal static void CheckAssemblyOrModuleName(string name, CommonMessageProvider messageProvider, int code, DiagnosticBag diagnostics)
        {
            string errorArgumentResourceId = GetAssemblyOrModuleNameErrorArgumentResourceName(name);
            if (errorArgumentResourceId != null)
            {
                diagnostics.Add(
                    messageProvider.CreateDiagnostic(code, Location.None,
                        new CodeAnalysisResourcesLocalizableErrorArgument(errorArgumentResourceId)));
            }
        }

        internal static void CheckAssemblyOrModuleName(string name, CommonMessageProvider messageProvider, int code, ArrayBuilder<Diagnostic> builder)
        {
            string errorArgumentResourceId = GetAssemblyOrModuleNameErrorArgumentResourceName(name);
            if (errorArgumentResourceId != null)
            {
                builder.Add(
                    messageProvider.CreateDiagnostic(code, Location.None,
                        new CodeAnalysisResourcesLocalizableErrorArgument(errorArgumentResourceId)));
            }
        }

        private static string GetAssemblyOrModuleNameErrorArgumentResourceName(string name)
        {
            if (name == null)
            {
                return nameof(CodeAnalysisResources.NameCannotBeNull);
            }

            // Dev11 VB can produce assembly with no name (vbc /out:".dll" /target:library).
            // We disallow it. PEVerify reports an error: Assembly has no name.
            if (name.Length == 0)
            {
                return nameof(CodeAnalysisResources.NameCannotBeEmpty);
            }

            // Dev11 VB can produce assembly that starts with whitespace (vbc /out:" a.dll" /target:library).
            // We disallow it. PEVerify reports an error: Assembly name contains leading spaces.
            if (char.IsWhiteSpace(name[0]))
            {
                return nameof(CodeAnalysisResources.NameCannotStartWithWhitespace);
            }

            if (!IsValidMetadataFileName(name))
            {
                return nameof(CodeAnalysisResources.NameContainsInvalidCharacter);
            }

            return null;
        }

        /// <summary>
        /// Checks that the specified name is a valid metadata String and a file name.
        /// The specification isn't entirely consistent and complete but it mentions:
        ///
        /// 22.19.2: "Name shall index a non-empty string in the String heap. It shall be in the format {filename}.{extension} (e.g., 'foo.dll', but not 'c:\utils\foo.dll')."
        /// 22.30.2: "The format of Name is {file name}.{file extension} with no path or drive letter; on POSIX-compliant systems Name contains no colon, no forward-slash, no backslash."
        ///          As Microsoft specific constraint.
        ///
        /// A reasonable restriction seems to be a valid UTF8 non-empty string that doesn't contain '\0', '\', '/', ':' characters.
        /// </summary>
        internal static bool IsValidMetadataFileName(string name)
        {
            return FileNameUtilities.IsFileName(name) && IsValidMetadataIdentifier(name);
        }

        /// <summary>
        /// Determine if the given namespace and type names combine to produce the given fully qualified name.
        /// </summary>
        /// <param name="namespaceName">The namespace part of the split name.</param>
        /// <param name="typeName">The type name part of the split name.</param>
        /// <param name="fullyQualified">The fully qualified name to compare with.</param>
        /// <returns>true if the combination of <paramref name="namespaceName"/> and <paramref name="typeName"/> equals the fully-qualified name given by <paramref name="fullyQualified"/></returns>
        internal static bool SplitNameEqualsFullyQualifiedName(string namespaceName, string typeName, string fullyQualified)
        {
            // Look for "[namespaceName].[typeName]" exactly
            return fullyQualified.Length == namespaceName.Length + typeName.Length + 1 &&
                   fullyQualified[namespaceName.Length] == MetadataHelpers.DotDelimiter &&
                   fullyQualified.StartsWith(namespaceName, StringComparison.Ordinal) &&
                   fullyQualified.EndsWith(typeName, StringComparison.Ordinal);
        }

        internal static bool IsValidPublicKey(ImmutableArray<byte> bytes) => CryptoBlobParser.IsValidPublicKey(bytes);

        /// <summary>
        /// Given an input string changes it to be acceptable as a part of a type name.
        /// </summary>
        internal static string MangleForTypeNameIfNeeded(string moduleName)
        {
            var pooledStrBuilder = PooledStringBuilder.GetInstance();
            var s = pooledStrBuilder.Builder;
            s.Append(moduleName);
            s.Replace("Q", "QQ");
            s.Replace("_", "Q_");
            s.Replace('.', '_');

            return pooledStrBuilder.ToStringAndFree();
        }
    }
}

{'repo_name': 'ASDAlexander77/cs2cpp', 'stars': '140', 'repo_language': 'C#', 'file_name': '__ConsoleStream.cs', 'mime_type': 'text/plain', 'hash': -1473608480589031925, 'source_dataset': 'data'}


#ifndef OPTION_LIST_H
#define OPTION_LIST_H
#include "list.h"

typedef struct{
    char *key;
    char *val;
    int used;
} kvp;

list *read_data_cfg(char *filename);
int read_option(char *s, list *options);
void option_insert(list *l, char *key, char *val);
char *option_find(list *l, char *key);
char *option_find_str(list *l, char *key, char *def);
int option_find_int(list *l, char *key, int def);
int option_find_int_quiet(list *l, char *key, int def);
float option_find_float(list *l, char *key, float def);
float option_find_float_quiet(list *l, char *key, float def);
void option_unused(list *l);

#endif

{'repo_name': 'avanetten/simrdwn', 'stars': '138', 'repo_language': 'C', 'file_name': 'class_labels_car.pbtxt', 'mime_type': 'text/plain', 'hash': -6509977782944799715, 'source_dataset': 'data'}


/*****************************************************************************
 * Copyright (c) 2014-2020 OpenRCT2 developers
 *
 * For a complete list of all authors, please refer to contributors.md
 * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
 *
 * OpenRCT2 is licensed under the GNU General Public License version 3.
 *****************************************************************************/

#include "Drawing.h"

#include <cmath>
#include <cstdlib>

/**
 * Draws a horizontal line of specified colour to a buffer.
 *  rct2: 0x0068474C
 */
static void gfx_draw_line_on_buffer(rct_drawpixelinfo* dpi, char colour, int32_t y, int32_t x, int32_t no_pixels)
{
    y -= dpi->y;

    // Check to make sure point is in the y range
    if (y < 0)
        return;
    if (y >= dpi->height)
        return;
    // Check to make sure we are drawing at least a pixel
    if (!no_pixels)
        no_pixels++;

    x -= dpi->x;

    // If x coord outside range leave
    if (x < 0)
    {
        // Unless the number of pixels is enough to be in range
        no_pixels += x;
        if (no_pixels <= 0)
            return;
        // Resets starting point to 0 as we don't draw outside the range
        x = 0;
    }

    // Ensure that the end point of the line is within range
    if (x + no_pixels - dpi->width > 0)
    {
        // If the end point has any pixels outside range
        // cut them off. If there are now no pixels return.
        no_pixels -= x + no_pixels - dpi->width;
        if (no_pixels <= 0)
            return;
    }

    // Get the buffer we are drawing to and move to the first coordinate.
    uint8_t* bits_pointer = dpi->bits + y * (dpi->pitch + dpi->width) + x;

    // Draw the line to the specified colour
    for (; no_pixels > 0; --no_pixels, ++bits_pointer)
    {
        *bits_pointer = colour;
    }
}

/**
 * Draws a line on dpi if within dpi boundaries
 *  rct2: 0x00684466
 * dpi (edi)
 * x1 (ax)
 * y1 (bx)
 * x2 (cx)
 * y2 (dx)
 * colour (ebp)
 */
void gfx_draw_line_software(rct_drawpixelinfo* dpi, int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t colour)
{
    // Check to make sure the line is within the drawing area
    if ((x1 < dpi->x) && (x2 < dpi->x))
    {
        return;
    }

    if ((y1 < dpi->y) && (y2 < dpi->y))
    {
        return;
    }

    if ((x1 > (dpi->x + dpi->width)) && (x2 > (dpi->x + dpi->width)))
    {
        return;
    }

    if ((y1 > (dpi->y + dpi->height)) && (y2 > (dpi->y + dpi->height)))
    {
        return;
    }

    // Bresenham's algorithm

    // If vertical plot points upwards
    int32_t steep = std::abs(y2 - y1) > std::abs(x2 - x1);
    if (steep)
    {
        int32_t temp_y2 = y2;
        int32_t temp_x2 = x2;
        y2 = x1;
        x2 = y1;
        y1 = temp_x2;
        x1 = temp_y2;
    }

    // If line is right to left swap direction
    if (x1 > x2)
    {
        int32_t temp_y2 = y2;
        int32_t temp_x2 = x2;
        y2 = y1;
        x2 = x1;
        y1 = temp_y2;
        x1 = temp_x2;
    }

    int32_t delta_x = x2 - x1;
    int32_t delta_y = std::abs(y2 - y1);
    int32_t error = delta_x / 2;
    int32_t y_step;
    int32_t y = y1;

    // Direction of step
    if (y1 < y2)
        y_step = 1;
    else
        y_step = -1;

    for (int32_t x = x1, x_start = x1, no_pixels = 1; x < x2; ++x, ++no_pixels)
    {
        // Vertical lines are drawn 1 pixel at a time
        if (steep)
            gfx_draw_line_on_buffer(dpi, colour, x, y, 1);

        error -= delta_y;
        if (error < 0)
        {
            // Non vertical lines are drawn with as many pixels in a horizontal line as possible
            if (!steep)
                gfx_draw_line_on_buffer(dpi, colour, y, x_start, no_pixels);

            // Reset non vertical line vars
            x_start = x + 1;
            no_pixels = 1;
            y += y_step;
            error += delta_x;
        }

        // Catch the case of the last line
        if (x + 1 == x2 && !steep)
        {
            gfx_draw_line_on_buffer(dpi, colour, y, x_start, no_pixels);
        }
    }
}

{'repo_name': 'OpenRCT2/OpenRCT2', 'stars': '8178', 'repo_language': 'C++', 'file_name': 'applytransparency.frag', 'mime_type': 'text/x-c', 'hash': 6908909050583261571, 'source_dataset': 'data'}


#include "clar_libgit2.h"
#include "checkout_helpers.h"
#include "refs.h"
#include "fileops.h"
#include "index.h"

void assert_on_branch(git_repository *repo, const char *branch)
{
	git_reference *head;
	git_buf bname = GIT_BUF_INIT;

	cl_git_pass(git_reference_lookup(&head, repo, GIT_HEAD_FILE));
	cl_assert_(git_reference_type(head) == GIT_REF_SYMBOLIC, branch);

	cl_git_pass(git_buf_joinpath(&bname, "refs/heads", branch));
	cl_assert_equal_s(bname.ptr, git_reference_symbolic_target(head));

	git_reference_free(head);
	git_buf_free(&bname);
}

void reset_index_to_treeish(git_object *treeish)
{
	git_object *tree;
	git_index *index;
	git_repository *repo = git_object_owner(treeish);

	cl_git_pass(git_object_peel(&tree, treeish, GIT_OBJ_TREE));

	cl_git_pass(git_repository_index(&index, repo));
	cl_git_pass(git_index_read_tree(index, (git_tree *)tree));
	cl_git_pass(git_index_write(index));

	git_object_free(tree);
	git_index_free(index);
}

int checkout_count_callback(
	git_checkout_notify_t why,
	const char *path,
	const git_diff_file *baseline,
	const git_diff_file *target,
	const git_diff_file *workdir,
	void *payload)
{
	checkout_counts *ct = payload;

	GIT_UNUSED(baseline); GIT_UNUSED(target); GIT_UNUSED(workdir);

	if (why & GIT_CHECKOUT_NOTIFY_CONFLICT) {
		ct->n_conflicts++;

		if (ct->debug) {
			if (workdir) {
				if (baseline) {
					if (target)
						fprintf(stderr, "M %s (conflicts with M %s)\n",
							workdir->path, target->path);
					else
						fprintf(stderr, "M %s (conflicts with D %s)\n",
							workdir->path, baseline->path);
				} else {
					if (target)
						fprintf(stderr, "Existing %s (conflicts with A %s)\n",
							workdir->path, target->path);
					else
						fprintf(stderr, "How can an untracked file be a conflict (%s)\n", workdir->path);
				}
			} else {
				if (baseline) {
					if (target)
						fprintf(stderr, "D %s (conflicts with M %s)\n",
							target->path, baseline->path);
					else
						fprintf(stderr, "D %s (conflicts with D %s)\n",
							baseline->path, baseline->path);
				} else {
					if (target)
						fprintf(stderr, "How can an added file with no workdir be a conflict (%s)\n", target->path);
					else
						fprintf(stderr, "How can a nonexistent file be a conflict (%s)\n", path);
				}
			}
		}
	}

	if (why & GIT_CHECKOUT_NOTIFY_DIRTY) {
		ct->n_dirty++;

		if (ct->debug) {
			if (workdir)
				fprintf(stderr, "M %s\n", workdir->path);
			else
				fprintf(stderr, "D %s\n", baseline->path);
		}
	}

	if (why & GIT_CHECKOUT_NOTIFY_UPDATED) {
		ct->n_updates++;

		if (ct->debug) {
			if (baseline) {
				if (target)
					fprintf(stderr, "update: M %s\n", path);
				else
					fprintf(stderr, "update: D %s\n", path);
			} else {
				if (target)
					fprintf(stderr, "update: A %s\n", path);
				else
					fprintf(stderr, "update: this makes no sense %s\n", path);
			}
		}
	}

	if (why & GIT_CHECKOUT_NOTIFY_UNTRACKED) {
		ct->n_untracked++;

		if (ct->debug)
			fprintf(stderr, "? %s\n", path);
	}

	if (why & GIT_CHECKOUT_NOTIFY_IGNORED) {
		ct->n_ignored++;

		if (ct->debug)
			fprintf(stderr, "I %s\n", path);
	}

	return 0;
}

void tick_index(git_index *index)
{
	struct timespec ts;
	struct p_timeval times[2];

	cl_assert(index->on_disk);
	cl_assert(git_index_path(index));

	cl_git_pass(git_index_read(index, true));
	ts = index->stamp.mtime;

	times[0].tv_sec = ts.tv_sec;
	times[0].tv_usec = ts.tv_nsec / 1000;
	times[1].tv_sec = ts.tv_sec + 5;
	times[1].tv_usec = ts.tv_nsec / 1000;

	cl_git_pass(p_utimes(git_index_path(index), times));
	cl_git_pass(git_index_read(index, true));
}

{'repo_name': 'DGA-MI-SSI/YaCo', 'stars': '271', 'repo_language': 'C++', 'file_name': 'director_detect_runme.pl', 'mime_type': 'text/plain', 'hash': -5989328722294637724, 'source_dataset': 'data'}


/**
 * @file
 * @brief String hunk management
 */

/*
Copyright (C) 2002-2020 UFO: Alien Invasion.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/

#include "stringhunk.h"
#include "../common/common.h"

/**
 * @return @c true if the add was successful, @c false if there was an overflow and the string was cut.
 */
bool STRHUNK_Add (stringHunk_t* hunk, const char* string)
{
	const ptrdiff_t filled = hunk->pos - hunk->hunk;
	const size_t remaining = hunk->size - filled;
	const size_t strLength = strlen(string);
	const bool overflow = remaining <= strLength;

	if (remaining < 1)
		return false;

	/* add delimiter char. */
	if (hunk->pos != hunk->hunk) {
		if (remaining == 1)
			return false;
		*hunk->pos++ = '\xFF';
	}

	Q_strncpyz(hunk->pos, string, remaining - 1);
	hunk->pos += overflow ? remaining - 1: strLength + 1;
	hunk->entries++;
	return !overflow;
}

void STRHUNK_Reset (stringHunk_t* hunk)
{
	hunk->pos = hunk->hunk;
	hunk->entries = 0;
	hunk->hunk[0] = '\0';
}

void STRHUNK_Visit (stringHunk_t* hunk, stringHunkVisitor_t visitor)
{
	const char* string = hunk->hunk;

	if (hunk->entries == 0)
		return;

	for (;;) {
		visitor(string);
		string += strlen(string) + 1;
		if (*string != '\xFF')
			break;
		string++;
	}
}

int STRHUNK_Size (const stringHunk_t* hunk)
{
	return hunk->entries;
}

size_t STRHUNK_GetFreeSpace (const stringHunk_t* hunk)
{
	return hunk->size - (ptrdiff_t)(hunk->pos - hunk->hunk);
}

stringHunk_t* STRHUNK_Create (size_t size)
{
	stringHunk_t* strHunk = Mem_AllocType(stringHunk_t);
	strHunk->size = size;
	strHunk->hunk = Mem_AllocTypeN(char, size);
	strHunk->pos = strHunk->hunk;
	return strHunk;
}

void STRHUNK_Delete (stringHunk_t** hunk)
{
	Mem_Free(*hunk);
	*hunk = nullptr;
}

{'repo_name': 'ufoai/ufoai', 'stars': '116', 'repo_language': 'C', 'file_name': 'ufo.6', 'mime_type': 'text/troff', 'hash': -5604924614861952733, 'source_dataset': 'data'}


/*
 * Copyright 1998-2008 VIA Technologies, Inc. All Rights Reserved.
 * Copyright 2001-2008 S3 Graphics, Inc. All Rights Reserved.

 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation;
 * either version 2, or (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTIES OR REPRESENTATIONS; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.See the GNU General Public License
 * for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc.,
 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
#include "global.h"

static int hw_bitblt_1(void __iomem *engine, u8 op, u32 width, u32 height,
	u8 dst_bpp, u32 dst_addr, u32 dst_pitch, u32 dst_x, u32 dst_y,
	u32 *src_mem, u32 src_addr, u32 src_pitch, u32 src_x, u32 src_y,
	u32 fg_color, u32 bg_color, u8 fill_rop)
{
	u32 ge_cmd = 0, tmp, i;

	if (!op || op > 3) {
		printk(KERN_WARNING "hw_bitblt_1: Invalid operation: %d\n", op);
		return -EINVAL;
	}

	if (op != VIA_BITBLT_FILL && !src_mem && src_addr == dst_addr) {
		if (src_x < dst_x) {
			ge_cmd |= 0x00008000;
			src_x += width - 1;
			dst_x += width - 1;
		}
		if (src_y < dst_y) {
			ge_cmd |= 0x00004000;
			src_y += height - 1;
			dst_y += height - 1;
		}
	}

	if (op == VIA_BITBLT_FILL) {
		switch (fill_rop) {
		case 0x00: /* blackness */
		case 0x5A: /* pattern inversion */
		case 0xF0: /* pattern copy */
		case 0xFF: /* whiteness */
			break;
		default:
			printk(KERN_WARNING "hw_bitblt_1: Invalid fill rop: "
				"%u\n", fill_rop);
			return -EINVAL;
		}
	}

	switch (dst_bpp) {
	case 8:
		tmp = 0x00000000;
		break;
	case 16:
		tmp = 0x00000100;
		break;
	case 32:
		tmp = 0x00000300;
		break;
	default:
		printk(KERN_WARNING "hw_bitblt_1: Unsupported bpp %d\n",
			dst_bpp);
		return -EINVAL;
	}
	writel(tmp, engine + 0x04);

	if (op != VIA_BITBLT_FILL) {
		if (src_x & (op == VIA_BITBLT_MONO ? 0xFFFF8000 : 0xFFFFF000)
			|| src_y & 0xFFFFF000) {
			printk(KERN_WARNING "hw_bitblt_1: Unsupported source "
				"x/y %d %d\n", src_x, src_y);
			return -EINVAL;
		}
		tmp = src_x | (src_y << 16);
		writel(tmp, engine + 0x08);
	}

	if (dst_x & 0xFFFFF000 || dst_y & 0xFFFFF000) {
		printk(KERN_WARNING "hw_bitblt_1: Unsupported destination x/y "
			"%d %d\n", dst_x, dst_y);
		return -EINVAL;
	}
	tmp = dst_x | (dst_y << 16);
	writel(tmp, engine + 0x0C);

	if ((width - 1) & 0xFFFFF000 || (height - 1) & 0xFFFFF000) {
		printk(KERN_WARNING "hw_bitblt_1: Unsupported width/height "
			"%d %d\n", width, height);
		return -EINVAL;
	}
	tmp = (width - 1) | ((height - 1) << 16);
	writel(tmp, engine + 0x10);

	if (op != VIA_BITBLT_COLOR)
		writel(fg_color, engine + 0x18);

	if (op == VIA_BITBLT_MONO)
		writel(bg_color, engine + 0x1C);

	if (op != VIA_BITBLT_FILL) {
		tmp = src_mem ? 0 : src_addr;
		if (dst_addr & 0xE0000007) {
			printk(KERN_WARNING "hw_bitblt_1: Unsupported source "
				"address %X\n", tmp);
			return -EINVAL;
		}
		tmp >>= 3;
		writel(tmp, engine + 0x30);
	}

	if (dst_addr & 0xE0000007) {
		printk(KERN_WARNING "hw_bitblt_1: Unsupported destination "
			"address %X\n", dst_addr);
		return -EINVAL;
	}
	tmp = dst_addr >> 3;
	writel(tmp, engine + 0x34);

	if (op == VIA_BITBLT_FILL)
		tmp = 0;
	else
		tmp = src_pitch;
	if (tmp & 0xFFFFC007 || dst_pitch & 0xFFFFC007) {
		printk(KERN_WARNING "hw_bitblt_1: Unsupported pitch %X %X\n",
			tmp, dst_pitch);
		return -EINVAL;
	}
	tmp = VIA_PITCH_ENABLE | (tmp >> 3) | (dst_pitch << (16 - 3));
	writel(tmp, engine + 0x38);

	if (op == VIA_BITBLT_FILL)
		ge_cmd |= fill_rop << 24 | 0x00002000 | 0x00000001;
	else {
		ge_cmd |= 0xCC000000; /* ROP=SRCCOPY */
		if (src_mem)
			ge_cmd |= 0x00000040;
		if (op == VIA_BITBLT_MONO)
			ge_cmd |= 0x00000002 | 0x00000100 | 0x00020000;
		else
			ge_cmd |= 0x00000001;
	}
	writel(ge_cmd, engine);

	if (op == VIA_BITBLT_FILL || !src_mem)
		return 0;

	tmp = (width * height * (op == VIA_BITBLT_MONO ? 1 : (dst_bpp >> 3)) +
		3) >> 2;

	for (i = 0; i < tmp; i++)
		writel(src_mem[i], engine + VIA_MMIO_BLTBASE);

	return 0;
}

static int hw_bitblt_2(void __iomem *engine, u8 op, u32 width, u32 height,
	u8 dst_bpp, u32 dst_addr, u32 dst_pitch, u32 dst_x, u32 dst_y,
	u32 *src_mem, u32 src_addr, u32 src_pitch, u32 src_x, u32 src_y,
	u32 fg_color, u32 bg_color, u8 fill_rop)
{
	u32 ge_cmd = 0, tmp, i;

	if (!op || op > 3) {
		printk(KERN_WARNING "hw_bitblt_2: Invalid operation: %d\n", op);
		return -EINVAL;
	}

	if (op != VIA_BITBLT_FILL && !src_mem && src_addr == dst_addr) {
		if (src_x < dst_x) {
			ge_cmd |= 0x00008000;
			src_x += width - 1;
			dst_x += width - 1;
		}
		if (src_y < dst_y) {
			ge_cmd |= 0x00004000;
			src_y += height - 1;
			dst_y += height - 1;
		}
	}

	if (op == VIA_BITBLT_FILL) {
		switch (fill_rop) {
		case 0x00: /* blackness */
		case 0x5A: /* pattern inversion */
		case 0xF0: /* pattern copy */
		case 0xFF: /* whiteness */
			break;
		default:
			printk(KERN_WARNING "hw_bitblt_2: Invalid fill rop: "
				"%u\n", fill_rop);
			return -EINVAL;
		}
	}

	switch (dst_bpp) {
	case 8:
		tmp = 0x00000000;
		break;
	case 16:
		tmp = 0x00000100;
		break;
	case 32:
		tmp = 0x00000300;
		break;
	default:
		printk(KERN_WARNING "hw_bitblt_2: Unsupported bpp %d\n",
			dst_bpp);
		return -EINVAL;
	}
	writel(tmp, engine + 0x04);

	if (op == VIA_BITBLT_FILL)
		tmp = 0;
	else
		tmp = src_pitch;
	if (tmp & 0xFFFFC007 || dst_pitch & 0xFFFFC007) {
		printk(KERN_WARNING "hw_bitblt_2: Unsupported pitch %X %X\n",
			tmp, dst_pitch);
		return -EINVAL;
	}
	tmp = (tmp >> 3) | (dst_pitch << (16 - 3));
	writel(tmp, engine + 0x08);

	if ((width - 1) & 0xFFFFF000 || (height - 1) & 0xFFFFF000) {
		printk(KERN_WARNING "hw_bitblt_2: Unsupported width/height "
			"%d %d\n", width, height);
		return -EINVAL;
	}
	tmp = (width - 1) | ((height - 1) << 16);
	writel(tmp, engine + 0x0C);

	if (dst_x & 0xFFFFF000 || dst_y & 0xFFFFF000) {
		printk(KERN_WARNING "hw_bitblt_2: Unsupported destination x/y "
			"%d %d\n", dst_x, dst_y);
		return -EINVAL;
	}
	tmp = dst_x | (dst_y << 16);
	writel(tmp, engine + 0x10);

	if (dst_addr & 0xE0000007) {
		printk(KERN_WARNING "hw_bitblt_2: Unsupported destination "
			"address %X\n", dst_addr);
		return -EINVAL;
	}
	tmp = dst_addr >> 3;
	writel(tmp, engine + 0x14);

	if (op != VIA_BITBLT_FILL) {
		if (src_x & (op == VIA_BITBLT_MONO ? 0xFFFF8000 : 0xFFFFF000)
			|| src_y & 0xFFFFF000) {
			printk(KERN_WARNING "hw_bitblt_2: Unsupported source "
				"x/y %d %d\n", src_x, src_y);
			return -EINVAL;
		}
		tmp = src_x | (src_y << 16);
		writel(tmp, engine + 0x18);

		tmp = src_mem ? 0 : src_addr;
		if (dst_addr & 0xE0000007) {
			printk(KERN_WARNING "hw_bitblt_2: Unsupported source "
				"address %X\n", tmp);
			return -EINVAL;
		}
		tmp >>= 3;
		writel(tmp, engine + 0x1C);
	}

	if (op != VIA_BITBLT_COLOR)
		writel(fg_color, engine + 0x4C);

	if (op == VIA_BITBLT_MONO)
		writel(bg_color, engine + 0x50);

	if (op == VIA_BITBLT_FILL)
		ge_cmd |= fill_rop << 24 | 0x00002000 | 0x00000001;
	else {
		ge_cmd |= 0xCC000000; /* ROP=SRCCOPY */
		if (src_mem)
			ge_cmd |= 0x00000040;
		if (op == VIA_BITBLT_MONO)
			ge_cmd |= 0x00000002 | 0x00000100 | 0x00020000;
		else
			ge_cmd |= 0x00000001;
	}
	writel(ge_cmd, engine);

	if (op == VIA_BITBLT_FILL || !src_mem)
		return 0;

	tmp = (width * height * (op == VIA_BITBLT_MONO ? 1 : (dst_bpp >> 3)) +
		3) >> 2;

	for (i = 0; i < tmp; i++)
		writel(src_mem[i], engine + VIA_MMIO_BLTBASE);

	return 0;
}

int viafb_init_engine(struct fb_info *info)
{
	struct viafb_par *viapar = info->par;
	void __iomem *engine;
	u32 vq_start_addr, vq_end_addr, vq_start_low, vq_end_low, vq_high,
		vq_len, chip_name = viapar->shared->chip_info.gfx_chip_name;

	engine = ioremap_nocache(info->fix.mmio_start, info->fix.mmio_len);
	viapar->shared->engine_mmio = engine;
	if (!engine) {
		printk(KERN_WARNING "viafb_init_accel: ioremap failed, "
			"hardware acceleration disabled\n");
		return -ENOMEM;
	}

	switch (chip_name) {
	case UNICHROME_CLE266:
	case UNICHROME_K400:
	case UNICHROME_K800:
	case UNICHROME_PM800:
	case UNICHROME_CN700:
	case UNICHROME_CX700:
	case UNICHROME_CN750:
	case UNICHROME_K8M890:
	case UNICHROME_P4M890:
	case UNICHROME_P4M900:
		viapar->shared->hw_bitblt = hw_bitblt_1;
		break;
	case UNICHROME_VX800:
	case UNICHROME_VX855:
		viapar->shared->hw_bitblt = hw_bitblt_2;
		break;
	default:
		viapar->shared->hw_bitblt = NULL;
	}

	viapar->fbmem_free -= CURSOR_SIZE;
	viapar->shared->cursor_vram_addr = viapar->fbmem_free;
	viapar->fbmem_used += CURSOR_SIZE;

	viapar->fbmem_free -= VQ_SIZE;
	viapar->shared->vq_vram_addr = viapar->fbmem_free;
	viapar->fbmem_used += VQ_SIZE;

	/* Init 2D engine reg to reset 2D engine */
	writel(0x0, engine + VIA_REG_KEYCONTROL);

	/* Init AGP and VQ regs */
	switch (chip_name) {
	case UNICHROME_K8M890:
	case UNICHROME_P4M900:
		writel(0x00100000, engine + VIA_REG_CR_TRANSET);
		writel(0x680A0000, engine + VIA_REG_CR_TRANSPACE);
		writel(0x02000000, engine + VIA_REG_CR_TRANSPACE);
		break;

	default:
		writel(0x00100000, engine + VIA_REG_TRANSET);
		writel(0x00000000, engine + VIA_REG_TRANSPACE);
		writel(0x00333004, engine + VIA_REG_TRANSPACE);
		writel(0x60000000, engine + VIA_REG_TRANSPACE);
		writel(0x61000000, engine + VIA_REG_TRANSPACE);
		writel(0x62000000, engine + VIA_REG_TRANSPACE);
		writel(0x63000000, engine + VIA_REG_TRANSPACE);
		writel(0x64000000, engine + VIA_REG_TRANSPACE);
		writel(0x7D000000, engine + VIA_REG_TRANSPACE);

		writel(0xFE020000, engine + VIA_REG_TRANSET);
		writel(0x00000000, engine + VIA_REG_TRANSPACE);
		break;
	}

	/* Enable VQ */
	vq_start_addr = viapar->shared->vq_vram_addr;
	vq_end_addr = viapar->shared->vq_vram_addr + VQ_SIZE - 1;

	vq_start_low = 0x50000000 | (vq_start_addr & 0xFFFFFF);
	vq_end_low = 0x51000000 | (vq_end_addr & 0xFFFFFF);
	vq_high = 0x52000000 | ((vq_start_addr & 0xFF000000) >> 24) |
		((vq_end_addr & 0xFF000000) >> 16);
	vq_len = 0x53000000 | (VQ_SIZE >> 3);

	switch (chip_name) {
	case UNICHROME_K8M890:
	case UNICHROME_P4M900:
		vq_start_low |= 0x20000000;
		vq_end_low |= 0x20000000;
		vq_high |= 0x20000000;
		vq_len |= 0x20000000;

		writel(0x00100000, engine + VIA_REG_CR_TRANSET);
		writel(vq_high, engine + VIA_REG_CR_TRANSPACE);
		writel(vq_start_low, engine + VIA_REG_CR_TRANSPACE);
		writel(vq_end_low, engine + VIA_REG_CR_TRANSPACE);
		writel(vq_len, engine + VIA_REG_CR_TRANSPACE);
		writel(0x74301001, engine + VIA_REG_CR_TRANSPACE);
		writel(0x00000000, engine + VIA_REG_CR_TRANSPACE);
		break;
	default:
		writel(0x00FE0000, engine + VIA_REG_TRANSET);
		writel(0x080003FE, engine + VIA_REG_TRANSPACE);
		writel(0x0A00027C, engine + VIA_REG_TRANSPACE);
		writel(0x0B000260, engine + VIA_REG_TRANSPACE);
		writel(0x0C000274, engine + VIA_REG_TRANSPACE);
		writel(0x0D000264, engine + VIA_REG_TRANSPACE);
		writel(0x0E000000, engine + VIA_REG_TRANSPACE);
		writel(0x0F000020, engine + VIA_REG_TRANSPACE);
		writel(0x1000027E, engine + VIA_REG_TRANSPACE);
		writel(0x110002FE, engine + VIA_REG_TRANSPACE);
		writel(0x200F0060, engine + VIA_REG_TRANSPACE);

		writel(0x00000006, engine + VIA_REG_TRANSPACE);
		writel(0x40008C0F, engine + VIA_REG_TRANSPACE);
		writel(0x44000000, engine + VIA_REG_TRANSPACE);
		writel(0x45080C04, engine + VIA_REG_TRANSPACE);
		writel(0x46800408, engine + VIA_REG_TRANSPACE);

		writel(vq_high, engine + VIA_REG_TRANSPACE);
		writel(vq_start_low, engine + VIA_REG_TRANSPACE);
		writel(vq_end_low, engine + VIA_REG_TRANSPACE);
		writel(vq_len, engine + VIA_REG_TRANSPACE);
		break;
	}

	/* Set Cursor Image Base Address */
	writel(viapar->shared->cursor_vram_addr, engine + VIA_REG_CURSOR_MODE);
	writel(0x0, engine + VIA_REG_CURSOR_POS);
	writel(0x0, engine + VIA_REG_CURSOR_ORG);
	writel(0x0, engine + VIA_REG_CURSOR_BG);
	writel(0x0, engine + VIA_REG_CURSOR_FG);
	return 0;
}

void viafb_show_hw_cursor(struct fb_info *info, int Status)
{
	struct viafb_par *viapar = info->par;
	u32 temp, iga_path = viapar->iga_path;

	temp = readl(viapar->shared->engine_mmio + VIA_REG_CURSOR_MODE);
	switch (Status) {
	case HW_Cursor_ON:
		temp |= 0x1;
		break;
	case HW_Cursor_OFF:
		temp &= 0xFFFFFFFE;
		break;
	}
	switch (iga_path) {
	case IGA2:
		temp |= 0x80000000;
		break;
	case IGA1:
	default:
		temp &= 0x7FFFFFFF;
	}
	writel(temp, viapar->shared->engine_mmio + VIA_REG_CURSOR_MODE);
}

void viafb_wait_engine_idle(struct fb_info *info)
{
	struct viafb_par *viapar = info->par;
	int loop = 0;

	while (!(readl(viapar->shared->engine_mmio + VIA_REG_STATUS) &
			VIA_VR_QUEUE_BUSY) && (loop < MAXLOOP)) {
		loop++;
		cpu_relax();
	}

	while ((readl(viapar->shared->engine_mmio + VIA_REG_STATUS) &
		    (VIA_CMD_RGTR_BUSY | VIA_2D_ENG_BUSY | VIA_3D_ENG_BUSY)) &&
		    (loop < MAXLOOP)) {
		loop++;
		cpu_relax();
	}

	if (loop >= MAXLOOP)
		printk(KERN_ERR "viafb_wait_engine_idle: not syncing\n");
}

{'repo_name': 'EmcraftSystems/linux-emcraft', 'stars': '228', 'repo_language': 'C', 'file_name': 'io.c', 'mime_type': 'text/x-c', 'hash': -83038611759408763, 'source_dataset': 'data'}


package io.quarkus.hibernate.orm.panache.kotlin.deployment.test;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusUnitTest;

public class NoConfigTest {

    @RegisterExtension
    static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
            () -> ShrinkWrap.create(JavaArchive.class));

    @Test
    public void testNoConfig() {
        // we should be able to start the application, even with no configuration at all
    }
}

{'repo_name': 'quarkusio/quarkus', 'stars': '5298', 'repo_language': 'Java', 'file_name': 'ProdModeTestResults.java', 'mime_type': 'text/x-java', 'hash': 2973605217279179311, 'source_dataset': 'data'}


/*==============================================================================

  Program: 3D Slicer

  Copyright (c) Kitware Inc.

  See COPYRIGHT.txt
  or http://www.slicer.org/copyright/copyright.txt for details.

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

  This file was originally developed by Csaba Pinter, PerkLab, Queen's University
  and was supported through the Applied Cancer Research Unit program of Cancer Care
  Ontario with funds provided by the Ontario Ministry of Health and Long-Term Care

==============================================================================*/

// Qt includes
#include <QStringList>
#include <QItemSelectionModel>

// qMRML includes
#include "qMRMLNodeAttributeTableView.h"
#include "ui_qMRMLNodeAttributeTableView.h"

// MRML includes
#include <vtkMRMLNode.h>

// STL includes
#include <set>

// --------------------------------------------------------------------------
class qMRMLNodeAttributeTableViewPrivate: public Ui_qMRMLNodeAttributeTableView
{
  Q_DECLARE_PUBLIC(qMRMLNodeAttributeTableView);
protected:
  qMRMLNodeAttributeTableView* const q_ptr;
public:
  qMRMLNodeAttributeTableViewPrivate(qMRMLNodeAttributeTableView& object);
  void init();

  /// Sets table message and takes care of the visibility of the label
  void setMessage(const QString& message)
  {
    this->AttributeTableMessageLabel->setVisible(!message.isEmpty());
    this->AttributeTableMessageLabel->setText(message);
  };

public:
  /// MRML node to inspect
  vtkMRMLNode* InspectedNode;
};

// --------------------------------------------------------------------------
qMRMLNodeAttributeTableViewPrivate::qMRMLNodeAttributeTableViewPrivate(qMRMLNodeAttributeTableView& object)
  : q_ptr(&object)
{
  this->InspectedNode = nullptr;
}

// --------------------------------------------------------------------------
void qMRMLNodeAttributeTableViewPrivate::init()
{
  Q_Q(qMRMLNodeAttributeTableView);
  this->setupUi(q);

  QObject::connect(this->NodeAttributesTable, SIGNAL(itemChanged(QTableWidgetItem*)),
          q, SLOT(onAttributeChanged(QTableWidgetItem*)));

  this->setMessage(QString());
}

// --------------------------------------------------------------------------
// qMRMLNodeAttributeTableView methods

// --------------------------------------------------------------------------
qMRMLNodeAttributeTableView::qMRMLNodeAttributeTableView(QWidget* _parent)
  : QWidget(_parent)
  , d_ptr(new qMRMLNodeAttributeTableViewPrivate(*this))
{
  Q_D(qMRMLNodeAttributeTableView);
  d->init();
  this->populateAttributeTable();
}

// --------------------------------------------------------------------------
qMRMLNodeAttributeTableView::~qMRMLNodeAttributeTableView() = default;

//-----------------------------------------------------------------------------
void qMRMLNodeAttributeTableView::setInspectedNode(vtkMRMLNode* node)
{
  Q_D(qMRMLNodeAttributeTableView);

  qvtkReconnect( d->InspectedNode, node, vtkCommand::ModifiedEvent,
                this, SLOT( populateAttributeTable() ) );

  d->InspectedNode = node;
  this->populateAttributeTable();
}

//-----------------------------------------------------------------------------
vtkMRMLNode* qMRMLNodeAttributeTableView::inspectedNode()
{
  Q_D(qMRMLNodeAttributeTableView);

  return d->InspectedNode;
}

//-----------------------------------------------------------------------------
void qMRMLNodeAttributeTableView::populateAttributeTable()
{
  Q_D(qMRMLNodeAttributeTableView);

  d->setMessage(QString());

  // Block signals so that onAttributeChanged function is not called when populating
  bool wasBlocked = d->NodeAttributesTable->blockSignals(true);

  d->NodeAttributesTable->clearContents();

  QStringList headerLabels;
  headerLabels << "Attribute name" << "Attribute value";
  d->NodeAttributesTable->setHorizontalHeaderLabels(headerLabels);
  d->NodeAttributesTable->setColumnWidth(0, d->NodeAttributesTable->width() / 2 - 10);
  d->NodeAttributesTable->setColumnWidth(1, d->NodeAttributesTable->width() / 2 - 10);

  if (!d->InspectedNode)
    {
    d->setMessage(tr("No node is selected"));
    d->NodeAttributesTable->setRowCount(0);
    d->NodeAttributesTable->blockSignals(wasBlocked);
    return;
    }

  std::vector< std::string > attributeNames = d->InspectedNode->GetAttributeNames();
  if (attributeNames.size() == 0)
    {
    d->setMessage(tr("Selected node has no attributes"));
    d->NodeAttributesTable->setRowCount(0);
    }
  else
    {
    d->NodeAttributesTable->setRowCount(attributeNames.size());

    int row = 0;
    for (std::vector< std::string >::iterator iter = attributeNames.begin();
        iter != attributeNames.end(); ++iter, ++row)
      {
      // attribute name
      QString attributeName = QString(iter->c_str());
      QTableWidgetItem* attributeNameItem = new QTableWidgetItem(attributeName);
      // save the attribute name as user data so that if the item is renamed
      // we know which attribute name to change
      attributeNameItem->setData(Qt::UserRole, attributeName);
      d->NodeAttributesTable->setItem( row, 0, attributeNameItem);

      // attribute value
      d->NodeAttributesTable->setItem( row, 1, new QTableWidgetItem(
        QString(d->InspectedNode->GetAttribute(iter->c_str())) ) );
      }
    }

  // Unblock signals
  d->NodeAttributesTable->blockSignals(wasBlocked);
}

//-----------------------------------------------------------------------------
void qMRMLNodeAttributeTableView::onAttributeChanged(QTableWidgetItem* changedItem)
{
  Q_D(qMRMLNodeAttributeTableView);

  d->setMessage(QString());

  if (!changedItem || !d->InspectedNode)
    {
    return;
    }

  if (changedItem->column() == 0)
    {
    // Attribute name has been changed
    QTableWidgetItem* valueItem = d->NodeAttributesTable->item( changedItem->row(), 1 );
    QString valueText;
    if (valueItem)
      {
      valueText = valueItem->text();
      }

    QString attributeNameBeforeEditing = changedItem->data(Qt::UserRole).toString();
    if (d->InspectedNode->GetAttribute(changedItem->text().toUtf8().constData()))
      {
      // Don't set if there is another attribute with the same name (would overwrite it),
      // revert to the original value.
      d->setMessage(tr("There is already an attribute with the same name"));
      bool wasBlocked = d->NodeAttributesTable->blockSignals(true);
      changedItem->setText(attributeNameBeforeEditing);
      d->NodeAttributesTable->blockSignals(wasBlocked);
      }
    else
      {
      int wasModifying = d->InspectedNode->StartModify();

      d->InspectedNode->RemoveAttribute(attributeNameBeforeEditing.toUtf8().constData());
      d->InspectedNode->SetAttribute(
        changedItem->text().toUtf8().constData(), valueText.toUtf8().constData());

      // Save the new attribute name
      bool wasBlocked = d->NodeAttributesTable->blockSignals(true);
      changedItem->setData(Qt::UserRole, changedItem->text());
      d->NodeAttributesTable->blockSignals(wasBlocked);

      d->InspectedNode->EndModify(wasModifying);
      }
    }
  else if (changedItem->column() == 1)
    {
    // Attribute value has been changed
    QTableWidgetItem* nameItem = d->NodeAttributesTable->item( changedItem->row(), 0 );
    QString nameText;
    if (nameItem)
      {
      nameText = nameItem->text();
      }
    d->InspectedNode->SetAttribute( nameText.toUtf8().constData(), changedItem->text().toUtf8().constData() );
    }
}

//-----------------------------------------------------------------------------
QString qMRMLNodeAttributeTableView::generateNewAttributeName() const
{
  Q_D(const qMRMLNodeAttributeTableView);

  QString newAttributeNameBase("NewAttributeName");
  QString newAttributeName(newAttributeNameBase);
  int i=0;
  while (d->InspectedNode->GetAttribute(newAttributeName.toUtf8().constData()))
    {
    newAttributeName = QString("%1%2").arg(newAttributeNameBase).arg(++i);
    }
  return newAttributeName;
}

//-----------------------------------------------------------------------------
void qMRMLNodeAttributeTableView::addAttribute()
{
  Q_D(qMRMLNodeAttributeTableView);

  if (!d->InspectedNode)
    {
    d->setMessage(tr("No node is selected"));
    return;
    }

  d->setMessage(QString());

  bool wasBlocked = d->NodeAttributesTable->blockSignals(true);
  int rowCountBefore = d->NodeAttributesTable->rowCount();
  d->NodeAttributesTable->insertRow( rowCountBefore );
  QString newAttributeName = this->generateNewAttributeName();
  QString newAttributeValue;
  QTableWidgetItem* attributeNameItem = new QTableWidgetItem(newAttributeName);
  // save the attribute name as user data so that if the item is renamed
  // we know which attribute name to change
  attributeNameItem->setData(Qt::UserRole, newAttributeName);
  d->NodeAttributesTable->setItem( rowCountBefore, 0, attributeNameItem);
  d->NodeAttributesTable->setItem( rowCountBefore, 1, new QTableWidgetItem(newAttributeValue) );
  d->NodeAttributesTable->blockSignals(wasBlocked);

  d->InspectedNode->SetAttribute(newAttributeName.toUtf8().constData(), newAttributeValue.toUtf8().constData());
}

//-----------------------------------------------------------------------------
void qMRMLNodeAttributeTableView::removeSelectedAttributes()
{
  Q_D(qMRMLNodeAttributeTableView);

  if (!d->InspectedNode)
    {
    d->setMessage(tr("No node is selected"));
    return;
    }

  d->setMessage(QString());

  // Extract selected row indices out of the selected table widget items list
  // (there may be more items selected in a row)
  QList<QTableWidgetItem*> selectedItems = d->NodeAttributesTable->selectedItems();
  QSet<int> affectedRowNumbers;
  foreach (QTableWidgetItem* item, selectedItems)
    {
    affectedRowNumbers.insert(item->row());
    }

  int wasModifying = d->InspectedNode->StartModify();

  for (QSet<int>::iterator it = affectedRowNumbers.begin(); it != affectedRowNumbers.end(); ++it)
    {
    QString attributeNameToDelete( d->NodeAttributesTable->item((*it), 0)->text() );
    d->InspectedNode->RemoveAttribute( attributeNameToDelete.toUtf8().constData() );
    }

  d->InspectedNode->Modified();
  d->InspectedNode->EndModify(wasModifying);
}

//-----------------------------------------------------------------------------
int qMRMLNodeAttributeTableView::attributeCount() const
{
  Q_D(const qMRMLNodeAttributeTableView);

  return d->NodeAttributesTable->rowCount();
}

//-----------------------------------------------------------------------------
QStringList qMRMLNodeAttributeTableView::attributes() const
{
  Q_D(const qMRMLNodeAttributeTableView);

  QStringList attributeList;
  for (int i=0; i<d->NodeAttributesTable->rowCount(); ++i)
    {
    attributeList << d->NodeAttributesTable->item(i,0)->text();
    }

  return attributeList;
}

//-----------------------------------------------------------------------------
QTableWidgetItem* qMRMLNodeAttributeTableView::findAttributeNameItem(const QString& attributeName) const
{
  Q_D(const qMRMLNodeAttributeTableView);

  QTableWidgetItem* item = nullptr;
  int numberOfAttributesFound = 0;
  QList<QTableWidgetItem*> itemList = d->NodeAttributesTable->findItems(attributeName, Qt::MatchFixedString);
  foreach(QTableWidgetItem* currentItem, itemList)
    {
    // Check if found item is in the name column (there may be values containing the same text)
    if (currentItem != nullptr && currentItem->column() == 0)
      {
        numberOfAttributesFound++;
        item = currentItem;
      }
    }

  return (numberOfAttributesFound == 1) ? item : nullptr;
}

//-----------------------------------------------------------------------------
QString qMRMLNodeAttributeTableView::attributeValue(const QString& attributeName) const
{
  Q_D(const qMRMLNodeAttributeTableView);

  QTableWidgetItem* item = this->findAttributeNameItem(attributeName);
  return item ? d->NodeAttributesTable->item(item->row(), item->column()+1)->text() : QString();
}

//-----------------------------------------------------------------------------
void qMRMLNodeAttributeTableView::setAttribute(const QString& attributeName, const QString& attributeValue)
{
  if (attributeName.isNull())
    {
    return;
    }

  Q_D(qMRMLNodeAttributeTableView);

  QTableWidgetItem* nameItem = this->findAttributeNameItem(attributeName);
  if (!nameItem)
    {
    if (attributeName.isEmpty() || attributeValue.isNull())
      {
      return;
      }
    int rowCountBefore = d->NodeAttributesTable->rowCount();
    d->NodeAttributesTable->insertRow( rowCountBefore );
    d->NodeAttributesTable->setItem( rowCountBefore, 0, new QTableWidgetItem(attributeName) );
    d->NodeAttributesTable->setItem( rowCountBefore, 1, new QTableWidgetItem(attributeValue) );
    return;
    }
  else if (attributeValue.isNull())
    {
    d->InspectedNode->RemoveAttribute(attributeName.toUtf8().constData());
    return;
    }

  QTableWidgetItem* valueItem = d->NodeAttributesTable->item(nameItem->row(), nameItem->column()+1);

  if (valueItem)
    {
    valueItem->setText(attributeValue);
    }
}

//-----------------------------------------------------------------------------
void qMRMLNodeAttributeTableView::renameAttribute(const QString& oldName, const QString& newName)
{
  QTableWidgetItem* nameItem = this->findAttributeNameItem(oldName);
  if (nameItem)
    {
    nameItem->setText(newName);
    }
}

//-----------------------------------------------------------------------------
void qMRMLNodeAttributeTableView::selectItemRange(const int topRow, const int leftColumn, const int bottomRow, const int rightColumn)
{
  Q_D(qMRMLNodeAttributeTableView);

  QTableWidgetSelectionRange range(topRow, leftColumn, bottomRow, rightColumn);
  d->NodeAttributesTable->setRangeSelected(range, true);
}

//-----------------------------------------------------------------------------
QItemSelectionModel* qMRMLNodeAttributeTableView::selectionModel()
{
  Q_D(qMRMLNodeAttributeTableView);

  return d->NodeAttributesTable->selectionModel();
}

{'repo_name': 'Slicer/Slicer', 'stars': '115', 'repo_language': 'C++', 'file_name': 'itkFactoryRegistrationConfigure.h.in', 'mime_type': 'text/x-c', 'hash': 8089341669090305396, 'source_dataset': 'data'}


//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft Corporation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
this.WScript.LoadScriptFile("..\\UnitTestFramework\\SimdJsHelpers.js");
function asmModule(stdlib, imports) {
    "use asm";
    var ui16 = stdlib.SIMD.Uint8x16;
    var ui16check = ui16.check;
    var ui16add = ui16.add;
    var ui16sub = ui16.sub;

    var globImportui16 = ui16check(imports.g1);

    var ui16g1 = ui16(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
    var ui16g2 = ui16(256, 255, 128, 127, 0, 0, 1000, 1000, 5, 15, 3, 399, 299, 21, 45, 22);

    var loopCOUNT = 3;

    var i16 = stdlib.SIMD.Int8x16;
    var i16check = i16.check;
    var i16fu16 = i16.fromUint8x16Bits;

    function testAddLocal()
    {
        var a = ui16(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
        var b = ui16(16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
        var result = ui16(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
        var loopIndex = 0;

        while ( (loopIndex|0) < (loopCOUNT|0)) {
            result = ui16add(a, b);
            loopIndex = (loopIndex + 1) | 0;
        }

        return i16check(i16fu16(result));
    }

    function testSubLocal()
    {
        var a = ui16(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
        var b = ui16(16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
        var result = ui16(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
        var loopIndex = 0;

        while ( (loopIndex|0) < (loopCOUNT|0)) {
            result = ui16sub(a, b);
            loopIndex = (loopIndex + 1) | 0;
        }

        return i16check(i16fu16(result));
    }

    function testAddGlobal()
    {
        var result = ui16(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
        var loopIndex = 0;

        while ( (loopIndex|0) < (loopCOUNT|0)) {
            result = ui16add(ui16g1, ui16g2);
            loopIndex = (loopIndex + 1) | 0;
        }

        return i16check(i16fu16(result));
    }

    function testSubGlobal()
    {
        var result = ui16(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
        var loopIndex = 0;

        while ( (loopIndex|0) < (loopCOUNT|0)) {
            result = ui16sub(ui16g1, ui16g2);
            loopIndex = (loopIndex + 1) | 0;
        }

        return i16check(i16fu16(result));
    }

    function testAddGlobalImport()
    {
        var a = ui16(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
        var result = ui16(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
        var loopIndex = 0;

        while ( (loopIndex|0) < (loopCOUNT|0)) {
            result = ui16add(globImportui16, a);
            loopIndex = (loopIndex + 1) | 0;
        }

        return i16check(i16fu16(result));
    }

    function testSubGlobalImport()
    {
        var a = ui16(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
        var result = ui16(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
        var loopIndex = 0;

        while ( (loopIndex|0) < (loopCOUNT|0)) {
            result = ui16sub(globImportui16, a);
            loopIndex = (loopIndex + 1) | 0;
        }

        return i16check(i16fu16(result));
    }

    return { testAddLocal: testAddLocal, testSubLocal: testSubLocal, testAddGlobal: testAddGlobal, testSubGlobal: testSubGlobal, testAddGlobalImport: testAddGlobalImport, testSubGlobalImport: testSubGlobalImport };
}

var m = asmModule(this, {g1:SIMD.Uint8x16(100, 65535, 1028, 102, 3883, 38, 52929, 1442, 52, 127, 127, 129, 129, 0, 88, 10234)});

var ret1 = SIMD.Uint8x16.fromInt8x16Bits(m.testAddLocal());
var ret2 = SIMD.Uint8x16.fromInt8x16Bits(m.testSubLocal());
var ret3 = SIMD.Uint8x16.fromInt8x16Bits(m.testAddGlobal());
var ret4 = SIMD.Uint8x16.fromInt8x16Bits(m.testSubGlobal());
var ret5 = SIMD.Uint8x16.fromInt8x16Bits(m.testAddGlobalImport());
var ret6 = SIMD.Uint8x16.fromInt8x16Bits(m.testSubGlobalImport());

equalSimd([17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17], ret1, SIMD.Uint8x16, "Func1");
equalSimd([241, 243, 245, 247, 249, 251, 253, 255, 1, 3, 5, 7, 9, 11, 13, 15], ret2, SIMD.Uint8x16, "Func2");
equalSimd([1, 1, 131, 131, 5, 6, 239, 240, 14, 25, 14, 155, 56, 35, 60, 38], ret3, SIMD.Uint8x16, "Func3");
equalSimd([1, 3, 131, 133, 5, 6, 31, 32, 4, 251, 8, 125, 226, 249, 226, 250], ret4, SIMD.Uint8x16, "Func4");
equalSimd([101, 1, 7, 106, 48, 44, 200, 170, 61, 137, 138, 141, 142, 14, 103, 10], ret5, SIMD.Uint8x16, "Func5");
equalSimd([99, 253, 1, 98, 38, 32, 186, 154, 43, 117, 116, 117, 116, 242, 73, 234], ret6, SIMD.Uint8x16, "Func6");
print("PASS");

{'repo_name': 'mozilla/spidernode', 'stars': '526', 'repo_language': 'JavaScript', 'file_name': 'os2emx.s', 'mime_type': 'text/x-asm', 'hash': -3569649170621686060, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
  <throwableRenderer class="org.apache.log4j.EnhancedThrowableRenderer" />
  <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
    <param name="threshold" value="DEBUG" />
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%-5p [%c{1}] - %m%n" />
    </layout>
  </appender>
  <!--
       <appender name="FILE" class="org.apache.log4j.RollingFileAppender">
          <param name="file" value="target/test.log"/>
          <layout class="org.apache.log4j.PatternLayout">
              <param name="ConversionPattern" value="%d %-5p [%c] - %m%n" />
          </layout>
      </appender>
   -->
  <!--
      <logger name="org.hibernate">
          <level value="info" />
      </logger>
  -->
  <logger name="gwt-log">
    <level value="OFF" />
  </logger>
  <root>
    <level value="ERROR" />
    <appender-ref ref="STDOUT" />
    <!--         <appender-ref ref="FILE" /> -->
  </root>
</log4j:configuration>

{'repo_name': 'zanata/zanata-platform', 'stars': '271', 'repo_language': 'Java', 'file_name': 'QueryParserTest.java', 'mime_type': 'text/x-java', 'hash': -8101701432101147523, 'source_dataset': 'data'}


#pragma warning disable xUnit1013 // Public method should be marked as test

using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Xunit;

namespace MonoMod.UnitTest {
    public class MultiHookUnitTestAutomaticRegistration {
        [Collection("RuntimeDetour")]
        public class OnIL {
            Hook h1;
            ILHook hIL;

            private bool h1Run;
            private bool hILRun;

            [SkipRemoteLinuxMonoFact]
            public void OnThenIL() {
                h1 = new Hook(
                    typeof(OnIL).GetMethod("DoNothing"),
                    new Action<Action<OnIL>, OnIL>((orig, self) => {
                        orig(self);
                        h1Run = true;
                    }),
                    new HookConfig {
                        ManualApply = false
                    }
                );
                hIL = new ILHook(
                    typeof(OnIL).GetMethod("DoNothing"),
                    il => {
                        ILCursor c = new ILCursor(il);
                        c.EmitDelegate<Action>(() => {
                            hILRun = true;
                        });
                    },
                    new ILHookConfig {
                        ManualApply = false
                    }
                );
                h1Run = false;
                hILRun = false;
                DoNothing();
                Assert.True(h1Run);
                Assert.True(hILRun);
                h1.Dispose();
                hIL.Dispose();
            }

            [SkipRemoteLinuxMonoFact]
            public void ILThenOn() {
                hIL = new ILHook(
                    typeof(OnIL).GetMethod("DoNothing"),
                    il => {
                        ILCursor c = new ILCursor(il);
                        c.EmitDelegate<Action>(() => {
                            hILRun = true;
                        });
                    },
                    new ILHookConfig {
                        ManualApply = false
                    }
                );
                h1 = new Hook(
                   typeof(OnIL).GetMethod("DoNothing"),
                   new Action<Action<OnIL>, OnIL>((orig, self) => {
                       orig(self);
                       h1Run = true;
                   }),
                   new HookConfig {
                       ManualApply = false
                   }
               );
                h1Run = false;
                hILRun = false;
                DoNothing();
                Assert.True(h1Run);
                Assert.True(hILRun);
                h1.Dispose();
                hIL.Dispose();
            }
            [MethodImpl(MethodImplOptions.NoInlining)]
            public void DoNothing() {
            }
        }
        [Collection("RuntimeDetour")]
        public class OnOnIL {
            Hook h1;
            Hook h2;
            ILHook hIL;

            private bool h1Run;
            private bool h2Run;
            private bool hILRun;

            [SkipRemoteLinuxMonoFact]
            public void OnThenOnThenIL() {
                h1 = new Hook(
                    typeof(OnOnIL).GetMethod("DoNothing"),
                    new Action<Action<OnOnIL>, OnOnIL>((orig, self) => {
                        orig(self);
                        h1Run = true;
                    }),
                    new HookConfig {
                        ManualApply = false
                    }
                );
                h2 = new Hook(
                    typeof(OnOnIL).GetMethod("DoNothing"),
                    new Action<Action<OnOnIL>, OnOnIL>((orig, self) => {
                        orig(self);
                        h2Run = true;
                    }),
                    new HookConfig {
                        ManualApply = false
                    }
                );
                hIL = new ILHook(
                    typeof(OnOnIL).GetMethod("DoNothing"),
                    il => {
                        ILCursor c = new ILCursor(il);
                        c.EmitDelegate<Action>(() => {
                            hILRun = true;
                        });
                    },
                    new ILHookConfig {
                        ManualApply = false
                    }
                );
                h1Run = false;
                h2Run = false;
                hILRun = false;
                DoNothing();
                Assert.True(h1Run);
                Assert.True(h2Run);
                Assert.True(hILRun);
                h1.Dispose();
                h2.Dispose();
                hIL.Dispose();
            }

            [SkipRemoteLinuxMonoFact]
            public void OnThenILThenOn() {
                h1 = new Hook(
                    typeof(OnOnIL).GetMethod("DoNothing"),
                    new Action<Action<OnOnIL>, OnOnIL>((orig, self) => {
                        orig(self);
                        h1Run = true;
                    }),
                    new HookConfig {
                        ManualApply = false
                    }
                );
                hIL = new ILHook(
                    typeof(OnOnIL).GetMethod("DoNothing"),
                    il => {
                        ILCursor c = new ILCursor(il);
                        c.EmitDelegate<Action>(() => {
                            hILRun = true;
                        });
                    },
                    new ILHookConfig {
                        ManualApply = false
                    }
                );
                h2 = new Hook(
                    typeof(OnOnIL).GetMethod("DoNothing"),
                    new Action<Action<OnOnIL>, OnOnIL>((orig, self) => {
                        orig(self);
                        h2Run = true;
                    }),
                    new HookConfig {
                        ManualApply = false
                    }
                );
                h1Run = false;
                h2Run = false;
                hILRun = false;
                DoNothing();
                Assert.True(h1Run);
                Assert.True(h2Run);
                Assert.True(hILRun);
                h1.Dispose();
                h2.Dispose();
                hIL.Dispose();
            }

            [SkipRemoteLinuxMonoFact]
            public void ILThenOnThenOn() {
                hIL = new ILHook(
                    typeof(OnOnIL).GetMethod("DoNothing"),
                    il => {
                        ILCursor c = new ILCursor(il);
                        c.EmitDelegate<Action>(() => {
                            hILRun = true;
                        });
                    },
                    new ILHookConfig {
                        ManualApply = false
                    }
                );
                h1 = new Hook(
                    typeof(OnOnIL).GetMethod("DoNothing"),
                    new Action<Action<OnOnIL>, OnOnIL>((orig, self) => {
                        orig(self);
                        h1Run = true;
                    }),
                    new HookConfig {
                        ManualApply = false
                    }
                );
                h2 = new Hook(
                    typeof(OnOnIL).GetMethod("DoNothing"),
                    new Action<Action<OnOnIL>, OnOnIL>((orig, self) => {
                        orig(self);
                        h2Run = true;
                    }),
                    new HookConfig {
                        ManualApply = false
                    }
                );
                h1Run = false;
                h2Run = false;
                hILRun = false;
                DoNothing();
                Assert.True(h1Run);
                Assert.True(h2Run);
                Assert.True(hILRun);
                h1.Dispose();
                h2.Dispose();
                hIL.Dispose();
            }
            [MethodImpl(MethodImplOptions.NoInlining)]
            public void DoNothing() {
            }
        }
    }
}

{'repo_name': 'MonoMod/MonoMod', 'stars': '238', 'repo_language': 'C#', 'file_name': 'ModInteropManager.cs', 'mime_type': 'text/plain', 'hash': 3949931341782115324, 'source_dataset': 'data'}