text:
//---------------------------------------------------------------------
// <copyright file="vs.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//
// @owner       [....]
// @backupOwner [....]
//---------------------------------------------------------------------

namespace System.Data.Metadata.Edm
{
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Diagnostics;
    using System.Globalization;
    using System.Linq;
    using System.Reflection;

    internal sealed class ObjectItemConventionAssemblyLoader : ObjectItemAssemblyLoader
    {
        // for root entities, entities with no base type, we will additionally look
        // at properties on the clr base hierarchy.
        private const BindingFlags RootEntityPropertyReflectionBindingFlags = PropertyReflectionBindingFlags & ~BindingFlags.DeclaredOnly | BindingFlags.FlattenHierarchy;

        private new MutableAssemblyCacheEntry CacheEntry { get { return (MutableAssemblyCacheEntry)base.CacheEntry; } }
        private List<Action> _referenceResolutions = new List<Action>();

        internal ObjectItemConventionAssemblyLoader(Assembly assembly, ObjectItemLoadingSessionData sessionData)
            : base(assembly, new MutableAssemblyCacheEntry(), sessionData)
        {
            Debug.Assert(Create == sessionData.ObjectItemAssemblyLoaderFactory, "Why is there a different factory creating this class");
            SessionData.RegisterForLevel1PostSessionProcessing(this);
        }

        protected override void LoadTypesFromAssembly()
        {
            foreach (Type type in EntityUtil.GetTypesSpecial(SourceAssembly))
            {
                EdmType cspaceType;
                if (TryGetCSpaceTypeMatch(type, out cspaceType))
                {
                    if (type.IsValueType && !type.IsEnum)
                    {
                        SessionData.LoadMessageLogger.LogLoadMessage(Strings.Validator_OSpace_Convention_Struct(cspaceType.FullName, type.FullName), cspaceType);
                        continue;
                    }

                    EdmType ospaceType;
                    if (TryCreateType(type, cspaceType, out ospaceType))
                    {
                        Debug.Assert(ospaceType is StructuralType || Helper.IsEnumType(ospaceType), "Only StructuralType or EnumType expected.");

                        CacheEntry.TypesInAssembly.Add(ospaceType);
                        // check for duplicates so we don't cause an ArgumentException,
                        // Mapping will do the actual error for the duplicate type later
                        if (!SessionData.CspaceToOspace.ContainsKey(cspaceType))
                        {
                            SessionData.CspaceToOspace.Add(cspaceType, ospaceType);
                        }
                        else
                        {
                            // at this point there is already a Clr Type that is structurally matched to this CSpace type, we throw exception
                            EdmType previousOSpaceType = SessionData.CspaceToOspace[cspaceType];
                            SessionData.EdmItemErrors.Add(
                                new EdmItemError(Strings.Validator_OSpace_Convention_AmbiguousClrType(cspaceType.Name, previousOSpaceType.ClrType.FullName, type.FullName), previousOSpaceType));
                        }
                    }
                }
            }

            if (SessionData.TypesInLoading.Count == 0)
            {
                Debug.Assert(CacheEntry.ClosureAssemblies.Count == 0, "How did we get closure assemblies?");

                // since we didn't find any types, don't lock into convention based
                SessionData.ObjectItemAssemblyLoaderFactory = null;
            }
        }

        protected override void AddToAssembliesLoaded()
        {
            SessionData.AssembliesLoaded.Add(SourceAssembly, CacheEntry);
        }

        private bool TryGetCSpaceTypeMatch(Type type, out EdmType cspaceType)
        {
            // brute force try and find a matching name
            KeyValuePair<EdmType, int> pair;
            if (SessionData.ConventionCSpaceTypeNames.TryGetValue(type.Name, out pair))
            {
                if (pair.Value == 1)
                {
                    // we found a type match
                    cspaceType = pair.Key;
                    return true;
                }
                else
                {
                    Debug.Assert(pair.Value > 1, "how did we get a negative count of types in the dictionary?");
                    SessionData.EdmItemErrors.Add(new EdmItemError(Strings.Validator_OSpace_Convention_MultipleTypesWithSameName(type.Name), pair.Key));
                }
            }

            cspaceType = null;
            return false;
        }

        /// <summary>
        /// Creates a structural or enum OSpace type based on CLR type and CSpace type.
        /// </summary>
        /// <param name="type">CLR type.</param>
        /// <param name="cspaceType">CSpace Type</param>
        /// <param name="newOSpaceType">OSpace type created based on CLR <paramref name="type"/> and <paramref name="cspaceType"/></param>
        /// <returns><c>true</c> if the type was created successfully. Otherwise <c>false</c>.</returns>
        private bool TryCreateType(Type type, EdmType cspaceType, out EdmType newOSpaceType)
        {
            Debug.Assert(type != null, "type != null");
            Debug.Assert(cspaceType != null, "cspaceType != null");
            Debug.Assert(cspaceType is StructuralType || Helper.IsEnumType(cspaceType), "Structural or enum type expected");

            newOSpaceType = null;

            // if one of the types is an enum while the other is not there is no match
            if (Helper.IsEnumType(cspaceType) ^ type.IsEnum)
            {
                SessionData.LoadMessageLogger.LogLoadMessage(
                    Strings.Validator_OSpace_Convention_SSpaceOSpaceTypeMismatch(cspaceType.FullName, cspaceType.FullName),
                    cspaceType);
                return false;
            }

            if(Helper.IsEnumType(cspaceType))
            {
                return TryCreateEnumType(type, (EnumType)cspaceType, out newOSpaceType);
            }
            else
            {
                Debug.Assert(cspaceType is StructuralType);
                return TryCreateStructuralType(type, (StructuralType)cspaceType, out newOSpaceType);
            }
        }

        /// <summary>
        /// Creates a structural OSpace type based on CLR type and CSpace type.
        /// </summary>
        /// <param name="type">CLR type.</param>
        /// <param name="cspaceType">CSpace Type</param>
        /// <param name="newOSpaceType">OSpace type created based on CLR <paramref name="type"/> and <paramref name="cspaceType"/></param>
        /// <returns><c>true</c> if the type was created successfully. Otherwise <c>false</c>.</returns>
        private bool TryCreateStructuralType(Type type, StructuralType cspaceType, out EdmType newOSpaceType)
        {
            Debug.Assert(type != null, "type != null");
            Debug.Assert(cspaceType != null, "cspaceType != null");

            List<Action> referenceResolutionListForCurrentType = new List<Action>();
            newOSpaceType = null;
            Debug.Assert(TypesMatchByConvention(type, cspaceType), "The types passed as parameters don't match by convention.");

            StructuralType ospaceType;
            if (Helper.IsEntityType(cspaceType))
            {
                ospaceType = new ClrEntityType(type, cspaceType.NamespaceName, cspaceType.Name);
            }
            else
            {
                Debug.Assert(Helper.IsComplexType(cspaceType), "Invalid type attribute encountered");
                ospaceType = new ClrComplexType(type, cspaceType.NamespaceName, cspaceType.Name);
            }

            if (cspaceType.BaseType != null)
            {
                if (TypesMatchByConvention(type.BaseType, cspaceType.BaseType))
                {
                    TrackClosure(type.BaseType);
                    referenceResolutionListForCurrentType.Add(
                        () => ospaceType.BaseType = ResolveBaseType((StructuralType)cspaceType.BaseType, type));
                }
                else
                {
                    string message = Strings.Validator_OSpace_Convention_BaseTypeIncompatible(type.BaseType.FullName, type.FullName, cspaceType.BaseType.FullName);
                    SessionData.LoadMessageLogger.LogLoadMessage(message, cspaceType);
                    return false;
                }
            }

            // Load the properties for this type
            if (!TryCreateMembers(type, (StructuralType)cspaceType, ospaceType, referenceResolutionListForCurrentType))
            {
                return false;
            }

            // Add this to the known type map so we won't try to load it again
            SessionData.TypesInLoading.Add(type.FullName, ospaceType);

            // we only add the referenceResolution to the list unless we structrually matched this type
            foreach (var referenceResolution in referenceResolutionListForCurrentType)
            {
                this._referenceResolutions.Add(referenceResolution);
            }

            newOSpaceType = ospaceType;
            return true;
        }

        /// <summary>
        /// Creates new enum OSpace type built based on CLR <paramref name="enumType"/> and <paramref name="cspaceEnumType"/>
        /// </summary>
        /// <param name="enumType">CLR type to create OSpace type from.</param>
        /// <param name="cspaceEnumType">CSpace type used to get namespace and name for the newly created OSpace type.</param>
        /// <param name="newOSpaceType">
        /// New enum OSpace type built based on CLR <paramref name="enumType"/> and <paramref name="cspaceEnumType"/> or null
        /// if the type could not be built.
        /// </param>
        /// <returns><c>true</c> if the type was built successfully.<c>false</c> otherwise.</returns>
        private bool TryCreateEnumType(Type enumType, EnumType cspaceEnumType, out EdmType newOSpaceType)
        {
            Debug.Assert(enumType != null, "enumType != null");
            Debug.Assert(enumType.IsEnum, "enum type expected");
            Debug.Assert(cspaceEnumType != null, "cspaceEnumType != null");
            Debug.Assert(Helper.IsEnumType(cspaceEnumType), "Enum type expected");
            Debug.Assert(TypesMatchByConvention(enumType, cspaceEnumType), "The types passed as parameters don't match by convention.");

            newOSpaceType = null;

            // Check if the OSpace and CSpace enum type match
            if (!UnderlyingEnumTypesMatch(enumType, cspaceEnumType) || !EnumMembersMatch(enumType, cspaceEnumType))
            {
                return false;
            }

            newOSpaceType = new ClrEnumType(enumType, cspaceEnumType.NamespaceName, cspaceEnumType.Name);
            SessionData.TypesInLoading.Add(enumType.FullName, newOSpaceType);

            return true;
        }

        /// <summary>
        /// Verifies whether underlying types of CLR and EDM types match
        /// </summary>
        /// <param name="enumType">OSpace CLR enum type.</param>
        /// <param name="cspaceEnumType">CSpace EDM enum type.</param>
        /// <returns><c>true</c> if types match. <c>false</c> otherwise.</returns>
        private bool UnderlyingEnumTypesMatch(Type enumType, EnumType cspaceEnumType)
        {
            Debug.Assert(enumType != null, "enumType != null");
            Debug.Assert(enumType.IsEnum, "expected enum OSpace type");
            Debug.Assert(cspaceEnumType != null, "cspaceEnumType != null");
            Debug.Assert(Helper.IsEnumType(cspaceEnumType), "Enum type expected");

            // Note that TryGetPrimitiveType() will return false not only for types that are not primitive
            // but also for CLR primitive types that are valid underlying enum types in CLR but are not
            // a valid Edm primitive types (e.g. ulong)
            PrimitiveType underlyingEnumType;
            if (!ClrProviderManifest.Instance.TryGetPrimitiveType(enumType.GetEnumUnderlyingType(), out underlyingEnumType))
            {
                SessionData.LoadMessageLogger.LogLoadMessage(
                    Strings.Validator_UnsupportedEnumUnderlyingType(enumType.GetEnumUnderlyingType().FullName),
                    cspaceEnumType);

                return false;
            }
            else if (underlyingEnumType.PrimitiveTypeKind != cspaceEnumType.UnderlyingType.PrimitiveTypeKind)
            {
                SessionData.LoadMessageLogger.LogLoadMessage(
                    Strings.Validator_OSpace_Convention_NonMatchingUnderlyingTypes, cspaceEnumType);

                return false;
            }

            return true;
        }

        /// <summary>
        /// Verifies whether enum members of CLR and EDM types match.
        /// </summary>
        /// <param name="enumType">OSpace CLR enum type.</param>
        /// <param name="cspaceEnumType">CSpace EDM enum type.</param>
        /// <returns><c>true</c> if members match. <c>false</c> otherwise.</returns>
        private bool EnumMembersMatch(Type enumType, EnumType cspaceEnumType)
        {
            Debug.Assert(enumType != null, "enumType != null");
            Debug.Assert(enumType.IsEnum, "expected enum OSpace type");
            Debug.Assert(cspaceEnumType != null, "cspaceEnumType != null");
            Debug.Assert(Helper.IsEnumType(cspaceEnumType), "Enum type expected");
            Debug.Assert(cspaceEnumType.UnderlyingType.ClrEquivalentType == enumType.GetEnumUnderlyingType(), "underlying types should have already been checked");

            var enumUnderlyingType = enumType.GetEnumUnderlyingType();

            var cspaceSortedEnumMemberEnumerator = cspaceEnumType.Members.OrderBy(m => m.Name).GetEnumerator();
            var ospaceSortedEnumMemberNamesEnumerator = enumType.GetEnumNames().OrderBy(n => n).GetEnumerator();

            // no checks required if edm enum type does not have any members
            if (!cspaceSortedEnumMemberEnumerator.MoveNext())
            {
                return true;
            }

            while (ospaceSortedEnumMemberNamesEnumerator.MoveNext())
            {
                if (cspaceSortedEnumMemberEnumerator.Current.Name == ospaceSortedEnumMemberNamesEnumerator.Current &&
                    cspaceSortedEnumMemberEnumerator.Current.Value.Equals(
                        Convert.ChangeType(
                            Enum.Parse(enumType, ospaceSortedEnumMemberNamesEnumerator.Current), enumUnderlyingType, CultureInfo.InvariantCulture)))
                {
                    if (!cspaceSortedEnumMemberEnumerator.MoveNext())
                    {
                        return true;
                    }
                }
            }

            SessionData.LoadMessageLogger.LogLoadMessage(
                System.Data.Entity.Strings.Mapping_Enum_OCMapping_MemberMismatch(
                        enumType.FullName,
                        cspaceSortedEnumMemberEnumerator.Current.Name,
                        cspaceSortedEnumMemberEnumerator.Current.Value,
                        cspaceEnumType.FullName), cspaceEnumType);

            return false;
        }

        internal override void OnLevel1SessionProcessing()
        {
            CreateRelationships();

            foreach (Action resolve in _referenceResolutions)
            {
                resolve();
            }

            base.OnLevel1SessionProcessing();
        }

        private EdmType ResolveBaseType(StructuralType baseCSpaceType, Type type)
        {
            EdmType ospaceType;
            bool foundValue = SessionData.CspaceToOspace.TryGetValue(baseCSpaceType, out ospaceType);
            if (!foundValue)
            {
                string message =
                    SessionData.LoadMessageLogger.CreateErrorMessageWithTypeSpecificLoadLogs(
                        Strings.Validator_OSpace_Convention_BaseTypeNotLoaded(type, baseCSpaceType),
                        baseCSpaceType);
                SessionData.EdmItemErrors.Add(new EdmItemError(message, ospaceType));
            }

            Debug.Assert(!foundValue || ospaceType is StructuralType, "Structural type expected (if found).");

            return ospaceType;
        }

        private bool TryCreateMembers(Type type, StructuralType cspaceType, StructuralType ospaceType, List<Action> referenceResolutionListForCurrentType)
        {
            BindingFlags flags = cspaceType.BaseType == null ? RootEntityPropertyReflectionBindingFlags : PropertyReflectionBindingFlags;

            PropertyInfo[] clrProperties = type.GetProperties(flags);

            // required properties scalar properties first
            if (!TryFindAndCreatePrimitiveProperties(type, cspaceType, ospaceType, clrProperties))
            {
                return false;
            }

            if(!TryFindAndCreateEnumProperties(type, cspaceType, ospaceType, clrProperties, referenceResolutionListForCurrentType))
            {
                return false;
            }

            if (!TryFindComplexProperties(type, cspaceType, ospaceType, clrProperties, referenceResolutionListForCurrentType))
            {
                return false;
            }

            if (!TryFindNavigationProperties(type, cspaceType, ospaceType, clrProperties, referenceResolutionListForCurrentType))
            {
                return false;
            }

            return true;
        }

        private bool TryFindComplexProperties(Type type, StructuralType cspaceType, StructuralType ospaceType, PropertyInfo[] clrProperties, List<Action> referenceResolutionListForCurrentType)
        {
            List<KeyValuePair<EdmProperty, PropertyInfo>> typeClosureToTrack =
                new List<KeyValuePair<EdmProperty, PropertyInfo>>();
            foreach (EdmProperty cspaceProperty in cspaceType.GetDeclaredOnlyMembers<EdmProperty>().Where(m => Helper.IsComplexType(m.TypeUsage.EdmType)))
            {
                PropertyInfo clrProperty = clrProperties.FirstOrDefault(p => MemberMatchesByConvention(p, cspaceProperty));
                if (clrProperty != null)
                {
                    typeClosureToTrack.Add(
                        new KeyValuePair<EdmProperty, PropertyInfo>(
                            cspaceProperty, clrProperty));
                }
                else
                {
                    string message = Strings.Validator_OSpace_Convention_MissingRequiredProperty(cspaceProperty.Name, type.FullName);
                    SessionData.LoadMessageLogger.LogLoadMessage(message, cspaceType);
                    return false;
                }
            }

            foreach (var typeToTrack in typeClosureToTrack)
            {
                TrackClosure(typeToTrack.Value.PropertyType);
                // prevent the lifting of these closure variables
                var ot = ospaceType;
                var cp = typeToTrack.Key;
                var clrp = typeToTrack.Value;
                referenceResolutionListForCurrentType.Add(() => CreateAndAddComplexType(type, ot, cp, clrp));
            }

            return true;
        }

        private bool TryFindNavigationProperties(Type type, StructuralType cspaceType, StructuralType ospaceType, PropertyInfo[] clrProperties, List<Action> referenceResolutionListForCurrentType)
        {
            List<KeyValuePair<NavigationProperty, PropertyInfo>> typeClosureToTrack =
                new List<KeyValuePair<NavigationProperty, PropertyInfo>>();
            foreach (NavigationProperty cspaceProperty in cspaceType.GetDeclaredOnlyMembers<NavigationProperty>())
            {
                PropertyInfo clrProperty = clrProperties.FirstOrDefault(p => NonPrimitiveMemberMatchesByConvention(p, cspaceProperty));
                if (clrProperty != null)
                {
                    bool needsSetter = cspaceProperty.ToEndMember.RelationshipMultiplicity != RelationshipMultiplicity.Many;
                    if (clrProperty.CanRead && (!needsSetter || clrProperty.CanWrite))
                    {
                        typeClosureToTrack.Add(
                            new KeyValuePair<NavigationProperty, PropertyInfo>(
                                cspaceProperty, clrProperty));
                    }
                }
                else
                {
                    string message = Strings.Validator_OSpace_Convention_MissingRequiredProperty(
                        cspaceProperty.Name, type.FullName);
                    SessionData.LoadMessageLogger.LogLoadMessage(message, cspaceType);
                    return false;
                }
            }

            foreach (var typeToTrack in typeClosureToTrack)
            {
                TrackClosure(typeToTrack.Value.PropertyType);

                // keep from lifting these closure variables
                var ct = cspaceType;
                var ot = ospaceType;
                var cp = typeToTrack.Key;
                var clrp = typeToTrack.Value;

                referenceResolutionListForCurrentType.Add(() => CreateAndAddNavigationProperty(ct, ot, cp, clrp));
            }

            return true;
        }

        private void TrackClosure(Type type)
        {

            if (SourceAssembly != type.Assembly &&
                !CacheEntry.ClosureAssemblies.Contains(type.Assembly) &&
                !(type.IsGenericType &&
                  (
                    EntityUtil.IsAnICollection(type) || // EntityCollection<>, List<>, ICollection<>
                    type.GetGenericTypeDefinition() == typeof(System.Data.Objects.DataClasses.EntityReference<>) ||
                    type.GetGenericTypeDefinition() == typeof(System.Nullable<>)
                  )
                 )
                )
            {
                CacheEntry.ClosureAssemblies.Add(type.Assembly);
            }

            if (type.IsGenericType)
            {
                foreach (Type genericArgument in type.GetGenericArguments())
                {
                    TrackClosure(genericArgument);
                }
            }
        }

        private void CreateAndAddComplexType(Type type, StructuralType ospaceType, EdmProperty cspaceProperty, PropertyInfo clrProperty)
        {
            EdmType propertyType;
            if (SessionData.CspaceToOspace.TryGetValue((StructuralType)cspaceProperty.TypeUsage.EdmType, out propertyType))
            {
                Debug.Assert(propertyType is StructuralType, "Structural type expected.");

                EdmProperty property = new EdmProperty(cspaceProperty.Name, TypeUsage.Create(propertyType, new FacetValues { Nullable = false }), clrProperty, type.TypeHandle);
                ospaceType.AddMember(property);
            }
            else
            {
                string message =
                    SessionData.LoadMessageLogger.CreateErrorMessageWithTypeSpecificLoadLogs(
                        Strings.Validator_OSpace_Convention_MissingOSpaceType(cspaceProperty.TypeUsage.EdmType.FullName),
                        cspaceProperty.TypeUsage.EdmType);
                SessionData.EdmItemErrors.Add(new EdmItemError(message, ospaceType));
            }

        }

        private void CreateAndAddNavigationProperty(StructuralType cspaceType, StructuralType ospaceType, NavigationProperty cspaceProperty, PropertyInfo clrProperty)
        {
            EdmType ospaceRelationship;
            if (SessionData.CspaceToOspace.TryGetValue(cspaceProperty.RelationshipType, out ospaceRelationship))
            {
                Debug.Assert(ospaceRelationship is StructuralType, "Structural type expected.");

                bool foundTarget = false;
                EdmType targetType = null;
                if (Helper.IsCollectionType(cspaceProperty.TypeUsage.EdmType))
                {
                    EdmType findType;
                    foundTarget = SessionData.CspaceToOspace.TryGetValue((StructuralType)((CollectionType)cspaceProperty.TypeUsage.EdmType).TypeUsage.EdmType, out findType);
                    if (foundTarget)
                    {
                        Debug.Assert(findType is StructuralType, "Structural type expected.");

                        targetType = findType.GetCollectionType();
                    }
                }
                else
                {
                    EdmType findType;
                    foundTarget = SessionData.CspaceToOspace.TryGetValue((StructuralType)cspaceProperty.TypeUsage.EdmType, out findType);
                    if (foundTarget)
                    {
                        Debug.Assert(findType is StructuralType, "Structural type expected.");

                        targetType = findType;
                    }
                }

                Debug.Assert(foundTarget, "Since the relationship will only be created if it can find the types for both ends, we will never fail to find one of the ends");

                NavigationProperty navigationProperty = new NavigationProperty(cspaceProperty.Name, TypeUsage.Create(targetType), clrProperty);
                navigationProperty.RelationshipType = (RelationshipType)ospaceRelationship;

                // we can use First because o-space relationships are created directly from
                // c-space relationship
                navigationProperty.ToEndMember = (RelationshipEndMember)((RelationshipType)ospaceRelationship).Members.First(e => e.Name == cspaceProperty.ToEndMember.Name);
                navigationProperty.FromEndMember = (RelationshipEndMember)((RelationshipType)ospaceRelationship).Members.First(e => e.Name == cspaceProperty.FromEndMember.Name);
                ospaceType.AddMember(navigationProperty);
            }
            else
            {
                EntityTypeBase missingType = cspaceProperty.RelationshipType.RelationshipEndMembers.Select(e => ((RefType)e.TypeUsage.EdmType).ElementType).First(e => e != cspaceType);
                string message =
                    SessionData.LoadMessageLogger.CreateErrorMessageWithTypeSpecificLoadLogs(
                        Strings.Validator_OSpace_Convention_RelationshipNotLoaded(cspaceProperty.RelationshipType.FullName, missingType.FullName),
                        missingType);
                SessionData.EdmItemErrors.Add(new EdmItemError(message, ospaceType));
            }
        }

        private bool TryFindAndCreatePrimitiveProperties(Type type, StructuralType cspaceType, StructuralType ospaceType, PropertyInfo[] clrProperties)
        {
            foreach (EdmProperty cspaceProperty in cspaceType.GetDeclaredOnlyMembers<EdmProperty>().Where(p => Helper.IsPrimitiveType(p.TypeUsage.EdmType)))
            {
                PropertyInfo clrProperty = clrProperties.FirstOrDefault(p => MemberMatchesByConvention(p, cspaceProperty));
                if (clrProperty != null)
                {
                    PrimitiveType propertyType;
                    if (TryGetPrimitiveType(clrProperty.PropertyType, out propertyType))
                    {
                        if (clrProperty.CanRead && clrProperty.CanWrite)
                        {
                            AddScalarMember(type, clrProperty, ospaceType, cspaceProperty, propertyType);
                        }
                        else
                        {
                            string message = Strings.Validator_OSpace_Convention_ScalarPropertyMissginGetterOrSetter(clrProperty.Name, type.FullName, type.Assembly.FullName);
                            SessionData.LoadMessageLogger.LogLoadMessage(message, cspaceType);
                            return false;
                        }
                    }
                    else
                    {
                        string message = Strings.Validator_OSpace_Convention_NonPrimitiveTypeProperty(clrProperty.Name, type.FullName, clrProperty.PropertyType.FullName);
                        SessionData.LoadMessageLogger.LogLoadMessage(message, cspaceType);
                        return false;
                    }
                }
                else
                {
                    string message = Strings.Validator_OSpace_Convention_MissingRequiredProperty(cspaceProperty.Name, type.FullName);
                    SessionData.LoadMessageLogger.LogLoadMessage(message, cspaceType);
                    return false;
                }
            }
            return true;
        }

        private bool TryFindAndCreateEnumProperties(Type type, StructuralType cspaceType, StructuralType ospaceType, PropertyInfo[] clrProperties, List<Action> referenceResolutionListForCurrentType)
        {
            var typeClosureToTrack = new List<KeyValuePair<EdmProperty, PropertyInfo>>();

            foreach (EdmProperty cspaceProperty in cspaceType.GetDeclaredOnlyMembers<EdmProperty>().Where(p => Helper.IsEnumType(p.TypeUsage.EdmType)))
            {
                PropertyInfo clrProperty = clrProperties.FirstOrDefault(p => MemberMatchesByConvention(p, cspaceProperty));
                if (clrProperty != null)
                {
                    typeClosureToTrack.Add(new KeyValuePair<EdmProperty, PropertyInfo>(cspaceProperty, clrProperty));
                }
                else
                {
                    string message = Strings.Validator_OSpace_Convention_MissingRequiredProperty(cspaceProperty.Name, type.FullName);
                    SessionData.LoadMessageLogger.LogLoadMessage(message, cspaceType);
                    return false;
                }
            }

            foreach (var typeToTrack in typeClosureToTrack)
            {
                TrackClosure(typeToTrack.Value.PropertyType);
                // prevent the lifting of these closure variables
                var ot = ospaceType;
                var cp = typeToTrack.Key;
                var clrp = typeToTrack.Value;
                referenceResolutionListForCurrentType.Add(() => CreateAndAddEnumProperty(type, ot, cp, clrp));
            }

            return true;
        }

        /// <summary>
        /// Creates an Enum property based on <paramref name="clrProperty"/>and adds it to the parent structural type.
        /// </summary>
        /// <param name="type">CLR type owning <paramref name="clrProperty"/>.</param>
        /// <param name="ospaceType">OSpace type the created property will be added to.</param>
        /// <param name="cspaceProperty">Corresponding property from CSpace.</param>
        /// <param name="clrProperty">CLR property used to build an Enum property.</param>
        private void CreateAndAddEnumProperty(Type type, StructuralType ospaceType, EdmProperty cspaceProperty, PropertyInfo clrProperty)
        {
            EdmType propertyType;
            if (SessionData.CspaceToOspace.TryGetValue(cspaceProperty.TypeUsage.EdmType, out propertyType))
            {
                if (clrProperty.CanRead && clrProperty.CanWrite)
                {
                    AddScalarMember(type, clrProperty, ospaceType, cspaceProperty, propertyType);
                }
                else
                {
                    string message =
                        SessionData.LoadMessageLogger.CreateErrorMessageWithTypeSpecificLoadLogs(
                            Strings.Validator_OSpace_Convention_ScalarPropertyMissginGetterOrSetter(clrProperty.Name, type.FullName, type.Assembly.FullName),
                            cspaceProperty.TypeUsage.EdmType);

                    SessionData.EdmItemErrors.Add(new EdmItemError(message, ospaceType));
                }
            }
            else
            {
                string message =
                    SessionData.LoadMessageLogger.CreateErrorMessageWithTypeSpecificLoadLogs(
                        Strings.Validator_OSpace_Convention_MissingOSpaceType(cspaceProperty.TypeUsage.EdmType.FullName),
                        cspaceProperty.TypeUsage.EdmType);

                SessionData.EdmItemErrors.Add(new EdmItemError(message, ospaceType));
            }
        }

        private void CreateRelationships()
        {
            if (SessionData.ConventionBasedRelationshipsAreLoaded)
            {
                return;
            }

            SessionData.ConventionBasedRelationshipsAreLoaded = true;

            // find all the relationships
            foreach (AssociationType cspaceAssociation in SessionData.EdmItemCollection.GetItems<AssociationType>())
            {
                Debug.Assert(cspaceAssociation.RelationshipEndMembers.Count == 2, "Relationships are assumed to have exactly two ends");

                if (SessionData.CspaceToOspace.ContainsKey(cspaceAssociation))
                {
                    // don't try to load relationships that we already know about
                    continue;
                }

                EdmType[] ospaceEndTypes = new EdmType[2];
                if (SessionData.CspaceToOspace.TryGetValue(GetRelationshipEndType(cspaceAssociation.RelationshipEndMembers[0]), out ospaceEndTypes[0]) &&
                    SessionData.CspaceToOspace.TryGetValue(GetRelationshipEndType(cspaceAssociation.RelationshipEndMembers[1]), out ospaceEndTypes[1]))
                {
                    Debug.Assert(ospaceEndTypes[0] is StructuralType);
                    Debug.Assert(ospaceEndTypes[1] is StructuralType);

                    // if we can find both ends of the relationship, then create it

                    AssociationType ospaceAssociation = new AssociationType(cspaceAssociation.Name, cspaceAssociation.NamespaceName, cspaceAssociation.IsForeignKey, DataSpace.OSpace);
                    for (int i = 0; i < cspaceAssociation.RelationshipEndMembers.Count; i++)
                    {
                        EntityType ospaceEndType = (EntityType)ospaceEndTypes[i];
                        RelationshipEndMember cspaceEnd = cspaceAssociation.RelationshipEndMembers[i];

                        ospaceAssociation.AddKeyMember(new AssociationEndMember(cspaceEnd.Name, ospaceEndType.GetReferenceType(), cspaceEnd.RelationshipMultiplicity));
                    }
                    CacheEntry.TypesInAssembly.Add(ospaceAssociation);
                    SessionData.TypesInLoading.Add(ospaceAssociation.FullName, ospaceAssociation);
                    SessionData.CspaceToOspace.Add(cspaceAssociation, ospaceAssociation);

                }
            }
        }

        private static StructuralType GetRelationshipEndType(RelationshipEndMember relationshipEndMember)
        {
            return ((RefType)relationshipEndMember.TypeUsage.EdmType).ElementType;
        }

        private static bool MemberMatchesByConvention(PropertyInfo clrProperty, EdmMember cspaceMember)
        {
            return clrProperty.Name == cspaceMember.Name;
        }

        private static bool NonPrimitiveMemberMatchesByConvention(PropertyInfo clrProperty, EdmMember cspaceMember)
        {
            return !clrProperty.PropertyType.IsValueType && !clrProperty.PropertyType.IsAssignableFrom(typeof(string)) && clrProperty.Name == cspaceMember.Name;
        }

        internal static bool SessionContainsConventionParameters(ObjectItemLoadingSessionData sessionData)
        {
            return sessionData.EdmItemCollection != null;
        }

        internal static bool TypesMatchByConvention(Type type, EdmType cspaceType)
        {
            return type.Name == cspaceType.Name;
        }

        private void AddScalarMember(Type type, PropertyInfo clrProperty, StructuralType ospaceType, EdmProperty cspaceProperty, EdmType propertyType)
        {
            Debug.Assert(type != null, "type != null");
            Debug.Assert(clrProperty != null, "clrProperty != null");
            Debug.Assert(clrProperty.CanRead && clrProperty.CanWrite, "The clr property has to have a setter and a getter.");
            Debug.Assert(ospaceType != null, "ospaceType != null");
            Debug.Assert(cspaceProperty != null, "cspaceProperty != null");
            Debug.Assert(propertyType != null, "propertyType != null");
            Debug.Assert(Helper.IsScalarType(propertyType), "Property has to be primitive or enum.");

            var cspaceType = cspaceProperty.DeclaringType;

            bool isKeyMember = Helper.IsEntityType(cspaceType) && ((EntityType)cspaceType).KeyMemberNames.Contains(clrProperty.Name);

            // the property is nullable only if it is not a key and can actually be set to null (i.e. is not a value type or is a nullable value type)
            bool nullableFacetValue = !isKeyMember && (!clrProperty.PropertyType.IsValueType || Nullable.GetUnderlyingType(clrProperty.PropertyType) != null);

            EdmProperty ospaceProperty =
                new EdmProperty(
                    cspaceProperty.Name,
                    TypeUsage.Create(propertyType, new FacetValues { Nullable = nullableFacetValue }),
                    clrProperty,
                    type.TypeHandle);

            if (isKeyMember)
            {
                ((EntityType)ospaceType).AddKeyMember(ospaceProperty);
            }
            else
            {
                ospaceType.AddMember(ospaceProperty);
            }
        }

        internal static ObjectItemAssemblyLoader Create(Assembly assembly, ObjectItemLoadingSessionData sessionData)
        {
            if (!ObjectItemAttributeAssemblyLoader.IsSchemaAttributePresent(assembly))
            {
                return new ObjectItemConventionAssemblyLoader(assembly, sessionData);
            }
            else
            {
                // we were loading in convention mode, and ran into an assembly that can't be loaded by convention
                sessionData.EdmItemErrors.Add(new EdmItemError(Strings.Validator_OSpace_Convention_AttributeAssemblyReferenced(assembly.FullName), null));
                return new ObjectItemNoOpAssemblyLoader(assembly, sessionData);
            }
        }
    }
}


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System.Web;

namespace ServiceStack.Html.AntiXsrf
{
    // Provides an abstraction around how tokens are persisted and retrieved for a request
    internal interface ITokenStore
    {
        AntiForgeryToken GetCookieToken(HttpContextBase httpContext);
        AntiForgeryToken GetFormToken(HttpContextBase httpContext);
        void SaveCookieToken(HttpContextBase httpContext, AntiForgeryToken token);
    }
}

redpajama_set_name: RedPajamaGithub


text:
  - Changed help animation

### Since 0.12.0 (25 Oct 2017):

  - Changed all triggers from `md` to `mat`

### Since 0.11.0 (24 Jun 2017):

  - Added support for choices using new [choices API](https://github.com/Microsoft/vscode/issues/17545#issuecomment-271511528)

### Since 0.10.0 (23 Jun 2017):

  - Added support for new `accordion` & `expansion` material components
  - Fixed issues with few covalent snippets
  - Added new attribute directives for existing components
  - Made compatible with material `2.0.0-beta.7` release

### Since 0.9.0 (22 Jun 2017):

  - Now all attribute directives start with `@`

### Since 0.8.5 (15 Jun 2017):
### Since 0.8.4 (15 Jun 2017):

  - Better documentation

### Since 0.8.3 (15 Jun 2017):
### Since 0.8.2 (15 Jun 2017):
### Since 0.8.1 (15 Jun 2017):

  - Non functional changes

### Since 0.8.0 (15 Jun 2017):

  - Added support for reactive form control variation for each input
  - Added support for datepicker in material2
  - Added `optgroup` support for select component. This allows you to group options within select
  - Removed `fxLayoutWrap` as this is deprecated in favor of `fxLayout`

### Since 0.7.0 (7 Mar 2017):

  - Fixed a minor issue with svg set

### Since 0.6.0 (20 Feb 2017):

  - Made tooltip an attribute directive instead of snippet

### Since 0.5.0 (20 Feb 2017):

  - Fixed issue with templates that does not have name such as `button/.html` will also be included as part of templates
  - Improved help within `README.md`

### Since 0.4.0 (20 Feb 2017):

  - Fixed issue with tooltip

### Since 0.3.0 (19 Feb 2017):

  - Fixed issue with input floating placeholder

### Since 0.2.0 (18 Feb 2017):

  - Now extension should show gif showing how to use

### Since 0.1.0 (18 Feb 2017):

  - Initial support for Material v2.0.0-beta.2, Teradata covalent v1.0.0-beta.1, Flex layout 1.0.0-beta.5 & Material icons


text:
#include <gtypes.h>
#include <libc/stdio.h>

/**********************/
/* user_mfd_driver   */
/*********************/

void user_mfd_driver
    (types__pagerequestcmd* displaytodm_request,
    types__pagecontent displaytodm_page)
{
   printf ("[MFD] USER MFD DRIVER\n");
}


text:
set -e

# Filter categories:
# - Desktop environment (X11)
INSTALL_DESKTOP=false
# - Lightdm Desktop manager
INSTALL_LIGHTDM=false
# - Tools for program analysis
INSTALL_PRGANALYSIS_TOOLS=false
# - XFCE window manager
INSTALL_XFCE=false

while [ $# -ge 1 ]
do
    case "$1" in
        desktop)
            INSTALL_DESKTOP=true
            ;;
        lightdm)
            INSTALL_DESKTOP=true
            INSTALL_LIGHTDM=true
            ;;
        prganalysis-tools)
            INSTALL_PRGANALYSIS_TOOLS=true
            ;;
        xfce)
            INSTALL_DESKTOP=true
            INSTALL_XFCE=true
            ;;
        *)
            echo >&2 "Unknown selection $1"
            exit 1
            ;;
    esac
    shift
done

# Is this script running as root?
is_root() {
    [[ "$EUID" = "0" ]] || [ "$(id -u)" = "0" ]
}

# Find a usable user to build package without being root
BUILD_USER='nobody'
if ! is_root
then
    BUILD_USER="$(id -nu)"
elif [ -n "$SUDO_USER" ] && [ "$SUDO_USER" != 'root' ]
then
    BUILD_USER="$SUDO_USER"
fi
echo "Using build user: $BUILD_USER"

# Install packages from the official repository
pkg() {
    local PKGNAMES PKG
    PKGNAMES=()
    for PKG
    do
        if ! pacman -Si "$PKG" > /dev/null ; then
            echo >&2 "Package $PKG is not in official repositories"
            return 1
        elif ! pacman -Qi "$PKG" > /dev/null ; then
            PKGNAMES+=("$PKG")
        fi
    done
    if [ -n "${PKGNAMES[*]}" ] ; then
        if ! is_root
        then
            echo "pacman -S --noconfirm ${PKGNAMES[*]}"
            return
        fi
        echo "Installing ${PKGNAMES[*]}"
        pacman -S --noconfirm "${PKGNAMES[@]}"
        return $?
    fi
}

# Install packages from the AUR repository
aurpkg() {
    local PKGNAMES PKG
    PKGNAMES=()
    for PKG
    do
        if pacman -Si "$PKG" > /dev/null 2>&1 ; then
            echo >&2 "Package $PKG is in official repositories, not in the AUR"
            return 1
        elif ! pacman -Qi "$PKG" > /dev/null ; then
            PKGNAMES+=("$PKG")
        fi
    done
    if [ -n "${PKGNAMES[*]}" ] ; then
        if ! is_root
        then
            echo "sudo -u $BUILD_USER trizen -S ${PKGNAMES[*]}"
            return
        fi
        echo "Installing for AUR ${PKGNAMES[*]}"
        sudo -u "$BUILD_USER" trizen -S "${PKGNAMES[@]}"
        return $?
    fi
}

# Install packages from groups in the official repository
grouppkg() {
    local PKG GROUP
    for GROUP
    do
        if pacman -Si "$GROUP" > /dev/null 2>&1 ; then
            echo >&2 "Group $GROUP is a package in official repositories, not a group"
            return 1
        elif ! pacman -Sg "$GROUP" > /dev/null ; then
            echo >&2 "Group $GROUP has not been found in official repositories"
            return 1
        else
            echo "Installing packages from group $GROUP..."
            # shellcheck disable=SC2046
            if ! pkg $(pacman -Sqg "$GROUP")
            then
                return 1
            fi
        fi
    done
}

# Update the package database
if is_root
then
    pacman -Sy
fi

# Bootstrap installation of trizen AUR helper
if ! pacman -Qi trizen > /dev/null
then
    TRIZEN_BOOTSTRAP_DIR="${TRIZEN_BOOTSTRAP_DIR:-/tmp/trizen_bootstrap_dir}"
    echo 'Download, build and install trizen...'
    if is_root
    then
        sudo -u "$BUILD_USER" mkdir -p "$TRIZEN_BOOTSTRAP_DIR"
        sudo -u "$BUILD_USER" git clone https://aur.archlinux.org/trizen.git "$TRIZEN_BOOTSTRAP_DIR"
        (cd "$TRIZEN_BOOTSTRAP_DIR" && sudo -u "$BUILD_USER" makepkg -si)
    else
        echo '... or not, as we are not root'
    fi
fi

# Essential packages
pkg attr
pkg audit
pkg base
pkg bash-completion
pkg bc
pkg binutils
pkg busybox
pkg ca-certificates
pkg ccze
pkg colordiff
pkg diffstat
pkg dos2unix
pkg file
pkg fortune-mod
pkg gnupg
pkg haveged
pkg highlight
pkg htop
pkg iotop
pkg jq
pkg less
pkg lsb-release
pkg lsof
pkg moreutils
pkg most
pkg neovim
pkg progress
pkg psmisc
pkg pv
pkg reptyr
pkg ripgrep
pkg rlwrap
pkg rng-tools
pkg screen
pkg strace
pkg sudo
pkg time
pkg tmux
pkg vim
pkg zsh

# Hardware and TTY
pkg acpi
pkg acpi_call
pkg acpica
pkg bluez
pkg bluez-utils
pkg crda
pkg dmidecode
pkg efibootmgr
pkg fwupd
pkg gpm
pkg i2c-tools
pkg iw
pkg kbd
pkg libfido2
pkg lm_sensors
pkg lshw
pkg pciutils
pkg picocom
pkg read-edid
pkg smartmontools
pkg tpm2-pkcs11
pkg tpm2-tools
pkg tpm2-tss-engine
pkg usbutils
pkg wireless_tools
pkg wpa_supplicant

# Archives and filesystems
pkg btrfs-progs
pkg cabextract
pkg cpio
pkg cryfs
pkg cryptsetup
pkg dosfstools
pkg exfat-utils
pkg ext4magic
pkg innoextract
pkg lvm2
pkg lzop
pkg mdadm
pkg mtd-utils
pkg mtools
pkg ntfs-3g
pkg p7zip
pkg squashfs-tools
pkg unrar
pkg unzip
pkg zip

# Network
pkg arptables
pkg bind
pkg bridge-utils
pkg curl
pkg cyrus-sasl-gssapi
pkg dhclient
pkg dnsmasq
pkg ebtables
pkg fail2ban
pkg firejail
pkg hping
pkg iftop
pkg inetutils
pkg iptables
pkg iputils
pkg ldns
pkg lftp
pkg links
pkg mariadb-clients
pkg mtr
pkg mutt
pkg ndisc6
pkg net-snmp
pkg net-tools
pkg nftables
pkg nmap
pkg openbsd-netcat
pkg openldap
pkg openssh
pkg proxychains-ng
pkg rsync
pkg smbclient
pkg socat
pkg sqlmap
pkg sshfs
pkg stubby
pkg tcpdump
#pkg tor
pkg torsocks
pkg traceroute
pkg unbound
pkg wget
pkg whois
pkg wireguard-tools
pkg wireshark-cli

# Development
grouppkg base-devel
grouppkg multilib-devel
grouppkg linux-tools
pkg autoconf-archive
pkg bat
pkg bison
pkg check
pkg clang
pkg cmake
pkg devtools
pkg ed
pkg fakechroot
pkg fakeroot
pkg flex
pkg gdb
pkg git
pkg go
pkg help2man
pkg hexyl
pkg ipython
pkg libcap-ng
pkg linux-hardened-headers
pkg linux-headers
pkg ltrace
pkg mypy
pkg nodejs
pkg npm
pkg pkgconf
pkg pwgen
pkg pypy
pkg pypy3
pkg python
pkg ruby
pkg ruby-irb
pkg ruby-rake
pkg rustup
pkg sbt
pkg shellcheck
pkg yarn

# Intel x86 CPU
if [ "$(uname -m)" = 'x86_64' ]
then
    pkg intel-ucode
    pkg iucode-tool
    pkg x86_energy_perf_policy
fi

# Other
pkg cmatrix
pkg figlet
pkg john
pkg lolcat
pkg sl

# Arch Linux-specific packages
pkg asp
pkg aurphan
pkg pacman-contrib

if "$INSTALL_DESKTOP"
then
    # X11 server
    grouppkg xorg
    grouppkg xorg-drivers
    pkg rxvt-unicode
    pkg wmctrl
    pkg xpra
    pkg xscreensaver
    pkg xsel
    pkg xterm

    # Fonts
    pkg gnu-free-fonts
    pkg ttf-bitstream-vera
    pkg ttf-cascadia-code
    pkg ttf-dejavu
    pkg ttf-droid
    pkg ttf-fantasque-sans-mono
    pkg ttf-fira-code
    pkg ttf-fira-mono
    pkg ttf-fira-sans
    pkg ttf-font-awesome
    pkg ttf-inconsolata
    pkg ttf-liberation
    pkg ttf-ubuntu-font-family
    aurpkg ttf-vlgothic

    # Sound
    pkg alsa-utils
    pkg audacity
    pkg paprefs
    pkg pavucontrol
    pkg pulseaudio

    # Smartcard and YubiKey
    pkg ccid
    pkg libu2f-host
    pkg opensc
    pkg pcsc-tools
    pkg yubikey-manager
    pkg yubikey-personalization
    pkg yubikey-personalization-gui

    # Applications
    pkg arandr
    pkg baobab
    pkg bleachbit
    pkg cheese
    pkg chromium
    pkg eog
    pkg evince
    pkg ffmpeg
    pkg file-roller
    pkg filezilla
    pkg firefox
    pkg freerdp
    pkg gedit
    pkg gedit-plugins
    pkg gimp
    pkg gnome-mahjongg
    pkg gnome-system-monitor
    pkg gparted
    pkg graphviz
    pkg gtk3
    pkg gvfs
    pkg gvfs-smb
    pkg imagemagick
    pkg keepass
    pkg kismet
    pkg libreoffice-fresh
    pkg libvncserver
    pkg meld
    pkg modemmanager
    pkg mupdf
    pkg mupdf-tools
    pkg network-manager-applet
    pkg networkmanager
    pkg networkmanager-openvpn
    pkg networkmanager-strongswan
    pkg pandoc
    pkg parted
    pkg pdfpc
    pkg qpdf
    pkg rdesktop
    pkg recordmydesktop
    pkg remmina
    pkg sdl2
    pkg simple-scan
    pkg sox
    pkg sqlitebrowser
    pkg tk
    pkg udisks2
    pkg vinagre
    pkg vlc
    pkg wireshark-qt
    pkg x11vnc
    pkg xdg-utils
    pkg xdot
    pkg xsensors
    pkg xterm
    pkg youtube-dl
    pkg zenity

    aurpkg burpsuite
    aurpkg restview
    aurpkg trickle

    # Language
    pkg hunspell-en_GB
    pkg hunspell-en_US
    pkg hunspell-fr
    pkg mythes-en
    pkg mythes-fr

    # Power management for laptops
    pkg tlp
    pkg tp_smapi

    # Multilib repo
    pkg wine wine-gecko wine-mono winetricks

    # MinGW64
    pkg mingw-w64-binutils mingw-w64-gcc

    # Optional
    #pkg gnome-keyring
    #pkg virtualbox
    #pkg virtualbox-host-dkms
    #pkg virtualbox-guest-iso
fi

if "$INSTALL_LIGHTDM"
then
    pkg lightdm
    pkg lightdm-gtk-greeter
fi

if "$INSTALL_XFCE"
then
    grouppkg xfce4
    grouppkg xfce4-goodies
fi

if "$INSTALL_PRGANALYSIS_TOOLS"
then
    pkg aarch64-linux-gnu-binutils
    pkg aarch64-linux-gnu-gcc
    pkg aarch64-linux-gnu-gdb
    pkg aarch64-linux-gnu-glibc
    pkg aarch64-linux-gnu-linux-api-headers
    pkg aircrack-ng
    pkg ansible
    pkg ansible-lint
    pkg arduino-avr-core
    pkg arm-none-eabi-binutils
    pkg arm-none-eabi-gcc
    pkg arm-none-eabi-gdb
    pkg arm-none-eabi-newlib
    pkg binwalk
    pkg bochs
    pkg clinfo
    pkg codespell
    pkg cppcheck
    pkg docker-compose
    pkg earlyoom
    pkg flake8
    pkg ghidra
    pkg hashcat
    pkg hashcat-utils
    pkg hydra
    pkg impacket
    pkg ipcalc
    pkg ipv6calc
    pkg jre-openjdk
    pkg libnfc
    pkg libvirt
    #pkg lxc
    #pkg mariadb
    pkg maven
    pkg medusa
    pkg metasploit
    pkg openocd
    pkg perl-net-dns
    pkg php
    pkg php-sqlite
    pkg podman
    pkg python-argon2_cffi
    pkg python-gmpy2
    pkg python-kaitaistruct
    pkg python-keystone
    pkg python-lxml
    pkg python-matplotlib
    pkg python-numpy
    pkg python-passlib
    pkg python-pew
    pkg python-pillow
    pkg python-pipenv
    pkg python-pwntools
    pkg python-pycryptodome
    pkg python-pyelftools
    pkg python-pyflakes
    pkg python-pylint
    pkg python-pyopenssl
    pkg python-pyqtgraph
    pkg python-pyserial
    pkg python-pyusb
    pkg python-qrcode
    pkg python-requests
    pkg python-scapy
    pkg python-scipy
    pkg python-sphinx
    pkg python-sympy
    pkg python-unicorn
    pkg python-yaml
    pkg python-z3-solver
    pkg qemu
    pkg qemu-arch-extra
    pkg radare2
    pkg radare2-cutter
    pkg ropgadget
    pkg sagemath
    pkg samba
    pkg sleuthkit
    pkg smbnetfs
    pkg sshpass
    pkg upx
    pkg vagrant
    pkg volatility
    pkg wabt
    pkg zbar

    grouppkg texlive-most

    aurpkg android-apktool
    aurpkg arm-linux-gnueabihf-binutils
    aurpkg arm-linux-gnueabihf-gcc
    aurpkg arm-linux-gnueabihf-glibc
    aurpkg arm-linux-gnueabihf-linux-api-headers
    #aurpkg beignet  # For using OpenCL on some Intel iGPU
    aurpkg bluez-hcitool
    aurpkg bluez-rfcomm
    aurpkg coccinelle
    aurpkg dex2jar
    aurpkg ffdec
    aurpkg ilspymono-git
    aurpkg jd-gui
    aurpkg kaitai-struct-compiler
    aurpkg kaitai-struct-visualizer
    aurpkg lcov
    aurpkg libcgroup
    aurpkg msodbcsql
    aurpkg patator
    aurpkg pngcheck
    aurpkg proot
    aurpkg python-dlint
    aurpkg python-roca-detect
    aurpkg python-uncompyle6
    #aurpkg python-pwntools-git
    aurpkg pyzbar
    aurpkg sasquatch
    aurpkg selinux-python
    aurpkg setools
    aurpkg stegsolve
    aurpkg tpm-tools
    aurpkg uefitool-git
    aurpkg uefitool-ng-git

    # Humour
    aurpkg gti

    # Web analysis
    pkg sslscan
    pkg zaproxy
    aurpkg dirbuster
    aurpkg sslyze
    aurpkg wfuzz
fi


text:
package org.wso2.am.integration.tests.publisher;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.wso2.am.integration.clients.publisher.api.ApiException;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIListDTO;
import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest;
import org.wso2.am.integration.test.utils.bean.APICreationRequestBean;
import org.wso2.am.integration.test.utils.bean.APIRequest;
import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;

import javax.ws.rs.core.Response;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;

/**
 * Get all the APIs created through the publisher REST API
 * APIM-534 / APIM-542
 */

public class APIM534GetAllTheAPIsCreatedThroughThePublisherRestAPITestCase extends
        APIMIntegrationBaseTest {

    private static final Log log = LogFactory.
            getLog(APIM534GetAllTheAPIsCreatedThroughThePublisherRestAPITestCase.class);
    private static final String apiNameTest1 = "APIM534PublisherTest1";
    private static final String apiNameTest2 = "APIM534PublisherTest2";
    private static final String apiNameTest3 = "APIM534PublisherTest3";
    private static final String apiVersion = "1.0.0";
    private static String apiProviderName;
    private static String apiTest1EndPointUrl;
    private static String apiTest2EndPointUrl;
    private static String apiTest3EndPointUrl;
    private static String id;
    List<String> idList = new ArrayList<String>();

    @Factory(dataProvider = "userModeDataProvider")
    public APIM534GetAllTheAPIsCreatedThroughThePublisherRestAPITestCase(TestUserMode userMode) {
        this.userMode = userMode;
    }

    @DataProvider
    public static Object[][] userModeDataProvider() {
        return new Object[][]{
                new Object[]{TestUserMode.SUPER_TENANT_ADMIN},
//                new Object[]{TestUserMode.TENANT_ADMIN},
        };
    }

    @DataProvider(name = "createAPI")
    public static Object[][] createAppWithValidDataProvider() throws Exception {

        return new Object[][]{
                {apiNameTest1, "apim534PublisherTest1API", apiVersion, apiProviderName,
                        new URL(apiTest1EndPointUrl)},
                {apiNameTest2, "apim534PublisherTest2API", apiVersion, apiProviderName,
                        new URL(apiTest2EndPointUrl)},
                {apiNameTest3, "apim534PublisherTest3API", apiVersion, apiProviderName,
                        new URL(apiTest3EndPointUrl)}
        };
    }

    @BeforeClass(alwaysRun = true)
    public void setEnvironment() throws Exception {
        super.init(userMode);

        String apiTest1EndpointPostfixUrl = "jaxrs_basic/services/customers/" +
                "customerservice/customers/123";
        String apiTest2EndpointPostfixUrl = "name-check1/";
        String apiTest3EndpointPostfixUrl = "pizzashack-api-1.0.0/api/";

        String publisherURLHttp = publisherUrls.getWebAppURLHttp();

        apiTest1EndPointUrl = gatewayUrlsWrk.getWebAppURLHttp() + apiTest1EndpointPostfixUrl;
        apiTest2EndPointUrl = gatewayUrlsWrk.getWebAppURLHttp() + apiTest2EndpointPostfixUrl;
        apiTest3EndPointUrl = gatewayUrlsWrk.getWebAppURLHttp() + apiTest3EndpointPostfixUrl;

        apiProviderName = publisherContext.getContextTenant().getContextUser().getUserName();
    }

    @Test(dataProvider = "createAPI", description = "Create an API using valid data and get all " +
            "the API through Publisher Rest API")
    public void testGetAllTheAPICreatedThroughThePublisherRestAPI
            (String apiName, String context, String version, String provider,
             URL endpointUrl) throws Exception {

        APIRequest apiRequest = new APIRequest(apiName, context, endpointUrl);
        apiRequest.setVersion(version);
        HttpResponse apiCreationResponse = restAPIPublisher.addAPI(apiRequest);//(apiCreationRequestBean);
        id = apiCreationResponse.getData();
        assertEquals(apiCreationResponse.getResponseCode(), Response.Status.CREATED.getStatusCode(),
                "Response Code miss matched when creating the API");
        assertNotNull(id, "APIs are not created as expected");
        idList.add(id);

        HttpResponse resp = restAPIPublisher.getAPI(id);
        assertEquals(resp.getResponseCode(), Response.Status.OK.getStatusCode(), "API does not exist");
        //Create a API list with newly added APIs
        List<String> apiList = Arrays.asList(apiNameTest1, apiNameTest2, apiNameTest3);
        log.info("My API List :" + apiList);

        //Check the availability of API in Publisher
        Thread.sleep(5000);
        APIListDTO response = restAPIPublisher.getAllAPIs();
        JSONObject jsonObject = new JSONObject(response);
        JSONArray jsonArray = jsonObject.getJSONArray("list");
        List<String> allApiList = new ArrayList<String>();

        for (int i = 0; i < jsonArray.length(); i++) {
            String name = jsonArray.getJSONObject(i).getString("name");
            allApiList.add(name);
        }
        log.info("All API List :" + allApiList);

    }

    @Test(groups = {"wso2.am"}, description = "Validate if an API exists through the publisher " +
            "REST API", dependsOnMethods = "testGetAllTheAPICreatedThroughThePublisherRestAPI")
    public void testCheckIfAnAPIExistsThroughThePublisherRestAPI() throws Exception {

        //Trying to Create an API with an existing API Name
        APIRequest apiRequest = new APIRequest(apiNameTest1, "apim534PublisherTest1API", new URL(apiTest1EndPointUrl));
        apiRequest.setVersion(apiVersion);
        HttpResponse response = restAPIPublisher.addAPI(apiRequest);
        //response is null if addAPI fails with same api name
        assertNull("Added same api again", response);

    }

    @AfterClass(alwaysRun = true)
    public void destroyAPIs() throws Exception {
        for (String id : idList) {
            restAPIPublisher.deleteAPI(id);
        }
        super.cleanUp();
    }

}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.InfinityDependencies = void 0;

var _dependenciesBigNumberClass = require("./dependenciesBigNumberClass.generated");

var _factoriesAny = require("../../factoriesAny.js");

/**
 * THIS FILE IS AUTO-GENERATED
 * DON'T MAKE CHANGES HERE
 */
var InfinityDependencies = {
  BigNumberDependencies: _dependenciesBigNumberClass.BigNumberDependencies,
  createInfinity: _factoriesAny.createInfinity
};
exports.InfinityDependencies = InfinityDependencies;


text:
% This file is part of the RA package (http://github.com/davidssmith/ra).
%
% The MIT License (MIT)
%
% Copyright (c) 2015 David Smith
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% copies of the Software, and to permit persons to whom the Software is
% furnished to do so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% SOFTWARE.

function data = raread(filename)
fd = fopen(filename,'r');
h = getheader(fd);
ra_type_names = {'user','int','uint','float','complex'};
if h.eltype == 4 % complex float, which Matlab can't handle
    wascomplex = 1;
    h.elbyte = h.elbyte / 2;
    h.dims = [2; h.dims];
    h.eltype = 3;
else
    wascomplex = 0;
end
ratype = sprintf('%s%d',ra_type_names{h.eltype+1}, h.elbyte*8);
data = fread(fd, h.elbyte*prod(h.dims), ratype);
if ratype == 'float32'
    data = single(data);
end
if wascomplex
    tmp = complex(data(1:2:end), data(2:2:end));
    data = reshape(tmp, h.dims(2:end).');
else
    data = reshape(data, h.dims.');
end

function st = getheader(fd)
h = fread(fd, 6, 'uint64');
st = {};
st.flags = h(2);
st.eltype = h(3);
st.elbyte = h(4);
st.size = h(5);
st.ndims = h(6);
st.dims = fread(fd, st.ndims, 'uint64');


text:
package telegraf

import (
	"fmt"
	"sort"
	"strings"
	"sync"
	"time"

	"github.com/influxdb/influxdb/client"
)

// BatchPoints is used to send a batch of data in a single write from telegraf
// to influx
type BatchPoints struct {
	mu sync.Mutex

	client.BatchPoints

	Debug bool

	Prefix string

	Config *ConfiguredPlugin
}

// Add adds a measurement
func (bp *BatchPoints) Add(measurement string, val interface{}, tags map[string]string) {
	bp.mu.Lock()
	defer bp.mu.Unlock()

	measurement = bp.Prefix + measurement

	if bp.Config != nil {
		if !bp.Config.ShouldPass(measurement, tags) {
			return
		}
	}

	if bp.Debug {
		var tg []string

		for k, v := range tags {
			tg = append(tg, fmt.Sprintf("%s=\"%s\"", k, v))
		}

		sort.Strings(tg)

		fmt.Printf("> [%s] %s value=%v\n", strings.Join(tg, " "), measurement, val)
	}

	bp.Points = append(bp.Points, client.Point{
		Measurement: measurement,
		Tags:        tags,
		Fields: map[string]interface{}{
			"value": val,
		},
	})
}

// AddValuesWithTime adds a measurement with a provided timestamp
func (bp *BatchPoints) AddValuesWithTime(
	measurement string,
	values map[string]interface{},
	tags map[string]string,
	timestamp time.Time,
) {
	bp.mu.Lock()
	defer bp.mu.Unlock()

	measurement = bp.Prefix + measurement

	if bp.Config != nil {
		if !bp.Config.ShouldPass(measurement, tags) {
			return
		}
	}

	if bp.Debug {
		var tg []string

		for k, v := range tags {
			tg = append(tg, fmt.Sprintf("%s=\"%s\"", k, v))
		}

		var vals []string

		for k, v := range values {
			vals = append(vals, fmt.Sprintf("%s=%v", k, v))
		}

		sort.Strings(tg)
		sort.Strings(vals)

		fmt.Printf("> [%s] %s %s\n", strings.Join(tg, " "), measurement, strings.Join(vals, " "))
	}

	bp.Points = append(bp.Points, client.Point{
		Measurement: measurement,
		Tags:        tags,
		Fields:      values,
		Time:        timestamp,
	})
}


text:
/**
 * @file
 */
#pragma once

#include "src/expression/Expression.hpp"

namespace birch {
/**
 * Nil literal.
 *
 * @ingroup expression
 */
class Nil: public Expression {
public:
  /**
   * Constructor.
   *
   * @param loc Location.
   */
  Nil(Location* loc = nullptr);

  virtual void accept(Visitor* visitor) const;
};
}


text:
/**
 * Es6 module for React Component.
 * Section components combine modules and elements
 * to create a page section which could be easily
 * used in page components.
 *
 * @file
 * @module
 *
 * @author hello@ulrichmerkel.com (Ulrich Merkel), 2021
 */
import { default as React, FunctionComponent, ReactNode } from 'react';

import { SectionCommonGridSpaced } from './common/grid-spaced';
import { ModuleArticle } from '../module/article';
import { ModuleList } from '../module/list';

type Props = {
    children?: ReactNode;
    content: Record<string, unknown>;
    isDialog?: boolean;
    isMain?: boolean;
};

/**
 * Function representing a component to return a single react child element.
 *
 * @function
 * @param {object} [props] - The current component props
 * @param {Array|string} [props.children] - The component dom node childs - usually an array of components, if there is only a single child it's a string
 * @param {object} [props.content={}] - The content config input
 * @param {boolean} [props.isDialog=false] - Whether the component text should be displayed in a dialog or not
 * @param {boolean} [props.isMain=false] - Whether the component text should be displayed as main article or not
 * @returns {ReactElement} React component markup
 */
export const SectionList: FunctionComponent<Props> = (props) => {
    const { children, content, isDialog, isMain } = props;

    return (
        <SectionCommonGridSpaced>
            <ModuleArticle {...{ content, isMain, isDialog }}>
                <ModuleList {...{ content }}>{children}</ModuleList>
            </ModuleArticle>
        </SectionCommonGridSpaced>
    );
};


text:
$gradleVersion = $((Invoke-WebRequest https://services.gradle.org/versions/current | ConvertFrom-Json).version)
$sha = $(Invoke-RestMethod -Uri https://downloads.gradle.org/distributions/gradle-${gradleVersion}-bin.zip.sha256)

dir -Recurse -Filter Dockerfile | ForEach-Object {
    (Get-Content -Path $_.FullName) -replace "ENV GRADLE_VERSION .+$", "ENV GRADLE_VERSION ${gradleVersion}" | Set-Content $_.FullName
    (Get-Content -Path $_.FullName) -replace "GRADLE_DOWNLOAD_SHA256=.+$", "GRADLE_DOWNLOAD_SHA256=${sha}" | Set-Content $_.FullName
}
(Get-Content -Path .github/workflows/ci.yaml) -replace "expectedGradleVersion: .+", "expectedGradleVersion: ${gradleVersion}" | Set-Content .github/workflows/ci.yaml


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link type="application/atom+xml" rel="alternate" href="https://craftbyzen.com/feed.xml" title="Jeremy Wong" />

  <title>Flight Social Network</title>
  <meta name="description" content="Flight Social Network">

  <link rel="shortcut icon" type="image/x-icon" href="/assets/favicon.png">
  <link rel="stylesheet" href="/css/main.css">
  <link rel="canonical" href="https://craftbyzen.com/projects/flight-social-network">
  <link rel="alternate" type="application/rss+xml" title="Jeremy Wong" href="https://craftbyzen.com/feed.xml" />

            About

            Writing

                Codes

            Talks

            Logs

Flight Social Network

Flight is a social networking playground where users post their profiles and show their pictures.

Defunct - Website is down

Features

Users can create an account or log-in to do the following:

update their posts with text or pictures.

comment on anyone's status

create statuses (that no one else needs to comment on!)

be a friend to someone else, no limits!

Website

Flitr (sounds like 'Flirt') is hosted by Heroku and uses Amazon S3.

Contribute

Want to contribute to our efforts? Email Simon for details.

Questions?

You have questions, we have answers. Email Simon or Tweet at us and we'll get back to you.

License

Our team consists of Simon, Quy, Lienha, & Jeremy. This program is under an MIT License.

Images are under creative commons licenses.

      <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">

      Made With ❤

        © 2019 Craft By Zen


text:
param (
    [Parameter(Mandatory)]
    [ValidateSet('browse')]
    $cmd
    )

$ErrorActionPreference = 'stop'
$remoteOriginUrl = git config --get remote.origin.url
if (-not($remoteOriginUrl)) {
    Write-error "Not in a git repo. You stupid git"
}
$match =  $remoteOriginUrl | select-string -Pattern "^git@(?<host>[^\:]+)\:(?<user>[^\/]+)\/(?<repo>.+?)\.git$" | select -Expand Matches | select -first 1
if (-not($match)) {
    $match = $remoteOriginUrl | select-string -Pattern "^https://(?<host>[^\/]+)\/(?<user>[^\/]+)\/(?<repo>.+?)\.git$" | select -Expand Matches | select -first 1
}

if ($match) {
    $repo = $match.Groups['repo']
    $user = $match.Groups['user']
    $ihost = $match.Groups['host']
    $url = "https://$ihost/$user/$repo"
    start $url
} else {
    Write-error "Could not interpet remote.origin.url $remoteOriginUrl"
}


text:
/*
 * outlib.c
 *
 * Common routines for the output backends.
 */

#include "outlib.h"
#include "raa.h"

uint64_t realsize(enum out_type type, uint64_t size)
{
    switch (type) {
    case OUT_REL1ADR:
	return 1;
    case OUT_REL2ADR:
	return 2;
    case OUT_REL4ADR:
	return 4;
    case OUT_REL8ADR:
	return 8;
    default:
	return size;
    }
}

/* Common section/symbol handling */

struct ol_sect *_ol_sect_list;
uint64_t _ol_nsects;             /* True sections, not external symbols */
static struct ol_sect **ol_sect_tail = &_ol_sect_list;
static struct hash_table ol_secthash;
static struct RAA *ol_sect_index_tbl;

struct ol_sym *_ol_sym_list;
uint64_t _ol_nsyms;
static struct ol_sym **ol_sym_tail = &_ol_sym_list;
static struct hash_table ol_symhash;

void ol_init(void)
{
}

static void ol_free_symbols(void)
{
    struct ol_sym *s, *stmp;

    hash_free(&ol_symhash);

    list_for_each_safe(s, stmp, _ol_sym_list) {
        nasm_free((char *)s->name);
        nasm_free(s);
    }

    _ol_nsyms = 0;
    _ol_sym_list = NULL;
    ol_sym_tail = &_ol_sym_list;
}

static void ol_free_sections(void)
{
    struct ol_sect *s, *stmp;

    hash_free(&ol_secthash);
    raa_free(ol_sect_index_tbl);
    ol_sect_index_tbl = NULL;

    list_for_each_safe(s, stmp, _ol_sect_list) {
        saa_free(s->data);
        saa_free(s->reloc);
        nasm_free((char *)s->name);
        nasm_free(s);
    }

    _ol_nsects = 0;
    _ol_sect_list = NULL;
    ol_sect_tail = &_ol_sect_list;
}

void ol_cleanup(void)
{
    ol_free_symbols();
    ol_free_sections();
}

/*
 * Allocate a section index and add a section, subsection, or external
 * symbol to the section-by-index table. If the index provided is zero,
 * allocate a new index via seg_alloc().
 */
static uint32_t ol_seg_alloc(void *s, uint32_t ix)
{
    if (!ix)
        ix = seg_alloc();
    ol_sect_index_tbl = raa_write_ptr(ol_sect_index_tbl, ix >> 1, s);
    return ix;
}

/*
 * Find a section or create a new section structure if it does not exist
 * and allocate it an index value via seg_alloc().
 */
struct ol_sect *_ol_get_sect(const char *name, size_t ssize, size_t rsize)
{
    struct ol_sect *s, **sp;
    struct hash_insert hi;

    sp = (struct ol_sect **)hash_find(&ol_secthash, name, &hi);
    if (sp)
        return *sp;

    s             = nasm_zalloc(ssize);
    s->syml.tail  = &s->syml.head;
    s->name       = nasm_strdup(name);
    s->data       = saa_init(1);
    s->reloc      = saa_init(rsize);
    *ol_sect_tail = s;
    ol_sect_tail  = &s->next;
    _ol_nsects++;
    s->index     = s->subindex = ol_seg_alloc(s, 0);

    hash_add(&hi, s->name, s);
    return s;
}

/* Find a section by name without creating one */
struct ol_sect *_ol_sect_by_name(const char *name)
{
    struct ol_sect **sp;

    sp = (struct ol_sect **)hash_find(&ol_secthash, name, NULL);
    return sp ? *sp : NULL;
}

/* Find a section or external symbol by index; NULL if not valid */
struct ol_sect *_ol_sect_by_index(int32_t index)
{
    uint32_t ix = index;

    if (unlikely(ix >= SEG_ABS))
        return NULL;

    return raa_read_ptr(ol_sect_index_tbl, ix >> 1);
}

/*
 * Start a new subsection for the given section. At the moment, once a
 * subsection has been created, it is not possible to revert to an
 * earlier subsection. ol_sect_by_index() will return the main section
 * structure. Returns the new section index.  This is used to prevent
 * the front end from optimizing across subsection boundaries.
 */
int32_t _ol_new_subsection(struct ol_sect *sect)
{
    if (unlikely(!sect))
        return NO_SEG;

    return sect->subindex = ol_seg_alloc(sect, 0);
}

/*
 * Insert a symbol into a list; need to use upcasting using container_of()
 * to walk the list later.
 */
static void ol_add_sym_to(struct ol_symlist *syml, struct ol_symhead *head,
                          uint64_t offset)
{
    syml->tree.key = offset;
    head->tree     = rb_insert(head->tree, &syml->tree);
    *head->tail    = syml;
    head->tail     = &syml->next;
    head->n++;
}

/*
 * Create a location structure from seg:offs
 */
void ol_mkloc(struct ol_loc *loc, int64_t offs, int32_t seg)
{
    nasm_zero(*loc);
    loc->offs = offs;

    if (unlikely((uint32_t)seg >= SEG_ABS)) {
        if (likely(seg == NO_SEG)) {
            loc->seg.t     = OS_NOSEG;
        } else {
            loc->seg.t     = OS_ABS;
            loc->seg.index = seg - SEG_ABS;
        }
    } else {
        loc->seg.index  = seg & ~1;
        loc->seg.t      = OS_SECT | (seg & 1);
        loc->seg.s.sect = _ol_sect_by_index(loc->seg.index);
    }
}

/*
 * Create a new symbol. If this symbol is OS_OFFS, add it to the relevant
 * section, too. If the symbol already exists, return NULL; this is
 * different from ol_get_section() as a single section may be invoked
 * many times. On the contrary, the front end will prevent a single symbol
 * from being defined more than once.
 *
 * If flags has OF_GLOBAL set, add it to the global symbol hash for
 * the containing section if applicable.
 *
 * If flags has OF_IMPSEC set, allocate a segment index for it via
 * seg_alloc() unless v->index is already set, and add it to the
 * section by index list.
 */
struct ol_sym *_ol_new_sym(const char *name, const struct ol_loc *v,
                           uint32_t flags, size_t size)
{
    struct hash_insert hi;
    struct ol_sym *sym;

    if (hash_find(&ol_symhash, name, &hi))
        return NULL;            /* Symbol already exists */

    flags     |= OF_SYMBOL;

    sym        = nasm_zalloc(size);
    sym->name  = nasm_strdup(name);
    sym->v     = *v;

    if (sym->v.seg.t & OS_SECT) {
        struct ol_sect *sect = sym->v.seg.s.sect;

        if (!sect || (sect->flags & OF_SYMBOL))
            /* Must be an external or common reference */
            flags |= OF_IMPSEC;

        if (flags & OF_IMPSEC) {
            /* Metasection */
            if (!sym->v.seg.s.sym) {
                sym->v.seg.s.sym = sym;
                sym->v.seg.index = ol_seg_alloc(sym, sym->v.seg.index);
            }
        } else if (sym->v.seg.t == OS_OFFS) {
            struct ol_sect * const sect = sym->v.seg.s.sect;
            const uint64_t offs = sym->v.offs;

            ol_add_sym_to(&sym->syml, &sect->syml, offs);
            if (flags & OF_GLOBAL)
                ol_add_sym_to(&sym->symg, &sect->symg, offs);
        }
    }
    sym->flags = flags;

    *ol_sym_tail = sym;
    ol_sym_tail  = &sym->next;
    _ol_nsyms++;

    hash_add(&hi, sym->name, sym);
    return sym;
}

/* Find a symbol in the global namespace */
struct ol_sym *_ol_sym_by_name(const char *name)
{
    struct ol_sym **symp;

    symp = (struct ol_sym **)hash_find(&ol_symhash, name, NULL);
    return symp ? *symp : NULL;
}

/*
 * Find a symbol by address in a specific section. If no symbol is defined
 * at that exact address, return the immediately previously defined one.
 * If global is set, then only return global symbols.
 */
struct ol_sym *_ol_sym_by_address(struct ol_sect *sect, int64_t addr,
                                  bool global)
{
    struct ol_symhead *head;
    size_t t_offs;
    struct rbtree *t;

    if (global) {
        head = &sect->symg;
        t_offs = offsetof(struct ol_sym, symg.tree);
    } else {
        head = &sect->syml;
        t_offs = offsetof(struct ol_sym, syml.tree);
    }

    t = rb_search(head->tree, addr);
    if (!t)
        return NULL;

    return (struct ol_sym *)((char *)t - t_offs);
}


text:
class UuidifySubmissions < ActiveRecord::Migration
  extend Uuidable::Migration

  # The indexes here look odd but people query for study a lot (so they get to requests),
  # but project rarely, and so it's probably good just to stick that at the end.
  def self.up
    uuidify_table(
      :submissions, OnlyIndexes(
        [ :uuid, :is_current ],
        [ :study_uuid, :is_current, :project_uuid ]
      )
    )
  end
end


text:
static BOOL _blackWhite;
static BOOL _color;
static BOOL _duplex;

@implementation PrintersFilter

+(BOOL)setFilterWithBlackWhite:(BOOL)blackWhite color:(BOOL)color andDuplex:(BOOL)duplex {
    BOOL changed = _blackWhite != blackWhite || _color != color || _duplex != duplex;
    _blackWhite = blackWhite;
    _color = color;
    _duplex = duplex;
    return changed;
}

+(BOOL)blackWhite {
    return _blackWhite;
}

+(BOOL)color {
    return _color;
}

+(BOOL)duplex {
    return _duplex;
}

@end


text:
package uk.co.orangefoundry.tfl4j.line;

public enum Mode {

  BUS("bus"),TUBE("tube"),NATIONAL_RAIL("national-rail");

  private String name;

  Mode(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }
}


text:
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gnieh

import scala.collection.immutable.NumericRange

package object regex {

  type CharClass = NumericRange[Char]

  /** The non backtracking, VM implementation of regular expression. Import this object to use it. */
  object bytecode {

    implicit val impl = vm.BytecodeImpl

    implicit class RegexString(val string: String) extends AnyVal {

      def re: Regex =
        Regex(string)

    }

    implicit class RegexContext(val sc: StringContext) extends AnyVal {

      def re = sc.parts.mkString.re

    }

  }

  /** The TDFA implementation of regular expression. Import this object to use it. */
  object automaton {

    implicit val impl = tdfa.TDfaImpl

    implicit class RegexString(val string: String) extends AnyVal {

      def re: Regex =
        Regex(string)

    }

    implicit class RegexContext(val sc: StringContext) extends AnyVal {

      def re = sc.parts.mkString.re

    }

  }

  /** The standard library implementation. */
  object std {

    implicit class RegexString(val string: String) extends AnyVal {

      def re = string.r

    }

    implicit class RegexContext(val sc: StringContext) extends AnyVal {

      def re = sc.parts.mkString.r

    }

  }

}


text:
//
//  CDTQQuerySqlTranslator.h
//
//  Created by Michael Rhodes on 03/10/2014.
//  Copyright (c) 2014 Cloudant. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
//  except in compliance with the License. You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//  Unless required by applicable law or agreed to in writing, software distributed under the
//  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
//  either express or implied. See the License for the specific language governing permissions
//  and limitations under the License.

#import <Foundation/Foundation.h>

@class CDTQSqlParts;

@interface CDTQQueryNode : NSObject

@end

@interface CDTQChildrenQueryNode : CDTQQueryNode

@property (nonatomic, strong) NSMutableArray *children;

@end

@interface CDTQAndQueryNode : CDTQChildrenQueryNode

@end

@interface CDTQOrQueryNode : CDTQChildrenQueryNode

@end

@interface CDTQSqlQueryNode : CDTQQueryNode

@property (nonatomic, strong) CDTQSqlParts *sql;

@end

/**
 This class translates Cloudant Query selectors into the SQL we need to use
 to query our indexes.

 It creates a tree structure which contains AND/OR nodes, along with the SQL which
 needs to be used to get a list of document IDs for each level. This tree structure
 is passed back out of the translation process for execution by an interpreter which
 can perform the needed AND and OR operations between the document ID sets returned
 by the SQL queries.

 This merging of results in code allows use to make more intelligent use of indexes
 within the SQLite database. As SQLite allows us to use just a single index per query,
 performing several queries over indexes and then using set operations works out
 more flexible and likely more efficient.

 The SQL must be executed separately so we can do it in a transaction so we're doing
 it over a consistent view of the index.

 The translator is a simple depth-first, recursive decent parser over the selector
 dictionary.

 Some examples:

 AND : [ { x: X }, { y: Y } ]

 This can be represented by a single SQL query and AND tree node:

    AND
     |
    sql

 OR : [ { x: X }, { y: Y } ]

 This is a single OR node and two SQL queries:

       OR
       / \
     sql  sql

 The interpreter then unions the results.

 OR : [ { AND : [ { x: X }, { y: Y } ] }, { y: Y } ]

 This requires a more complex tree:

          OR
         /   \
       AND    sql
        |
       sql

 We could collapse out the extra AND node.

 AND : [ { OR : [ { x: X }, { y: Y } ] }, { y: Y } ]

 This is really the most complex situation:

         AND
         /  \
       OR   sql
      / |
    sql sql

 These basic patterns can be composed into more complicate structures.
 */
@interface CDTQQuerySqlTranslator : NSObject

+ (CDTQQueryNode *)translateQuery:(NSDictionary *)query
                     toUseIndexes:(NSDictionary *)indexes
                indexesCoverQuery:(BOOL *)indexesCoverQuery;

/**
 Expand implicit operators in a query.
 */
//+ (NSDictionary *)normaliseQuery:(NSDictionary *)query;

/**
 Extract fields from an AND clause

 `fieldName` and so on from:

 ```
 @[@{@"fieldName": @"mike"}, ...]
 ```
 */
+ (NSArray *)fieldsForAndClause:(NSArray *)clause;

/**
 Checks for the existence of an operator in a query clause array
*/
+ (BOOL)isOperator:(NSString *)operator inClause:(NSArray *)clause;

/**
 Selects an index to use for a given query from the set provided.

 Here we're looking for the index which supports all the fields used in the query.

 @param query full query provided by user.
 @param indexes index list of the form @{indexName: @[fieldName1, fieldName2]}
 @return name of index from `indexes` to ues for `query`, or `nil` if none found.
 */
+ (NSString *)chooseIndexForAndClause:(NSArray *)clause fromIndexes:(NSDictionary *)indexes;

/**
 Selects an index to use for a set of fields.
 */
+ (NSString *)chooseIndexForFields:(NSSet *)neededFields fromIndexes:(NSDictionary *)indexes;

/**
 Returns the SQL WHERE clause for a query.
 */
+ (CDTQSqlParts *)wherePartsForAndClause:(NSArray *)clause usingIndex:(NSString *)indexName;

/**
 Returns the SQL statement to find document IDs matching query.

 @param query the query being executed.
 @param indexName the index selected for use in this query
 */
+ (CDTQSqlParts *)selectStatementForAndClause:(NSArray *)clause usingIndex:(NSString *)indexName;

@end


text:
#ifndef DocumentResourceReference_h
#define DocumentResourceReference_h

#include "core/fetch/DocumentResource.h"
#include "core/fetch/ResourcePtr.h"

namespace WebCore {

class DocumentResourceReference : public DocumentResourceClient {
public:
    DocumentResourceReference(DocumentResource* document) : m_document(document) { m_document->addClient(this); }
    virtual ~DocumentResourceReference() { m_document->removeClient(this); }
    DocumentResource* document() { return m_document.get(); }
private:
    ResourcePtr<DocumentResource> m_document;
};

};

#endif


text:
<?php

namespace Benkle\Feeding\Standards\RSS;

use Benkle\Feeding\Interfaces\StandardInterface;

class RSS20StandardTest extends \PHPUnit_Framework_TestCase
{

    public function testNewStandard()
    {
        $standard = new RSS20Standard();
        $this->assertInstanceOf(StandardInterface::class, $standard);
    }

    public function testCanHandleDOMWithProperVersion()
    {
        $standard = new RSS20Standard();
        $dom = new \DOMDocument();
        $root = $dom->createElement('rss');
        $version = $dom->createAttribute('version');
        $root->appendChild($version);
        $dom->appendChild($root);

        $versionMap = [
            '0.9'   => false,
            '0.8'   => false,
            '0.80'  => false,
            '0.90'  => false,
            '0.91'  => false,
            '0.92'  => false,
            '0.99'  => false,
            '1.0'   => false,
            '2.0'   => true,
            '2.0.1' => true,
            '2.01'  => true,
            '2.1'   => false,
        ];

        foreach ($versionMap as $versionNr => $canHandle) {
            $version->nodeValue = $versionNr;
            $this->assertEquals($canHandle, $standard->canHandle($dom));
        }
    }

}


text:
"use strict";

/**

 * Module dependencies

 */

var nodemailer = require('nodemailer');
var mailer_config = require('../../config/mailer.json');
var site_config = require('../../config/site_config.json');
var winston = require('winston');

/*
* Sends mail basing on the options retrieved from the mailer_config file (config/mailer.json) and the provided parameters.
* Uses Gmail as email proxy.
*
* @receiver
* @subject
* @text
* @html
*
*/
module.exports.genericMailer = function(receiver, subject, text, html){
  var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
      user: mailer_config.user,
      pass: mailer_config.password
    }
  });

  if(site_config.enable_emails === true){
    var mailOptions = {
      from: 'Equipo Comet ✔ <'+mailer_config.user+'>', // sender address
      to: receiver, // list of receivers
      subject: subject, // Subject line
      text: text, // plaintext body
      html: html // html body
    };

    transporter.sendMail(mailOptions, function(error, info){
      if(error){
        return winston.info(error);
      }
        winston.info('Message sent: ' + info.response);
      });
  } else {
    winston.info('Mails not enabled by config file.');
  }
};


text:
package com.intellij.testFramework;

import com.intellij.analysis.AnalysisScope;
import com.intellij.codeInsight.daemon.HighlightDisplayKey;
import com.intellij.codeInspection.InspectionEP;
import com.intellij.codeInspection.InspectionProfileEntry;
import com.intellij.codeInspection.LocalInspectionEP;
import com.intellij.codeInspection.ex.GlobalInspectionContextImpl;
import com.intellij.codeInspection.ex.InspectionToolWrapper;
import com.intellij.codeInspection.ui.InspectionToolPresentation;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.testFramework.fixtures.impl.GlobalInspectionContextForTests;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.JBIterable;
import com.intellij.util.ui.UIUtil;
import org.jdom.Document;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;
import org.junit.Assert;

import java.io.CharArrayReader;
import java.io.File;
import java.io.StreamTokenizer;
import java.util.*;

public class InspectionTestUtil {
  private InspectionTestUtil() {
  }

  protected static void compareWithExpected(Document expectedDoc, Document doc, boolean checkRange) throws Exception {
    List<Element> expectedProblems = new ArrayList<>(expectedDoc.getRootElement().getChildren("problem"));
    List<Element> reportedProblems = new ArrayList<>(doc.getRootElement().getChildren("problem"));

    Element[] expectedArray = expectedProblems.toArray(new Element[expectedProblems.size()]);
    boolean failed = false;

    expected:
    for (Element expectedProblem : expectedArray) {
      Element[] reportedArrayed = reportedProblems.toArray(new Element[reportedProblems.size()]);
      for (Element reportedProblem : reportedArrayed) {
        if (compareProblemWithExpected(reportedProblem, expectedProblem, checkRange)) {
          expectedProblems.remove(expectedProblem);
          reportedProblems.remove(reportedProblem);
          continue expected;
        }
      }

      Document missing = new Document(expectedProblem.clone());
      System.out.println("The following haven't been reported as expected: " + JDOMUtil.writeDocument(missing, "\n"));
      failed = true;
    }

    for (Element reportedProblem : reportedProblems) {
      Document extra = new Document(reportedProblem.clone());
      System.out.println("The following has been unexpectedly reported: " + JDOMUtil.writeDocument(extra, "\n"));
      failed = true;
    }

    Assert.assertFalse(failed);
  }

  static boolean compareProblemWithExpected(Element reportedProblem, Element expectedProblem, boolean checkRange) throws Exception {
    if (!compareFiles(reportedProblem, expectedProblem)) return false;
    if (!compareLines(reportedProblem, expectedProblem)) return false;
    if (!compareDescriptions(reportedProblem, expectedProblem)) return false;
    if (checkRange && !compareTextRange(reportedProblem, expectedProblem)) return false;
    return true;
  }

  static boolean compareTextRange(final Element reportedProblem, final Element expectedProblem) {
    Element reportedTextRange = reportedProblem.getChild("entry_point");
    if (reportedTextRange == null) return false;
    Element expectedTextRange = expectedProblem.getChild("entry_point");
    return Comparing.equal(reportedTextRange.getAttributeValue("TYPE"), expectedTextRange.getAttributeValue("TYPE")) &&
           Comparing.equal(reportedTextRange.getAttributeValue("FQNAME"), expectedTextRange.getAttributeValue("FQNAME"));
  }

  static boolean compareDescriptions(Element reportedProblem, Element expectedProblem) throws Exception {
    String expectedDescription = expectedProblem.getChildText("description");
    String reportedDescription = reportedProblem.getChildText("description");
    if (expectedDescription.equals(reportedDescription)) return true;

    StreamTokenizer tokenizer = new StreamTokenizer(new CharArrayReader(expectedDescription.toCharArray()));
    tokenizer.quoteChar('\'');

    int idx = 0;
    while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
      String word;
      if (tokenizer.sval != null) {
        word = tokenizer.sval;
      } else if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
        word = Double.toString(tokenizer.nval);
      }
      else {
        continue;
      }

      idx = reportedDescription.indexOf(word, idx);
      if (idx == -1) return false;
      idx += word.length();
    }

    return true;
  }

  static boolean compareLines(Element reportedProblem, Element expectedProblem) {
    return Comparing.equal(reportedProblem.getChildText("line"), expectedProblem.getChildText("line"));
  }

  static boolean compareFiles(Element reportedProblem, Element expectedProblem) {
    String reportedFileName = reportedProblem.getChildText("file");
    if (reportedFileName == null) {
      return true;
    }
    File reportedFile = new File(reportedFileName);

    return Comparing.equal(reportedFile.getName(), expectedProblem.getChildText("file"));
  }

  public static void compareToolResults(@NotNull GlobalInspectionContextImpl context,
                                        @NotNull InspectionToolWrapper toolWrapper,
                                        boolean checkRange,
                                        @NotNull String testDir) {
    compareToolResults(context, checkRange, testDir, Collections.singletonList(toolWrapper));
  }

  static void compareToolResults(@NotNull GlobalInspectionContextImpl context,
                                 boolean checkRange,
                                 @NotNull String testDir,
                                 @NotNull Collection<? extends InspectionToolWrapper> toolWrappers) {
    final Element root = new Element("problems");

    for (InspectionToolWrapper toolWrapper : toolWrappers) {
      InspectionToolPresentation presentation = context.getPresentation(toolWrapper);
      presentation.updateContent();  //e.g. dead code need check for reachables
      presentation.exportResults(root, x -> false, x -> false);
    }

    try {
      File file = new File(testDir + "/expected.xml");
      compareWithExpected(JDOMUtil.loadDocument(file), new Document(root), checkRange);
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  @TestOnly
  public static void runTool(@NotNull InspectionToolWrapper toolWrapper,
                             @NotNull final AnalysisScope scope,
                             @NotNull final GlobalInspectionContextForTests globalContext) {
    final String shortName = toolWrapper.getShortName();
    final HighlightDisplayKey key = HighlightDisplayKey.find(shortName);
    if (key == null){
      HighlightDisplayKey.register(shortName);
    }

    globalContext.doInspections(scope);
    do {
      UIUtil.dispatchAllInvocationEvents();
    }
    while (!globalContext.isFinished());
  }

  @NotNull
  public static <T extends InspectionProfileEntry> List<InspectionProfileEntry> instantiateTools(@NotNull Collection<Class<? extends T>> inspections) {
    Set<String> classNames = JBIterable.from(inspections).transform(Class::getName).toSet();
    List<InspectionProfileEntry> tools = JBIterable.of(LocalInspectionEP.LOCAL_INSPECTION, InspectionEP.GLOBAL_INSPECTION)
      .flatten((o) -> Arrays.asList(o.getExtensions()))
      .filter((o) -> classNames.contains(o.implementationClass))
      .transform(InspectionEP::instantiateTool)
      .toList();
    if (tools.size() != classNames.size()) {
      Set<String> missing = ContainerUtil.newTreeSet(classNames);
      missing.removeAll(JBIterable.from(tools).transform((o) -> o.getClass().getName()).toSet());
      throw new RuntimeException("Unregistered inspections requested: " + missing);
    }
    return tools;
  }
}


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/Sample_Ocean.dir/src/OceanDemo.cpp.o"
  "CMakeFiles/Sample_Ocean.dir/src/MaterialControls.cpp.o"
  "../../lib/Sample_Ocean.pdb"
  "../../lib/Sample_Ocean.so"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/Sample_Ocean.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
using UnityEngine;
using System.Collections;
using Leap;

/**
 * A hand object consisting of discrete, component parts.
 *
 * The hand can have game objects for the palm, wrist and forearm, as well as fingers.
 */
public class SkeletalHand : HandModel {

  protected const float PALM_CENTER_OFFSET = 0.0150f;

  void Start() {
    // Ignore collisions with self.
    Leap.Utils.IgnoreCollisions(gameObject, gameObject);

    for (int i = 0; i < fingers.Length; ++i) {
      if (fingers[i] != null) {
        fingers[i].fingerType = (Finger.FingerType)i;
      }
    }
  }

  /** Updates the hand and its component parts by setting their positions and rotations. */
  public override void UpdateHand() {
    SetPositions();
  }

  protected Vector3 GetPalmCenter() {
    Vector3 offset = PALM_CENTER_OFFSET * Vector3.Scale(GetPalmDirection(), transform.localScale);
    return GetPalmPosition() - offset;
  }

  protected void SetPositions() {
    for (int f = 0; f < fingers.Length; ++f) {
      if (fingers[f] != null)
        fingers[f].UpdateFinger();
    }

    if (palm != null) {
      palm.position = GetPalmCenter();
      palm.rotation = GetPalmRotation();
    }

    if (wristJoint != null) {
      wristJoint.position = GetWristPosition();
      wristJoint.rotation = GetPalmRotation();
    }

    if (forearm != null) {
      forearm.position = GetArmCenter();
      forearm.rotation = GetArmRotation();
    }
  }
}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 12.2.1-2-s
description: >
    eval - a function assigning into 'eval' throws SyntaxError in
    strict mode
flags: [onlyStrict]
---*/

assert.throws(SyntaxError, function() {
    eval('function foo() { eval = 42; }; foo()');
});