Пример #1
0
        public void Remove()
        {
            MultiDictionary<string, string> dictionary = new MultiDictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            dictionary.Add("x", "x1");
            dictionary.Add("x", "x2");
            dictionary.Add("y", "y1");

            Assert.Equal(true, dictionary.Remove("x", "x1"));

            Assert.Equal(2, dictionary.KeyCount);
            Assert.Equal(2, dictionary.ValueCount);

            Assert.Equal(true, dictionary.Remove("x", "x2"));

            Assert.Equal(1, dictionary.KeyCount);
            Assert.Equal(1, dictionary.ValueCount);

            Assert.Equal(true, dictionary.Remove("y", "y1"));

            Assert.Equal(0, dictionary.KeyCount);
            Assert.Equal(0, dictionary.ValueCount);

            dictionary.Add("x", "x1");
            dictionary.Add("x", "x2");

            Assert.Equal(true, dictionary.Remove("x", "x2"));

            Assert.Equal(1, dictionary.KeyCount);
            Assert.Equal(1, dictionary.ValueCount);
        }
Пример #2
0
        public ParseResult ParseArgs(string[] args)
        {
            MultiDictionary<string, string> parsedArguments = new MultiDictionary<string, string>();
            ExecutionLog errorLog = ExecutionLog.CreateErrorLog();

            for (int i = 0; i < args.Length; ++i)
            {
                string currentArg = args[i];
                Match match = argRegex.Match(currentArg);
                if (match.Success)
                {
                    if (match.Groups.Count == 3)
                    {
                        if (string.IsNullOrEmpty(match.Groups[2].Value))
                        {
                            // Special case for the --help string.
                            // TODO(ruibm): Potentially just support args with zero arguments.
                            if (currentArg == "--help")
                            {
                                parsedArguments.Add(match.Groups[1].Value, true.ToString());
                            }
                            // The value must come after the space in the next args position.
                            else if (i + 1 >= args.Length)
                            {
                                errorLog.Add("Argument [{0}] is not set to a value.", currentArg);
                            }
                            else
                            {
                                parsedArguments.Add(match.Groups[1].Value, args[++i]);
                            }
                        }
                        else
                        {
                            // The current Arg is contains both key and value separated by '='.
                            parsedArguments.Add(match.Groups[1].Value, match.Groups[2].Value);
                        }
                    }
                    else
                    {
                        Assertions.Fail(
                            "Invalid parsed argument [{0}]. The group count was [{1}].",
                            currentArg,
                            match.Groups.Count);
                    }
                }
                else
                {
                    errorLog.Add("Unparseable argument [{0}].", currentArg);
                }
            }

            return new ParseResult(errorLog.Count == 0, parsedArguments, errorLog);
        }
Пример #3
0
        public IndexedArgInstances(List<ArgInstance> instances)
        {
            _mandatoryFullNames = new HashSet<string>();
            _argInstancesByName = new MultiDictionary<string, ArgInstance>();
            HashSet<string> tempNames = new HashSet<string>();

            foreach (ArgInstance currentInstance in instances)
            {
                if (currentInstance.Arg.IsMandatory)
                {
                    _mandatoryFullNames.Add(currentInstance.FullName);
                }
                tempNames.Clear();
                tempNames.Add(currentInstance.Name);
                tempNames.Add(currentInstance.FullName);
                if (currentInstance.ShortName != null)
                {
                    tempNames.Add(currentInstance.ShortName);
                }

                foreach (string name in tempNames)
                {
                    _argInstancesByName.Add(name, currentInstance);
                }
            }
        }
        internal WithPrimaryConstructorParametersBinder(MethodSymbol primaryCtor, Binder next)
            : base(next)
        {
            Debug.Assert((object)primaryCtor != null);
            this.primaryCtor = primaryCtor;
            var parameters = primaryCtor.Parameters;

            var definitionMap = new SmallDictionary<string, ParameterSymbol>();

            for (int i = parameters.Length - 1; i >= 0; i--)
            {
                var parameter = parameters[i];
                definitionMap[parameter.Name] = parameter;
            }

            this.definitionMap = definitionMap;

            var parameterMap = new MultiDictionary<string, ParameterSymbol>(parameters.Length, EqualityComparer<string>.Default);

            foreach (var parameter in parameters)
            {
                parameterMap.Add(parameter.Name, parameter);
            }

            this.parameterMap = parameterMap;
        }
Пример #5
0
        private static void ReadContactsFromFile(string file, MultiDictionary<string, string> contactsName, MultiDictionary<string, string> contactsTown)
        {
            StreamReader reader = new StreamReader(file);
            string line = reader.ReadLine();

            using (reader)
            {
                while (line != null)
                {
                    var details = line.Split('|');
                    string names = details[0].Trim();
                    string town = details[1].Trim();
                    string phone = details[2].Trim();

                    contactsTown.Add(town, phone);

                    var namesSeparated = names.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var name in namesSeparated)
                    {
                        contactsName.Add(name, phone);
                    }

                    line = reader.ReadLine();
                }
            }
        }
 private static void AddEvent(string command)
 {
     var currentEvent = new Event(DateTime.Now, "title", "location");
     ///GetParameters(command, "AddEvent", out date, out title, out location);
     var events = new MultiDictionary<string, Event>(true);  ///added that to make it stop crashing too
     events.Add("title", currentEvent);
 }
Пример #7
0
        protected FastInvokerBase(Type type)
        {
            ObjectType = type;

            MethodNameCache = new MultiDictionary<string, MethodInfo>(false);

            type.GetMethods(_methodBindingFlags).Each(method => MethodNameCache.Add(method.Name, method));
        }
Пример #8
0
 public ParseResult CreateParseResult(bool successfull, params string[] keyValues)
 {
     MultiDictionary<string, string> parsedValues = new MultiDictionary<string, string>();
     for (int i = 0; i < keyValues.Length / 2; ++i)
     {
         parsedValues.Add(keyValues[i * 2], keyValues[i * 2 + 1]);
     }
     return new ParseResult(successfull, parsedValues, ExecutionLog.CreateErrorLog());
 }
 public WithQueryLambdaParametersBinder(LambdaSymbol lambdaSymbol, RangeVariableMap rangeVariableMap, Binder next)
     : base(lambdaSymbol, next)
 {
     _rangeVariableMap = rangeVariableMap;
     _parameterMap = new MultiDictionary<string, RangeVariableSymbol>();
     foreach (var qv in rangeVariableMap.Keys)
     {
         _parameterMap.Add(qv.Name, qv);
     }
 }
Пример #10
0
 public IEnumerable<string> GetIdentityMembership(string username)
 {
     if (_membership == null)
     {
         _membership = new MultiDictionary<string, string>();
         foreach (var pair in _userGroupMembership.Split(' '))
             _membership.Add(System.Environment.UserDomainName + @"\" + pair.Split('-')[0], pair.Split('-')[1]);
     }
     return _membership.Get(username).ToList();
 }
Пример #11
0
        /// <summary>
        /// Modifies the graph by adding dependencies corresponding to language rules that apply in a looser 
        /// sense: TRUE forms depend on NEXT forms and DOES forms depend on LEGAL forms.
        /// </summary>
        private static MultiDictionary<ISentenceForm, ISentenceForm> AugmentGraphWithLanguageRules(
            MultiDictionary<ISentenceForm, ISentenceForm> dependencyGraph, ICollection<ISentenceForm> sentenceForms)
        {
            var newGraph = new MultiDictionary<ISentenceForm, ISentenceForm>(true);
            foreach (KeyValuePair<ISentenceForm, ICollection<ISentenceForm>> kv in dependencyGraph)
                newGraph[kv.Key] = kv.Value;

            foreach (ISentenceForm form in sentenceForms)
            {
                if (form.Name == GameContainer.Parser.TokTrue)
                {
                    ISentenceForm nextForm = form.WithName(GameContainer.Parser.TokNext);
                    if (sentenceForms.Contains(nextForm))
                        newGraph.Add(form, nextForm);
                }
                else if (form.Name == GameContainer.Parser.TokDoes)
                {
                    ISentenceForm legalForm = form.WithName(GameContainer.Parser.TokLegal);
                    if (sentenceForms.Contains(legalForm))
                        newGraph.Add(form, legalForm);
                }
            }
            return newGraph;
        }
Пример #12
0
        private static MultiDictionary<string, MultiDictionary<string, string>> FillPhoneBook()
        {
            const string PhonesPath = "phones.txt";

            StreamReader phonesReader = new StreamReader(PhonesPath);

            var phoneBook = new MultiDictionary<string, MultiDictionary<string, string>>(true);

            using (phonesReader)
            {
                string line = phonesReader.ReadLine();

                while (line != null)
                {
                    var splittedEntry = line.Split('|');

                    string name = splittedEntry[0].Trim();
                    string town = splittedEntry[1].Trim();
                    string phoneNumber = splittedEntry[2].Trim();

                    if (phoneBook.ContainsKey(name))
                    {
                        var nameInPhoneBook = phoneBook[name].First();

                        if (nameInPhoneBook.ContainsKey(town))
                        {
                            nameInPhoneBook[town].Add(phoneNumber);
                        }
                        else
                        {
                            nameInPhoneBook.Add(town, phoneNumber);
                        }
                    }
                    else
                    {
                        phoneBook.Add(name, new MultiDictionary<string, string>(true));
                        var nameInPhoneBook = phoneBook[name].First();
                        nameInPhoneBook.Add(town, phoneNumber);
                    }

                    line = phonesReader.ReadLine();
                }

                return phoneBook;
            }
        }
Пример #13
0
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader("phones.txt", Encoding.GetEncoding("windows-1251"));
            StreamReader commands = new StreamReader("commands.txt", Encoding.GetEncoding("windows-1251"));
            using (reader)
            {
                using (commands)
                {
                    char[] separator = { '|','\n', '\r'};
                    MultiDictionary<Tuple<string, string>, string> phonesFile = new MultiDictionary<Tuple<string, string>, string>(true);
                    string text = reader.ReadToEnd();

                    string[] parts = text.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                    TrimTheParts(parts);

                    for (int i = 0; i < parts.Length; i += 3)
                    {
                        phonesFile.Add(new Tuple<string, string>(parts[i], parts[i + 1]), parts[i + 2]);
                    }

                    Console.WriteLine("Only by name----------------------------");
                    var peopleByName = phonesFile.FindAll(key => key.Key.Item1 == "Moro");
                    foreach (var people in peopleByName)
                    {
                        Console.WriteLine(people);
                    }
                    Console.WriteLine("By name and town----------------------------");

                    var peopleByNameAndTown = phonesFile.FindAll(key => key.Key.Item1 == "Kireto" && key.Key.Item2 == "Varna");
                    foreach (var people  in peopleByNameAndTown)
                    {
                        Console.WriteLine(people);
                    }

                    Console.WriteLine("Only by name but diferent towns----------------------------");
                    var peopleByNameDifTowns = phonesFile.FindAll(key => key.Key.Item1 == "Kireto");
                    foreach (var people in peopleByNameDifTowns)
                    {
                        Console.WriteLine(people);
                    }
                }

            }
        }
Пример #14
0
        public PhoneBook(List<PhoneEntry> entries)
        {
            firstNames = new MultiDictionary<string, PhoneEntry>(true);
            middleNames = new MultiDictionary<string, PhoneEntry>(true);
            lastNames = new MultiDictionary<string, PhoneEntry>(true);
            towns = new MultiDictionary<string, PhoneEntry>(true);

            foreach (var entry in entries)
            {
                firstNames.Add(new KeyValuePair<string,
                    ICollection<PhoneEntry>>(entry.FirstName, new PhoneEntry[] { entry }));
                middleNames.Add(new KeyValuePair<string,
                    ICollection<PhoneEntry>>(entry.MiddleName, new PhoneEntry[] { entry }));
                lastNames.Add(new KeyValuePair<string,
                    ICollection<PhoneEntry>>(entry.LastName, new PhoneEntry[] { entry }));
                towns.Add(new KeyValuePair<string,
                    ICollection<PhoneEntry>>(entry.Town, new PhoneEntry[] { entry }));
            }
        }
    private StepDataRequirements()
    {
        requirements = new MultiDictionary<string, string>();

        // Get resource file
        string path = Application.dataPath + filePath;
        XmlDocument doc = new XmlDocument();
        doc.Load(path);

        XmlNode root = doc.DocumentElement;

        foreach(XmlNode current in root.ChildNodes)
        {
          string key = current.LocalName;
          foreach (XmlNode val in current.ChildNodes)
          {
        requirements.Add(key, val.Value);
          }
        }
    }
Пример #16
0
        public static SimulationPath <A, S> RunSimulation(PDA <A, S> dpda, A[] word, AcceptanceCondition acceptanceCondition, CancellationToken token)
        {
            Assertion.Assert(dpda.Deterministic, "The given PDA is not deterministic");

            var path = new List <Node <A, S> >()
            {
                Node <A, S> .InitialNode(
                    new Configuration <A, S>(dpda.InitialState,
                                             new Word <A>(word),
                                             new CurrentStack <S>(new List <S>()
                {
                    dpda.FirstStackSymbol
                })))
            };

            var configAccepts = acceptanceCondition.IsFinalState() ?
                                new Func <Configuration <A, S>, bool>(config => config.State.Final)
                : new Func <Configuration <A, S>, bool>(config => config.Stack.IsEmpty());

            var potentialCircleStartsWithMinStackSoFar = new MultiDictionary <int, NodeWithMinimumStackHeightAfterIt>();

            potentialCircleStartsWithMinStackSoFar.Add(dpda.InitialState.Id,
                                                       new NodeWithMinimumStackHeightAfterIt(path.Last(), path.Last().Config.Stack.StackSymbols.Count()));

            while (!(path.Last().Config.RemainingWord.IsEmpty() && configAccepts(path.Last().Config)))
            {
                token.ThrowIfCancellationRequested();

                var enterableTransitions = path.Last().Config.GetEnterableTransitions();

                Assertion.Assert(enterableTransitions.Count() <= 1, "The given PDA is not deterministic - fatal error");

                if (enterableTransitions.Count() == 0)
                {
                    return(new SimulationPath <A, S>(path, noTransitionMessage));
                }

                path.Add(Node <A, S> .ApplyTransitionToParentNode(enterableTransitions.First(), path.Last()));

                if (enterableTransitions.First().SymbolIn.IsEmpty())
                {
                    if (EndlessCircleWasPassed(potentialCircleStartsWithMinStackSoFar, path.Last()))
                    {
                        return(new SimulationPath <A, S>(path, endlessCircleMessage));
                    }

                    var currentNode = path.Last();

                    var currentStackHeight = currentNode.Config.Stack.StackSymbols.Count();
                    potentialCircleStartsWithMinStackSoFar.Add(currentNode.Config.State.Id,
                                                               new NodeWithMinimumStackHeightAfterIt(currentNode, currentStackHeight));

                    foreach (var n in potentialCircleStartsWithMinStackSoFar.Values)
                    {
                        n.MinimumStackHeightAfterIt = Math.Min(n.MinimumStackHeightAfterIt, currentStackHeight);
                    }
                }
                else
                {
                    potentialCircleStartsWithMinStackSoFar = new MultiDictionary <int, NodeWithMinimumStackHeightAfterIt>();
                }
            }
            return(new SimulationPath <A, S>(path));
        }
Пример #17
0
        /// <summary>
        /// Processes the IO.
        /// </summary>
        /// <param name="componentTemplateIODictionary">The io dictionary of either Inputs of Outputs of the component template.</param>
        /// <param name="settings">input or output settings for the composite component that is being defined</param>
        /// <param name="benchmarkMappingSettingsCollection">The benchmark setting collection .</param>
        private static void ProcessIO(IDictionary<string, IOItem> componentTemplateIODictionary, SortedDictionary<string, ItemSetting> settings, BenchmarkSettingCollection<IOItem> benchmarkMappingSettingsCollection)
        {
            MultiDictionary<string, ItemSetting> lookupByType = new MultiDictionary<string, ItemSetting>();

            //first prepare lookup by type 
            foreach (KeyValuePair<string, ItemSetting> pair in settings)
            {
                ItemSetting item = pair.Value;
                //as default don't include it
                item.Include = false;
                lookupByType.Add(item.Type, item);
            }

            foreach (string itemKey in componentTemplateIODictionary.Keys)
            {
                IOItem item = componentTemplateIODictionary[itemKey];

                //check if there are any item settings with matching type
                IEnumerable<ItemSetting> matchingItemSettings;
                if (lookupByType.TryGetValue(item.IOItemDefinition.Type, out matchingItemSettings))
                {
                    ItemSettingCollection list = new ItemSettingCollection(matchingItemSettings);

                    //add all to the candidate matching items - these are items that user can choose from
                    var setting = new BenchmarkItemSetting<IOItem>(item, list);
                    benchmarkMappingSettingsCollection.Add(setting);
                    setting.SelectedSetting = setting.CandidateSettings[0];
                }
                else
                {
                    //add empty list - no matching items - benchmarking cannot be executed
                    var setting = new BenchmarkItemSetting<IOItem>(item, new ItemSettingCollection());
                    benchmarkMappingSettingsCollection.Add(setting);
                }
            }
        }
        private static void AddTypeParameters(GenericNameSyntax genericNameSyntax, MultiDictionary<string, TypeParameterSymbol> map)
        {
            // NOTE: Dev11 does not warn about duplication, it just matches parameter types to the
            // *last* type parameter with the same name.  That's why we're iterating backwards and
            // skipping subsequent symbols with the same name.  This can result in some surprising
            // behavior.  For example, both 'T's in "A<T>.B<T>" bind to the second implicitly
            // declared type parameter.
            SeparatedSyntaxList<TypeSyntax> typeArguments = genericNameSyntax.TypeArgumentList.Arguments;
            for (int i = typeArguments.Count - 1; i >= 0; i--)
            {
                // Other types (non-identifiers) are allowed in error scenarios, but they do not introduce new 
                // cref type parameters.
                if (typeArguments[i].Kind() == SyntaxKind.IdentifierName)
                {
                    IdentifierNameSyntax typeParameterSyntax = (IdentifierNameSyntax)typeArguments[i];
                    Debug.Assert(typeParameterSyntax != null, "Syntactic requirement of crefs");

                    string name = typeParameterSyntax.Identifier.ValueText;
                    if (SyntaxFacts.IsValidIdentifier(name) && !map.ContainsKey(name))
                    {
                        TypeParameterSymbol typeParameterSymbol = new CrefTypeParameterSymbol(name, i, typeParameterSyntax);
                        map.Add(name, typeParameterSymbol);
                    }
                }
            }
        }
Пример #19
0
        private async Task CheckItemsAsync(
            CodeFixContext context,
            SyntaxToken nameToken,
            bool isGeneric,
            CompletionList completionList,
            WordSimilarityChecker similarityChecker
            )
        {
            var document          = context.Document;
            var cancellationToken = context.CancellationToken;

            var onlyConsiderGenerics = isGeneric;
            var results = new MultiDictionary <double, string>();

            foreach (var item in completionList.Items)
            {
                if (onlyConsiderGenerics && !IsGeneric(item))
                {
                    continue;
                }

                var candidateText = item.FilterText;
                if (!similarityChecker.AreSimilar(candidateText, out var matchCost))
                {
                    continue;
                }

                var insertionText = await GetInsertionTextAsync(
                    document,
                    item,
                    completionList.Span,
                    cancellationToken : cancellationToken
                    )
                                    .ConfigureAwait(false);

                results.Add(matchCost, insertionText);
            }

            var nameText    = nameToken.ValueText;
            var codeActions = results
                              .OrderBy(kvp => kvp.Key)
                              .SelectMany(kvp => kvp.Value.Order())
                              .Where(t => t != nameText)
                              .Take(3)
                              .Select(n => CreateCodeAction(nameToken, nameText, n, document))
                              .ToImmutableArrayOrEmpty <CodeAction>();

            if (codeActions.Length > 1)
            {
                // Wrap the spell checking actions into a single top level suggestion
                // so as to not clutter the list.
                context.RegisterCodeFix(
                    new MyCodeAction(
                        string.Format(FeaturesResources.Fix_typo_0, nameText),
                        codeActions
                        ),
                    context.Diagnostics
                    );
            }
            else
            {
                context.RegisterFixes(codeActions, context.Diagnostics);
            }
        }
Пример #20
0
            internal AnonymousTypeTemplateSymbol(AnonymousTypeManager manager, AnonymousTypeDescriptor typeDescr)
            {
                this.Manager           = manager;
                this.TypeDescriptorKey = typeDescr.Key;
                _smallestLocation      = typeDescr.Location;

                // Will be set when the type's metadata is ready to be emitted,
                // <anonymous-type>.Name will throw exception if requested
                // before that moment.
                _nameAndIndex = null;

                int fieldsCount = typeDescr.Fields.Length;

                // members
                Symbol[] members     = new Symbol[fieldsCount * 3 + 1];
                int      memberIndex = 0;

                // The array storing property symbols to be used in
                // generation of constructor and other methods
                if (fieldsCount > 0)
                {
                    AnonymousTypePropertySymbol[] propertiesArray     = new AnonymousTypePropertySymbol[fieldsCount];
                    TypeParameterSymbol[]         typeParametersArray = new TypeParameterSymbol[fieldsCount];

                    // Process fields
                    for (int fieldIndex = 0; fieldIndex < fieldsCount; fieldIndex++)
                    {
                        AnonymousTypeField field = typeDescr.Fields[fieldIndex];

                        // Add a type parameter
                        AnonymousTypeParameterSymbol typeParameter =
                            new AnonymousTypeParameterSymbol(this, fieldIndex, GeneratedNames.MakeAnonymousTypeParameterName(field.Name));
                        typeParametersArray[fieldIndex] = typeParameter;

                        // Add a property
                        AnonymousTypePropertySymbol property = new AnonymousTypePropertySymbol(this, field, typeParameter);
                        propertiesArray[fieldIndex] = property;

                        // Property related symbols
                        members[memberIndex++] = property;
                        members[memberIndex++] = property.BackingField;
                        members[memberIndex++] = property.GetMethod;
                    }

                    _typeParameters = typeParametersArray.AsImmutable();
                    this.Properties = propertiesArray.AsImmutable();
                }
                else
                {
                    _typeParameters = ImmutableArray <TypeParameterSymbol> .Empty;
                    this.Properties = ImmutableArray <AnonymousTypePropertySymbol> .Empty;
                }

                // Add a constructor
                members[memberIndex++] = new AnonymousTypeConstructorSymbol(this, this.Properties);
                _members = members.AsImmutable();

                Debug.Assert(memberIndex == _members.Length);

                // fill nameToSymbols map
                foreach (var symbol in _members)
                {
                    _nameToSymbols.Add(symbol.Name, symbol);
                }

                // special members: Equals, GetHashCode, ToString
                MethodSymbol[] specialMembers = new MethodSymbol[3];
                specialMembers[0]   = new AnonymousTypeEqualsMethodSymbol(this);
                specialMembers[1]   = new AnonymousTypeGetHashCodeMethodSymbol(this);
                specialMembers[2]   = new AnonymousTypeToStringMethodSymbol(this);
                this.SpecialMembers = specialMembers.AsImmutable();
            }
 public void Add(Declaration child)
 {
     Requires.That(child.ContainingNamespace == this, nameof(child), "Child must be contained in this namespace");
     members.Add(child.Name, child);
 }
Пример #22
0
        private static int VerifyForwardedTypes(
            Dictionary<INamedTypeSymbol, INamedTypeSymbol> equivalentTypesWithDifferingAssemblies,
            Compilation compilation,
            HashSet<INamedTypeSymbol> verifiedKeys,
            bool isSearchSymbolCompilation)
        {
            Contract.ThrowIfNull(compilation);
            Contract.ThrowIfNull(equivalentTypesWithDifferingAssemblies);
            Contract.ThrowIfTrue(!equivalentTypesWithDifferingAssemblies.Any());

            // Must contain equivalents named types residing in different assemblies.
            Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => !SymbolEquivalenceComparer.Instance.Equals(kvp.Key.ContainingAssembly, kvp.Value.ContainingAssembly)));

            // Must contain non-nested named types.
            Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Key.ContainingType == null));
            Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Value.ContainingType == null));

            var referencedAssemblies = new MultiDictionary<string, IAssemblySymbol>();
            foreach (var assembly in compilation.GetReferencedAssemblySymbols())
            {
                referencedAssemblies.Add(assembly.Name, assembly);
            }

            int verifiedCount = 0;
            foreach (var kvp in equivalentTypesWithDifferingAssemblies)
            {
                if (!verifiedKeys.Contains(kvp.Key))
                {
                    INamedTypeSymbol originalType, expectedForwardedType;
                    if (isSearchSymbolCompilation)
                    {
                        originalType = kvp.Value.OriginalDefinition;
                        expectedForwardedType = kvp.Key.OriginalDefinition;
                    }
                    else
                    {
                        originalType = kvp.Key.OriginalDefinition;
                        expectedForwardedType = kvp.Value.OriginalDefinition;
                    }

                    foreach (var referencedAssembly in referencedAssemblies[originalType.ContainingAssembly.Name])
                    {
                        var fullyQualifiedTypeName = originalType.MetadataName;
                        if (originalType.ContainingNamespace != null)
                        {
                            fullyQualifiedTypeName = originalType.ContainingNamespace.ToDisplayString(SymbolDisplayFormats.SignatureFormat) +
                                "." + fullyQualifiedTypeName;
                        }

                        // Resolve forwarded type and verify that the types from different assembly are indeed equivalent.
                        var forwardedType = referencedAssembly.ResolveForwardedType(fullyQualifiedTypeName);
                        if (forwardedType == expectedForwardedType)
                        {
                            verifiedKeys.Add(kvp.Key);
                            verifiedCount++;
                        }
                    }
                }
            }

            return verifiedCount;
        }
        /// <summary>
        /// This macro implements InitializationConcept (singleton) instead of AutoInheritRowPermissionsInfo,
        /// in order to allow creating the new concepts in a single iteration.
        /// </summary>
        public IEnumerable <IConceptInfo> CreateNewConcepts(InitializationConcept conceptInfo, IDslModel existingConcepts)
        {
            var autoInheritModules = new HashSet <string>(
                existingConcepts.FindByType <AutoInheritRowPermissionsInfo>().Select(airp => airp.Module.Name));

            var autoInheritExtensionsByBase = new MultiDictionary <string, DataStructureExtendsInfo>();
            var autoInheritExtensions       = existingConcepts.FindByType <DataStructureExtendsInfo>()
                                              .Where(e => autoInheritModules.Contains(e.Extension.Module.Name));

            foreach (var autoInheritExtension in autoInheritExtensions)
            {
                autoInheritExtensionsByBase.Add(autoInheritExtension.Base.GetKey(), autoInheritExtension);
            }

            var autoInheritDetailsByMaster = new MultiDictionary <string, ReferenceDetailInfo>();
            var autoInheritDetails         = existingConcepts.FindByType <ReferenceDetailInfo>()
                                             .Where(d => autoInheritModules.Contains(d.Reference.DataStructure.Module.Name));

            foreach (var autoInheritDetail in autoInheritDetails)
            {
                autoInheritDetailsByMaster.Add(autoInheritDetail.Reference.Referenced.GetKey(), autoInheritDetail);
            }

            var rowPermissionsRead  = existingConcepts.FindByType <RowPermissionsReadInfo>();
            var rowPermissionsWrite = existingConcepts.FindByType <RowPermissionsWriteInfo>();
            var allDataStructuresWithRowPermissions = new HashSet <string>(
                rowPermissionsRead.Select(rp => rp.Source.GetKey())
                .Union(rowPermissionsWrite.Select(rp => rp.Source.GetKey())).ToList());

            var newConcepts = new List <IConceptInfo>();

            var newDataStructuresWithRowPermissions = new List <string>(allDataStructuresWithRowPermissions);

            while (newDataStructuresWithRowPermissions.Count > 0)
            {
                var newInheritences = new List <IConceptInfo>();

                newInheritences.AddRange(newDataStructuresWithRowPermissions
                                         .SelectMany(ds => autoInheritExtensionsByBase.Get(ds))
                                         .SelectMany(extension =>
                {
                    var rpFilters = new RowPermissionsPluginableFiltersInfo {
                        DataStructure = extension.Extension
                    };
                    var rpInherit = new RowPermissionsInheritFromBaseInfo {
                        RowPermissionsFilters = rpFilters
                    };
                    return(new IConceptInfo[] { rpFilters, rpInherit });
                }));

                newInheritences.AddRange(newDataStructuresWithRowPermissions
                                         .SelectMany(ds => autoInheritDetailsByMaster.Get(ds))
                                         .SelectMany(detail =>
                {
                    var rpFilters = new RowPermissionsPluginableFiltersInfo {
                        DataStructure = detail.Reference.DataStructure
                    };
                    var rpInherit = new RowPermissionsInheritFromReferenceInfo {
                        RowPermissionsFilters = rpFilters, ReferenceProperty = detail.Reference
                    };
                    return(new IConceptInfo[] { rpFilters, rpInherit });
                }));

                newConcepts.AddRange(newInheritences);

                newDataStructuresWithRowPermissions = newInheritences.OfType <RowPermissionsPluginableFiltersInfo>()
                                                      .Select(rpFilters => rpFilters.DataStructure.GetKey())
                                                      .Where(dataStructure => !allDataStructuresWithRowPermissions.Contains(dataStructure))
                                                      .ToList();

                foreach (var dataStructure in newDataStructuresWithRowPermissions)
                {
                    allDataStructuresWithRowPermissions.Add(dataStructure);
                }
            }
            ;

            return(newConcepts);
        }
Пример #24
0
 public void Add(string key, PhoneEntry value)
 {
     names.Add(key, value);
 }
Пример #25
0
        /// <summary>
        /// Evaluates the Command in the given Context
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        public override void Evaluate(SparqlUpdateEvaluationContext context)
        {
            bool datasetOk  = false;
            bool defGraphOk = false;

            try
            {
                // First evaluate the WHERE pattern to get the affected bindings
                ISparqlAlgebra where = this._wherePattern.ToAlgebra();
                if (context.Commands != null)
                {
                    where = context.Commands.ApplyAlgebraOptimisers(where);
                }

                // Set Active Graph for the WHERE
                // Don't bother if there are USING URIs as these would override any Active Graph we set here
                // so we can save ourselves the effort of doing this
                if (!this.UsingUris.Any())
                {
                    if (this._graphUri != null)
                    {
                        context.Data.SetActiveGraph(this._graphUri);
                        defGraphOk = true;
                    }
                    else
                    {
                        context.Data.SetActiveGraph((Uri)null);
                        defGraphOk = true;
                    }
                }

                // We need to make a dummy SparqlQuery object since if the Command has used any
                // USING NAMEDs along with GRAPH clauses then the algebra needs to have the
                // URIs available to it which it gets from the Query property of the Context
                // object
                SparqlQuery query = new SparqlQuery();
                foreach (Uri u in this.UsingUris)
                {
                    query.AddDefaultGraph(u);
                }
                foreach (Uri u in this.UsingNamedUris)
                {
                    query.AddNamedGraph(u);
                }
                SparqlEvaluationContext queryContext = new SparqlEvaluationContext(query, context.Data, context.QueryProcessor);
                if (this.UsingUris.Any())
                {
                    // If there are USING URIs set the Active Graph to be formed of the Graphs with those URIs
                    context.Data.SetActiveGraph(this._usingUris);
                    datasetOk = true;
                }
                BaseMultiset results = queryContext.Evaluate(where);
                if (results is IdentityMultiset)
                {
                    results = new SingletonMultiset(results.Variables);
                }
                if (this.UsingUris.Any())
                {
                    // If there are USING URIs reset the Active Graph afterwards
                    // Also flag the dataset as no longer being OK as this flag is used in the finally
                    // block to determine whether the Active Graph needs resetting which it may do if the
                    // evaluation of the query fails for any reason
                    context.Data.ResetActiveGraph();
                    datasetOk = false;
                }

                // Reset Active Graph for the WHERE
                if (defGraphOk)
                {
                    context.Data.ResetActiveGraph();
                    defGraphOk = false;
                }

                // TODO: Need to detect when we create a Graph for Insertion but then fail to insert anything since in this case the Inserted Graph should be removed

                // Get the Graph to which we are inserting Triples with no explicit Graph clause
                IGraph g = null;
                if (this._insertPattern.TriplePatterns.Count > 0)
                {
                    if (context.Data.HasGraph(this._graphUri))
                    {
                        g = context.Data.GetModifiableGraph(this._graphUri);
                    }
                    else
                    {
                        // insertedGraphs.Add(this._graphUri);
                        g         = new Graph();
                        g.BaseUri = this._graphUri;
                        context.Data.AddGraph(g);
                        g = context.Data.GetModifiableGraph(this._graphUri);
                    }
                }

                // Keep a record of graphs to which we insert
                MultiDictionary <Uri, IGraph> graphs = new MultiDictionary <Uri, IGraph>(u => (u != null ? u.GetEnhancedHashCode() : 0), true, new UriComparer(), MultiDictionaryMode.AVL);

                // Insert the Triples for each Solution
                foreach (ISet s in results.Sets)
                {
                    List <Triple> insertedTriples = new List <Triple>();

                    try
                    {
                        // Create a new Construct Context for each Solution
                        ConstructContext constructContext = new ConstructContext(null, s, true);

                        // Triples from raw Triple Patterns
                        if (this._insertPattern.TriplePatterns.Count > 0)
                        {
                            foreach (IConstructTriplePattern p in this._insertPattern.TriplePatterns.OfType <IConstructTriplePattern>())
                            {
                                try
                                {
                                    insertedTriples.Add(p.Construct(constructContext));
                                }
                                catch (RdfQueryException)
                                {
                                    // If we throw an error this means we couldn't construct a specific Triple
                                    // so we continue anyway
                                }
                            }
                            g.Assert(insertedTriples);
                        }

                        // Triples from GRAPH clauses
                        foreach (GraphPattern gp in this._insertPattern.ChildGraphPatterns)
                        {
                            insertedTriples.Clear();
                            try
                            {
                                String graphUri;
                                switch (gp.GraphSpecifier.TokenType)
                                {
                                case Token.URI:
                                    graphUri = gp.GraphSpecifier.Value;
                                    break;

                                case Token.VARIABLE:
                                    String graphVar = gp.GraphSpecifier.Value.Substring(1);
                                    if (s.ContainsVariable(graphVar))
                                    {
                                        INode temp = s[graphVar];
                                        if (temp == null)
                                        {
                                            // If the Variable is not bound then skip
                                            continue;
                                        }
                                        if (temp.NodeType == NodeType.Uri)
                                        {
                                            graphUri = temp.ToSafeString();
                                        }
                                        else
                                        {
                                            // If the Variable is not bound to a URI then skip
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        // If the Variable is not bound for this solution then skip
                                        continue;
                                    }
                                    break;

                                default:
                                    // Any other Graph Specifier we have to ignore this solution
                                    continue;
                                }

                                // Ensure the Graph we're inserting to exists in the dataset creating it if necessary
                                IGraph h;
                                Uri    destUri = UriFactory.Create(graphUri);
                                if (graphs.ContainsKey(destUri))
                                {
                                    h = graphs[destUri];
                                }
                                else
                                {
                                    if (context.Data.HasGraph(destUri))
                                    {
                                        h = context.Data.GetModifiableGraph(destUri);
                                    }
                                    else
                                    {
                                        // insertedGraphs.Add(destUri);
                                        h         = new Graph();
                                        h.BaseUri = destUri;
                                        context.Data.AddGraph(h);
                                        h = context.Data.GetModifiableGraph(destUri);
                                    }
                                    graphs.Add(destUri, h);
                                }

                                // Do the actual Insertions
                                foreach (IConstructTriplePattern p in gp.TriplePatterns.OfType <IConstructTriplePattern>())
                                {
                                    try
                                    {
                                        Triple t = p.Construct(constructContext);
                                        t = new Triple(t.Subject, t.Predicate, t.Object, destUri);
                                        insertedTriples.Add(t);
                                    }
                                    catch (RdfQueryException)
                                    {
                                        // If we throw an error this means we couldn't construct a specific Triple
                                        // so we continue anyway
                                    }
                                }
                                h.Assert(insertedTriples);
                            }
                            catch (RdfQueryException)
                            {
                                // If we throw an error this means we couldn't construct for this solution so the
                                // solution is ignored for this Graph
                            }
                        }
                    }
                    catch (RdfQueryException)
                    {
                        // If we throw an error this means we couldn't construct for this solution so the
                        // solution is ignored for this graph
                    }
                }
            }
            finally
            {
                // If the Dataset was set and an error occurred in doing the WHERE clause then
                // we'll need to Reset the Active Graph
                if (datasetOk)
                {
                    context.Data.ResetActiveGraph();
                }
                if (defGraphOk)
                {
                    context.Data.ResetActiveGraph();
                }
            }
        }
Пример #26
0
        /// <summary>
        /// 编译指定目录的脚本
        /// </summary>
        public static bool Compile(bool bDebug, bool bCache, string strAssemblyDirectory, string strScriptDirectory)
        {
            EnsureDirectory(strAssemblyDirectory);

            ScriptAssemblyInfo scriptAssemblyInfo = new ScriptAssemblyInfo();

            const string SCRIPT_CONFIG_NAME = "/Scripts.config";
            string       strAssembliePath   = strScriptDirectory + SCRIPT_CONFIG_NAME;

            if (File.Exists(strAssembliePath) == false)
            {
                LOGs.WriteLine(LogMessageType.MSG_ERROR, LanguageString.SingletonInstance.ScriptCompilerString001, strAssembliePath);
                return(false);
            }
            else
            {
                // 以下是获取脚本里面的信息
                XDocument documentConfig = XDocument.Load(strAssembliePath);
                if (documentConfig == null)
                {
                    LOGs.WriteLine(LogMessageType.MSG_ERROR, LanguageString.SingletonInstance.ScriptCompilerString002, strAssembliePath);
                    return(false);
                }

                XElement elementRoot = documentConfig.Element((XName)"Mmose.Script");
                if (elementRoot == null)
                {
                    LOGs.WriteLine(LogMessageType.MSG_ERROR, LanguageString.SingletonInstance.ScriptCompilerString003, strAssembliePath);
                    return(false);
                }

                XAttribute attributeScriptName = elementRoot.Attribute((XName)"ScriptName");
                if (attributeScriptName == null)
                {
                    LOGs.WriteLine(LogMessageType.MSG_ERROR, LanguageString.SingletonInstance.ScriptCompilerString004, strAssembliePath);
                    return(false);
                }
                else
                {
                    scriptAssemblyInfo.SetScriptName(attributeScriptName.Value);
                }

                XAttribute attributeVersion = elementRoot.Attribute((XName)"Version");
                if (attributeVersion == null)
                {
                    LOGs.WriteLine(LogMessageType.MSG_ERROR, LanguageString.SingletonInstance.ScriptCompilerString005, strAssembliePath);
                    return(false);
                }
                else
                {
                    scriptAssemblyInfo.SetVersion(new VersionInfo(attributeVersion.Value));
                }
            }

            // 以下是C#脚本的编译
            if (CompileCSScripts(bDebug, bCache, strAssemblyDirectory, strScriptDirectory, ref scriptAssemblyInfo) == false)
            {
                return(false);
            }

            // 以下是VB脚本的编译
            if (CompileVBScripts(bDebug, bCache, strAssemblyDirectory, strScriptDirectory, ref scriptAssemblyInfo) == false)
            {
                return(false);
            }

            if (scriptAssemblyInfo.ScriptAssembly.Length <= 0)
            {
                return(false);
            }

            List <MethodInfo> invokeList = new List <MethodInfo>();

            foreach (Assembly assembly in scriptAssemblyInfo.ScriptAssembly)
            {
                Type[] types = assembly.GetTypes();

                foreach (Type type in types)
                {
                    // 以下是添加脚本class里面的静态的Initialize方法
                    if (type.GetInterface("INeedInitialize", true) != null)
                    {
                        MethodInfo methodInfo = type.GetMethod("Initialize", BindingFlags.Static | BindingFlags.Public);

                        if (methodInfo != null)
                        {
                            invokeList.Add(methodInfo);
                        }
                    }
                }
            }

            // 以下是排序脚本class里面的静态的Initialize方法
            invokeList.Sort(new CallPriorityComparer());

            // 以下是调用脚本class里面的静态的Initialize方法
            foreach (var invoke in invokeList)
            {
                invoke.Invoke(null, null);
            }

            s_LockScriptAssemblyInfos.Enter();
            {
                // 创建新的ScriptAssemblyInfo数组,添加数据,交换数组数据,不需要锁定,没有引用时自动会回收数据
                ScriptAssemblyInfo[] tempScriptAssemblyInfoArray = new ScriptAssemblyInfo[s_ScriptAssemblyInfoArray.Length + 1];

                for (int iIndex = 0; iIndex < s_ScriptAssemblyInfoArray.Length; ++iIndex)
                {
                    tempScriptAssemblyInfoArray[iIndex] = s_ScriptAssemblyInfoArray[iIndex];
                }

                tempScriptAssemblyInfoArray[s_ScriptAssemblyInfoArray.Length] = scriptAssemblyInfo;

                s_ScriptAssemblyInfoArray = tempScriptAssemblyInfoArray;

                s_ScriptAssemblyInfos.Add(scriptAssemblyInfo.ScriptName, scriptAssemblyInfo);
            }
            s_LockScriptAssemblyInfos.Exit();

            return(true);
        }
        private async Task CreateSpellCheckCodeIssueAsync(CodeFixContext context, TSimpleName nameNode, string nameText, CancellationToken cancellationToken)
        {
            var document = context.Document;
            var service  = CompletionService.GetService(document);

            // Disable snippets from ever appearing in the completion items. It's
            // very unlikely the user would ever mispell a snippet, then use spell-
            // checking to fix it, then try to invoke the snippet.
            var originalOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);

            var options = originalOptions.WithChangedOption(CompletionOptions.SnippetsBehavior, document.Project.Language, SnippetsRule.NeverInclude);

            var completionList = await service.GetCompletionsAsync(
                document, nameNode.SpanStart, options : options, cancellationToken : cancellationToken).ConfigureAwait(false);

            if (completionList == null)
            {
                return;
            }

            var onlyConsiderGenerics = IsGeneric(nameNode);
            var results = new MultiDictionary <double, string>();

            using (var similarityChecker = new WordSimilarityChecker(nameText, substringsAreSimilar: true))
            {
                foreach (var item in completionList.Items)
                {
                    if (onlyConsiderGenerics && !IsGeneric(item))
                    {
                        continue;
                    }

                    var    candidateText = item.FilterText;
                    double matchCost;
                    if (!similarityChecker.AreSimilar(candidateText, out matchCost))
                    {
                        continue;
                    }

                    var insertionText = await GetInsertionTextAsync(document, item, cancellationToken : cancellationToken).ConfigureAwait(false);

                    results.Add(matchCost, insertionText);
                }
            }

            var codeActions = results.OrderBy(kvp => kvp.Key)
                              .SelectMany(kvp => kvp.Value.Order())
                              .Where(t => t != nameText)
                              .Take(3)
                              .Select(n => CreateCodeAction(nameNode, nameText, n, document))
                              .ToImmutableArrayOrEmpty <CodeAction>();

            if (codeActions.Length > 1)
            {
                // Wrap the spell checking actions into a single top level suggestion
                // so as to not clutter the list.
                context.RegisterCodeFix(new MyCodeAction(
                                            String.Format(FeaturesResources.Spell_check_0, nameText), codeActions), context.Diagnostics);
            }
            else
            {
                context.RegisterFixes(codeActions, context.Diagnostics);
            }
        }
Пример #28
0
        public static DomainProperty Register(string name,
                                              Type propertyType,
                                              Type ownerType,
                                              Func <DomainObject, DomainProperty, object> getDefaultValue,
                                              PropertyChangedMode changedMode,
                                              Type dynamicType = null)
        {
            lock (_properties)
            {
                var target = _properties.GetValue(ownerType, (p) =>
                {
                    return(p.Name.EqualsIgnoreCase(name));
                });
                if (target != null)
                {
                    throw new DomainDrivenException(string.Format(Strings.RepeatedDeclareProperty, ownerType.FullName, name));
                }

                var validators    = PropertyValidatorAttribute.GetValidators(ownerType, name);
                var repositoryTip = GetAttribute <PropertyRepositoryAttribute>(ownerType, name);

                var property = new DomainProperty()
                {
                    Id              = Guid.NewGuid(),
                    Name            = name,
                    PropertyType    = propertyType,
                    OwnerType       = ownerType,
                    GetDefaultValue = getDefaultValue,
                    ChangedMode     = changedMode,
                    Validators      = validators,
                    RepositoryTip   = repositoryTip,
                    PropertyInfo    = ownerType.ResolveProperty(name),
                    DynamicType     = dynamicType
                };

                if (repositoryTip != null)
                {
                    repositoryTip.Property = property; //赋值
                }
                {
                    //获取属性值的行为链
                    var chain = new PropertyGetChain(property);
                    chain.AddMethods(PropertyGetAttribute.GetMethods(ownerType, name));
                    property.GetChain = chain;
                }

                {
                    //设置属性值的行为链
                    var chain = new PropertySetChain(property);
                    chain.AddMethods(PropertySetAttribute.GetMethods(ownerType, name));
                    property.SetChain = chain;
                }


                {
                    //更改属性值的行为链
                    var chain = new PropertyChangedChain(property);
                    chain.AddMethods(PropertyChangedAttribute.GetMethods(ownerType, name));
                    property.ChangedChain = chain;
                }

                InitAccessLevel(property);

                _properties.Add(ownerType, property);
                return(property);
            }
        }
Пример #29
0
        private MultiDictionary <string, PluginInfo> LoadPlugins(List <string> assemblyPaths)
        {
            var stopwatch = Stopwatch.StartNew();

            int ignoredFileCount = 0;

            assemblyPaths = assemblyPaths
                            .Where(file =>
            {
                string fileName = Path.GetFileName(file);
                bool ignored    = _ignoreAssemblyFiles.Contains(fileName) ||
                                  _ignoreAssemblyPrefixes.Any(prefix => fileName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
                if (ignored)
                {
                    ignoredFileCount++;
                }
                return(!ignored);
            })
                            .ToList();
            if (ignoredFileCount > 0)
            {
                _logger.Trace($"Ignored {ignoredFileCount} assemblies based on {nameof(PluginScannerOptions)}.");
            }

            lock (_pluginsCacheLock) // Reading and updating cache files should not be done in parallel.
            {
                var cache = _pluginScannerCache.LoadPluginsCacheData();

                bool cacheUpdated     = false;
                var  cachedAssemblies = 0;
                var  pluginsByExport  = new MultiDictionary <string, PluginInfo>();
                var  pluginsCount     = 0;

                foreach (var assemblyPath in assemblyPaths)
                {
                    var assemblyModifiedToken = new FileInfo(assemblyPath).LastWriteTimeUtc.ToString("O");
                    Dictionary <Type, List <PluginInfo> > exports;
                    if (cache.Assemblies.TryGetValue(assemblyPath, out var cachedFileData) && cachedFileData.ModifiedTime == assemblyModifiedToken)
                    {
                        exports = GetMefExportsForAssembly(assemblyPath, cachedFileData.TypesWithExports);
                        cachedAssemblies++;
                    }
                    else
                    {
                        _logger.Trace($"Assembly '{assemblyPath}' is not cached. Scanning all types.");
                        exports = GetMefExportsForAssembly(assemblyPath);
                    }

                    foreach (var export in exports)
                    {
                        foreach (var plugin in export.Value)
                        {
                            pluginsByExport.Add(export.Key.FullName, plugin);
                            pluginsCount++;
                        }
                    }

                    var newCachedFileData = new CachedFileData()
                    {
                        ModifiedTime     = assemblyModifiedToken,
                        TypesWithExports = exports.SelectMany(export => export.Value.Select(plugin => plugin.Type.AssemblyQualifiedName)).Distinct().ToList()
                    };
                    if (!cache.Assemblies.ContainsKey(assemblyPath) ||
                        !cache.Assemblies[assemblyPath].Equals(newCachedFileData))
                    {
                        cache.Assemblies[assemblyPath] = newCachedFileData;
                        cacheUpdated = true;
                    }
                }

                _logger.Trace($"Used cached data for {cachedAssemblies} out of total {assemblyPaths.Count} assemblies. {pluginsCount} total plugins loaded.");

                if (cacheUpdated)
                {
                    _pluginScannerCache.SavePluginsCacheData(cache);
                }

                foreach (var pluginsGroup in pluginsByExport)
                {
                    SortByDependency(pluginsGroup.Value);
                }

                _performanceLogger.Write(stopwatch, $"Loaded plugins ({pluginsCount}).");

                return(pluginsByExport);
            }
        }
Пример #30
0
        private static MultiDictionary<string, PluginInfo> LoadPlugins(List<string> assemblies)
        {
            var stopwatch = Stopwatch.StartNew();

            var assemblyCatalogs = assemblies.Select(a => new AssemblyCatalog(a));
            var container = new CompositionContainer(new AggregateCatalog(assemblyCatalogs));
            var mefPlugins = container.Catalog.Parts
                .Select(part => new
                {
                    PluginType = ReflectionModelServices.GetPartType(part).Value,
                    part.ExportDefinitions
                })
                .SelectMany(part =>
                    part.ExportDefinitions.Select(exportDefinition => new
                    {
                        exportDefinition.ContractName,
                        exportDefinition.Metadata,
                        part.PluginType
                    }));

            var pluginsByExport = new MultiDictionary<string, PluginInfo>();
            int pluginsCount = 0;
            foreach (var mefPlugin in mefPlugins)
            {
                pluginsCount++;
                pluginsByExport.Add(
                    mefPlugin.ContractName,
                    new PluginInfo
                    {
                        Type = mefPlugin.PluginType,
                        Metadata = mefPlugin.Metadata.ToDictionary(m => m.Key, m => m.Value)
                    });
            }

            foreach (var pluginsGroup in pluginsByExport)
                SortByDependency(pluginsGroup.Value);

            InitializationLogging.PerformanceLogger.Write(stopwatch, "MefPluginScanner: Loaded plugins (" + pluginsCount + ").");
            return pluginsByExport;
        }
Пример #31
0
 /// <summary>
 /// MultiDictionary<TKey,TValue>
 /// A dictionary (map) implemented by hash-table (DUPLICATES CONFIGURABLE)
 /// Allows duplicates
 /// Add / Find / Remove work in time O(1)
 /// Like Dictionary<TKey,List<TValue>>
 /// </summary>
 private static void TestMultiDictionary()
 {
     MultiDictionary<int, Student> students = new MultiDictionary<int, Student>(true);
     var student1 = new Student("First DUPLICATE", 21);
     var student2 = new Student("Second", 21);
     students.Add(1, student1);
     students.Add(1, student1);
     students.Add(2, student2);
     var student3 = new Student("Third", 22);
     var student4 = new Student("Forth", 23);
     var student5 = new Student("Fifth", 24);
     students.Add(3, student3);
     students.Add(4, student4);
     students.Add(2, student5);
     foreach (var item in students)
     {
         Console.WriteLine(item);
     }
 }
Пример #32
0
            /// <summary>
            /// Optimizes local functions such that if a local function only references other local functions
            /// that capture no variables, we don't need to create capture environments for any of them.
            /// </summary>
            private void RemoveUnneededReferences(ParameterSymbol thisParam)
            {
                var methodGraph      = new MultiDictionary <MethodSymbol, MethodSymbol>();
                var capturesThis     = new HashSet <MethodSymbol>();
                var capturesVariable = new HashSet <MethodSymbol>();
                var visitStack       = new Stack <MethodSymbol>();

                VisitClosures(ScopeTree, (scope, closure) =>
                {
                    foreach (var capture in closure.CapturedVariables)
                    {
                        if (capture is MethodSymbol localFunc)
                        {
                            methodGraph.Add(localFunc, closure.OriginalMethodSymbol);
                        }
                        else if (capture == thisParam)
                        {
                            if (capturesThis.Add(closure.OriginalMethodSymbol))
                            {
                                visitStack.Push(closure.OriginalMethodSymbol);
                            }
                        }
                        else if (capturesVariable.Add(closure.OriginalMethodSymbol) &&
                                 !capturesThis.Contains(closure.OriginalMethodSymbol))
                        {
                            visitStack.Push(closure.OriginalMethodSymbol);
                        }
                    }
                });

                while (visitStack.Count > 0)
                {
                    var current    = visitStack.Pop();
                    var setToAddTo = capturesVariable.Contains(current) ? capturesVariable : capturesThis;
                    foreach (var capturesCurrent in methodGraph[current])
                    {
                        if (setToAddTo.Add(capturesCurrent))
                        {
                            visitStack.Push(capturesCurrent);
                        }
                    }
                }

                // True if there are any closures in the tree which
                // capture 'this' and another variable
                bool captureMoreThanThis = false;

                VisitClosures(ScopeTree, (scope, closure) =>
                {
                    if (!capturesVariable.Contains(closure.OriginalMethodSymbol))
                    {
                        closure.CapturedVariables.Clear();
                    }

                    if (capturesThis.Contains(closure.OriginalMethodSymbol))
                    {
                        closure.CapturedVariables.Add(thisParam);
                        if (closure.CapturedVariables.Count > 1)
                        {
                            captureMoreThanThis |= true;
                        }
                    }
                });

                if (!captureMoreThanThis && capturesThis.Count > 0)
                {
                    // If we have closures which capture 'this', and nothing else, we can
                    // remove 'this' from the declared variables list, since we don't need
                    // to create an environment to hold 'this' (since we can emit the
                    // lowered methods directly onto the containing class)
                    bool removed = ScopeTree.DeclaredVariables.Remove(thisParam);
                    Debug.Assert(removed);
                }
            }
Пример #33
0
 /// <summary>
 /// Imports any Class heirarchy information from the given Graph into the Reasoners Knowledge Base in order to initialise the Reasoner.
 /// </summary>
 /// <param name="g">Graph to import from.</param>
 /// <remarks>
 /// Looks for Triples defining things to be classes and those defining that something is a subClass of something.
 /// </remarks>
 public void Initialise(IGraph g)
 {
     foreach (Triple t in g.Triples)
     {
         if (t.Predicate.Equals(_rdfType))
         {
             if (t.Object.Equals(_rdfsClass))
             {
                 // The Triple defines a Class
                 if (!_classMappings.ContainsKey(t.Subject))
                 {
                     _classMappings.Add(t.Subject, null);
                 }
             }
             else if (t.Object.Equals(_rdfProperty))
             {
                 // The Triple defines a Property
                 if (!_propertyMappings.ContainsKey(t.Subject))
                 {
                     _propertyMappings.Add(t.Subject, null);
                 }
             }
         }
         else if (t.Predicate.Equals(_rdfsSubClass))
         {
             // The Triple defines a Sub Class
             if (!_classMappings.ContainsKey(t.Subject))
             {
                 _classMappings.Add(t.Subject, t.Object);
             }
             else if (_classMappings[t.Subject] == null)
             {
                 _classMappings[t.Subject] = t.Object;
             }
         }
         else if (t.Predicate.Equals(_rdfsSubProperty))
         {
             // The Triple defines a Sub property
             if (!_propertyMappings.ContainsKey(t.Subject))
             {
                 _propertyMappings.Add(t.Subject, t.Object);
             }
             else if (_propertyMappings[t.Subject] == null)
             {
                 _propertyMappings[t.Subject] = t.Object;
             }
         }
         else if (t.Predicate.Equals(_rdfsRange))
         {
             // This Triple defines a Range
             if (!_propertyMappings.ContainsKey(t.Subject))
             {
                 _propertyMappings.Add(t.Subject, null);
             }
             if (!_rangeMappings.ContainsKey(t.Subject))
             {
                 _rangeMappings.Add(t.Subject, new List <INode> {
                     t.Object
                 });
             }
             if (!_classMappings.ContainsKey(t.Object))
             {
                 _classMappings.Add(t.Object, null);
             }
         }
         else if (t.Predicate.Equals(_rdfsDomain))
         {
             // This Triple defines a Domain
             if (!_propertyMappings.ContainsKey(t.Subject))
             {
                 _propertyMappings.Add(t.Subject, null);
             }
             if (!_domainMappings.ContainsKey(t.Subject))
             {
                 _domainMappings.Add(t.Subject, new List <INode> {
                     t.Object
                 });
             }
             if (!_classMappings.ContainsKey(t.Object))
             {
                 _classMappings.Add(t.Object, null);
             }
         }
         else
         {
             // Just add the property as a predicate
             if (!_propertyMappings.ContainsKey(t.Predicate))
             {
                 _propertyMappings.Add(t.Predicate, null);
             }
         }
     }
 }
Пример #34
0
        /// <summary>
        /// Compare the root elements and, if they are equal, match up children by shallow equality, recursing on each pair.
        /// </summary>
        /// <returns>True if the elements are equal, false otherwise (in which case, firstMismatch will try to indicate a point of disagreement).</returns>
        private static bool CheckEqual(XElement expectedRoot, XElement actualRoot, IEqualityComparer <XElement> shallowComparer, out Tuple <XElement, XElement> firstMismatch)
        {
            Assert.NotNull(expectedRoot);
            Assert.NotNull(actualRoot);
            Assert.NotNull(shallowComparer);

            Tuple <XElement, XElement> rootPair = new Tuple <XElement, XElement>(expectedRoot, actualRoot);

            if (!shallowComparer.Equals(expectedRoot, actualRoot))
            {
                firstMismatch = rootPair;
                return(false);
            }

            Stack <Tuple <XElement, XElement> > stack = new Stack <Tuple <XElement, XElement> >();

            stack.Push(rootPair);

            while (stack.Count > 0)
            {
                Tuple <XElement, XElement> pair = stack.Pop();
                firstMismatch = pair;                                         // Will be overwritten if this pair is a match.
                Debug.Assert(shallowComparer.Equals(pair.Item1, pair.Item2)); // Shouldn't have been pushed otherwise.

                XElement[] children1 = pair.Item1.Elements().ToArray();
                MultiDictionary <XElement, XElement> children2Dict = new MultiDictionary <XElement, XElement>(shallowComparer);

                int children2Count = 0;
                foreach (XElement child in pair.Item2.Elements())
                {
                    children2Dict.Add(child, child);
                    children2Count++;
                }

                if (children1.Length != children2Count)
                {
                    return(false);
                }


                HashSet <XElement> children2Used = new HashSet <XElement>(ReferenceEqualityComparer.Instance);
                foreach (XElement child1 in children1)
                {
                    XElement child2 = null;
                    foreach (var candidate in children2Dict[child1])
                    {
                        if (!children2Used.Contains(candidate))
                        {
                            child2 = candidate;
                            break;
                        }
                    }

                    if (child2 == null)
                    {
                        return(false);
                    }
                    else
                    {
                        children2Used.Add(child2);
                        stack.Push(new Tuple <XElement, XElement>(child1, child2));
                    }
                }

                if (children2Used.Count < children1.Length)
                {
                    return(false);
                }
            }

            firstMismatch = null;
            return(true);
        }
Пример #35
0
 /// <summary>
 /// Adds a QName mapping to the cache.
 /// </summary>
 /// <param name="uri">URI.</param>
 /// <param name="mapping">Mapping.</param>
 protected virtual void AddToCache(String uri, QNameMapping mapping)
 {
     _mapping.Add(uri, mapping);
 }
Пример #36
0
        /// <summary>
        /// Transfers the CXSMILES state onto the CDK atom/molecule data-structures.
        /// </summary>
        /// <param name="bldr">chem-object builder</param>
        /// <param name="atoms">atoms parsed from the molecule or reaction. Reaction molecules are list left to right.</param>
        /// <param name="atomToMol">look-up of atoms to molecules when connectivity/sgroups need modification</param>
        /// <param name="cxstate">the CXSMILES state to read from</param>
        private void AssignCxSmilesInfo(IChemObjectBuilder bldr,
                                        IChemObject chemObj,
                                        List <IAtom> atoms,
                                        Dictionary <IAtom, IAtomContainer> atomToMol,
                                        CxSmilesState cxstate)
        {
            // atom-labels - must be done first as we replace atoms
            if (cxstate.atomLabels != null)
            {
                foreach (var e in cxstate.atomLabels)
                {
                    // bounds check
                    if (e.Key >= atoms.Count)
                    {
                        continue;
                    }

                    var old    = atoms[e.Key];
                    var pseudo = bldr.NewPseudoAtom();
                    var val    = e.Value;

                    // specialised label handling
                    if (val.EndsWith("_p", StringComparison.Ordinal)) // pseudo label
                    {
                        val = val.Substring(0, val.Length - 2);
                    }
                    else if (val.StartsWith("_AP", StringComparison.Ordinal)) // attachment point
                    {
                        pseudo.AttachPointNum = ParseIntSafe(val.Substring(3));
                    }

                    pseudo.Label                 = val;
                    pseudo.AtomicNumber          = 0;
                    pseudo.ImplicitHydrogenCount = 0;
                    var mol = atomToMol[old];
                    AtomContainerManipulator.ReplaceAtomByAtom(mol, old, pseudo);
                    atomToMol.Add(pseudo, mol);
                    atoms[e.Key] = pseudo;
                }
            }

            // atom-values - set as comment, mirrors Molfile reading behavior
            if (cxstate.atomValues != null)
            {
                foreach (var e in cxstate.atomValues)
                {
                    atoms[e.Key].SetProperty(CDKPropertyName.Comment, e.Value);
                }
            }

            // atom-coordinates
            if (cxstate.atomCoords != null)
            {
                var numAtoms  = atoms.Count;
                var numCoords = cxstate.atomCoords.Count;
                var lim       = Math.Min(numAtoms, numCoords);
                if (cxstate.coordFlag)
                {
                    for (int i = 0; i < lim; i++)
                    {
                        atoms[i].Point3D = new Vector3(
                            cxstate.atomCoords[i][0],
                            cxstate.atomCoords[i][1],
                            cxstate.atomCoords[i][2]);
                    }
                }
                else
                {
                    for (int i = 0; i < lim; i++)
                    {
                        atoms[i].Point2D = new Vector2(
                            cxstate.atomCoords[i][0],
                            cxstate.atomCoords[i][1]);
                    }
                }
            }

            // atom radicals
            if (cxstate.atomRads != null)
            {
                foreach (var e in cxstate.atomRads)
                {
                    // bounds check
                    if (e.Key >= atoms.Count)
                    {
                        continue;
                    }

                    int count = 0;
                    var aa    = e.Value;
                    switch (e.Value)
                    {
                    case CxSmilesState.Radical.Monovalent:
                        count = 1;
                        break;

                    // no distinction in CDK between singled/triplet
                    case CxSmilesState.Radical.Divalent:
                    case CxSmilesState.Radical.DivalentSinglet:
                    case CxSmilesState.Radical.DivalentTriplet:
                        count = 2;
                        break;

                    // no distinction in CDK between doublet/quartet
                    case CxSmilesState.Radical.Trivalent:
                    case CxSmilesState.Radical.TrivalentDoublet:
                    case CxSmilesState.Radical.TrivalentQuartet:
                        count = 3;
                        break;
                    }
                    var atom = atoms[e.Key];
                    var mol  = atomToMol[atom];
                    while (count-- > 0)
                    {
                        mol.SingleElectrons.Add(bldr.NewSingleElectron(atom));
                    }
                }
            }

            var sgroupMap = new MultiDictionary <IAtomContainer, Sgroup>();

            // positional-variation
            if (cxstate.positionVar != null)
            {
                foreach (var e in cxstate.positionVar)
                {
                    var sgroup = new Sgroup {
                        Type = SgroupType.ExtMulticenter
                    };
                    var beg   = atoms[e.Key];
                    var mol   = atomToMol[beg];
                    var bonds = mol.GetConnectedBonds(beg);
                    if (bonds.Count() == 0)
                    {
                        continue; // bad
                    }
                    sgroup.Add(beg);
                    sgroup.Add(bonds.First());
                    foreach (var endpt in e.Value)
                    {
                        sgroup.Add(atoms[endpt]);
                    }
                    sgroupMap.Add(mol, sgroup);
                }
            }

            // data sgroups
            if (cxstate.dataSgroups != null)
            {
                foreach (var dsgroup in cxstate.dataSgroups)
                {
                    if (dsgroup.Field != null && dsgroup.Field.StartsWith("cdk:", StringComparison.Ordinal))
                    {
                        chemObj.SetProperty(dsgroup.Field, dsgroup.Value);
                    }
                }
            }

            // polymer Sgroups
            if (cxstate.sgroups != null)
            {
                foreach (var psgroup in cxstate.sgroups)
                {
                    var            sgroup  = new Sgroup();
                    var            atomset = new HashSet <IAtom>();
                    IAtomContainer mol     = null;
                    foreach (var idx in psgroup.AtomSet)
                    {
                        if (idx >= atoms.Count)
                        {
                            continue;
                        }
                        var atom = atoms[idx];
                        var amol = atomToMol[atom];

                        if (mol == null)
                        {
                            mol = amol;
                        }
                        else if (amol != mol)
                        {
                            goto C_PolySgroup;
                        }

                        atomset.Add(atom);
                    }

                    if (mol == null)
                    {
                        continue;
                    }

                    foreach (var atom in atomset)
                    {
                        foreach (var bond in mol.GetConnectedBonds(atom))
                        {
                            if (!atomset.Contains(bond.GetOther(atom)))
                            {
                                sgroup.Add(bond);
                            }
                        }
                        sgroup.Add(atom);
                    }

                    sgroup.Subscript = psgroup.Subscript;
                    sgroup.PutValue(SgroupKey.CtabConnectivity, psgroup.Supscript);

                    switch (psgroup.Type)
                    {
                    case "n":
                        sgroup.Type = SgroupType.CtabStructureRepeatUnit;
                        break;

                    case "mon":
                        sgroup.Type = SgroupType.CtabMonomer;
                        break;

                    case "mer":
                        sgroup.Type = SgroupType.CtabMer;
                        break;

                    case "co":
                        sgroup.Type = SgroupType.CtabCopolymer;
                        break;

                    case "xl":
                        sgroup.Type = SgroupType.CtabCrossLink;
                        break;

                    case "mod":
                        sgroup.Type = SgroupType.CtabModified;
                        break;

                    case "mix":
                        sgroup.Type = SgroupType.CtabMixture;
                        break;

                    case "f":
                        sgroup.Type = SgroupType.CtabFormulation;
                        break;

                    case "any":
                        sgroup.Type = SgroupType.CtabAnyPolymer;
                        break;

                    case "gen":
                        sgroup.Type = SgroupType.CtabGeneric;
                        break;

                    case "c":
                        sgroup.Type = SgroupType.CtabComponent;
                        break;

                    case "grf":
                        sgroup.Type = SgroupType.CtabGraft;
                        break;

                    case "alt":
                        sgroup.Type = SgroupType.CtabCopolymer;
                        sgroup.PutValue(SgroupKey.CtabSubType, "ALT");
                        break;

                    case "ran":
                        sgroup.Type = SgroupType.CtabCopolymer;
                        sgroup.PutValue(SgroupKey.CtabSubType, "RAN");
                        break;

                    case "blk":
                        sgroup.Type = SgroupType.CtabCopolymer;
                        sgroup.PutValue(SgroupKey.CtabSubType, "BLO");
                        break;
                    }
                    sgroupMap.Add(mol, sgroup);
C_PolySgroup:
                    ;
                }
            }

            // assign Sgroups
            foreach (var e in sgroupMap)
            {
                e.Key.SetCtabSgroups(new List <Sgroup>(e.Value));
            }
        }
Пример #37
0
        private static int VerifyForwardedTypes(
            Dictionary <INamedTypeSymbol, INamedTypeSymbol> equivalentTypesWithDifferingAssemblies,
            Compilation compilation,
            HashSet <INamedTypeSymbol> verifiedKeys,
            bool isSearchSymbolCompilation)
        {
            Contract.ThrowIfNull(compilation);
            Contract.ThrowIfNull(equivalentTypesWithDifferingAssemblies);
            Contract.ThrowIfTrue(!equivalentTypesWithDifferingAssemblies.Any());

            // Must contain equivalents named types residing in different assemblies.
            Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => !SymbolEquivalenceComparer.Instance.Equals(kvp.Key.ContainingAssembly, kvp.Value.ContainingAssembly)));

            // Must contain non-nested named types.
            Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Key.ContainingType == null));
            Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Value.ContainingType == null));

            var referencedAssemblies = new MultiDictionary <string, IAssemblySymbol>();

            foreach (var assembly in compilation.GetReferencedAssemblySymbols())
            {
                referencedAssemblies.Add(assembly.Name, assembly);
            }

            var verifiedCount = 0;

            foreach (var kvp in equivalentTypesWithDifferingAssemblies)
            {
                if (!verifiedKeys.Contains(kvp.Key))
                {
                    INamedTypeSymbol originalType, expectedForwardedType;
                    if (isSearchSymbolCompilation)
                    {
                        originalType          = kvp.Value.OriginalDefinition;
                        expectedForwardedType = kvp.Key.OriginalDefinition;
                    }
                    else
                    {
                        originalType          = kvp.Key.OriginalDefinition;
                        expectedForwardedType = kvp.Value.OriginalDefinition;
                    }

                    foreach (var referencedAssembly in referencedAssemblies[originalType.ContainingAssembly.Name])
                    {
                        var fullyQualifiedTypeName = originalType.MetadataName;
                        if (originalType.ContainingNamespace != null)
                        {
                            fullyQualifiedTypeName = originalType.ContainingNamespace.ToDisplayString(SymbolDisplayFormats.SignatureFormat) +
                                                     "." + fullyQualifiedTypeName;
                        }

                        // Resolve forwarded type and verify that the types from different assembly are indeed equivalent.
                        var forwardedType = referencedAssembly.ResolveForwardedType(fullyQualifiedTypeName);
                        if (Equals(forwardedType, expectedForwardedType))
                        {
                            verifiedKeys.Add(kvp.Key);
                            verifiedCount++;
                        }
                    }
                }
            }

            return(verifiedCount);
        }
 public void AddEdge(T n1, T n2)
 {
     AddNode(n1);
     AddNode(n2);
     edges.Add(n1, n2);
 }
Пример #39
0
 protected override bool OnAdding(DdeCustomTable item)
 {
     _customTablesByType.Add(item.Schema.EntityType, item);
     _customTablesByCaption.Add(item.TableName, item);
     return(base.OnAdding(item));
 }
Пример #40
0
            /// <summary>
            /// Optimizes local functions such that if a local function only references other local functions without closures, it itself doesn't need a closure.
            /// </summary>
            private void RemoveUnneededReferences()
            {
                // Note: methodGraph is the inverse of the dependency graph
                var methodGraph      = new MultiDictionary <MethodSymbol, MethodSymbol>();
                var capturesThis     = new HashSet <MethodSymbol>();
                var capturesVariable = new HashSet <MethodSymbol>();
                var visitStack       = new Stack <MethodSymbol>();

                foreach (var methodKvp in CapturedVariablesByLambda)
                {
                    foreach (var value in methodKvp.Value)
                    {
                        var method = value as MethodSymbol;
                        if (method != null)
                        {
                            methodGraph.Add(method, methodKvp.Key);
                        }
                        else if (value == _topLevelMethod.ThisParameter)
                        {
                            if (capturesThis.Add(methodKvp.Key))
                            {
                                visitStack.Push(methodKvp.Key);
                            }
                        }
                        else if (capturesVariable.Add(methodKvp.Key) && !capturesThis.Contains(methodKvp.Key)) // if capturesThis contains methodKvp, it's already in the stack.
                        {
                            visitStack.Push(methodKvp.Key);
                        }
                    }
                }

                while (visitStack.Count > 0)
                {
                    var current    = visitStack.Pop();
                    var setToAddTo = capturesVariable.Contains(current) ? capturesVariable : capturesThis;
                    foreach (var capturesCurrent in methodGraph[current])
                    {
                        if (setToAddTo.Add(capturesCurrent))
                        {
                            visitStack.Push(capturesCurrent);
                        }
                    }
                }

                var capturedVariablesNew = new MultiDictionary <Symbol, CSharpSyntaxNode>();

                foreach (var old in CapturedVariables)
                {
                    var method = old.Key as MethodSymbol;
                    // don't add if it's a method that only captures 'this'
                    if (method == null || capturesVariable.Contains(method))
                    {
                        foreach (var oldValue in old.Value)
                        {
                            capturedVariablesNew.Add(old.Key, oldValue);
                        }
                    }
                }
                CapturedVariables = capturedVariablesNew;
                var capturedVariablesByLambdaNew = new MultiDictionary <MethodSymbol, Symbol>();

                foreach (var old in CapturedVariablesByLambda)
                {
                    if (capturesVariable.Contains(old.Key))
                    {
                        foreach (var oldValue in old.Value)
                        {
                            capturedVariablesByLambdaNew.Add(old.Key, oldValue);
                        }
                    }
                    else if (capturesThis.Contains(old.Key))
                    {
                        capturedVariablesByLambdaNew.Add(old.Key, _topLevelMethod.ThisParameter);
                    }
                }
                CapturedVariablesByLambda = capturedVariablesByLambdaNew;
            }
Пример #41
0
	MultiDictionary<int, Tbl_SkillBook_Record> TransferToIdxMultidic(List<Tbl_SkillBook_Record> _list)
	{
		MultiDictionary<int, Tbl_SkillBook_Record> mdicIdx = new MultiDictionary<int, Tbl_SkillBook_Record>();
		
		foreach(Tbl_SkillBook_Record record in _list)
		{
			mdicIdx.Add(record.Skill1_Index, record);
			if(record.ChoiceType == eChoiceType.Choice)
				mdicIdx.Add(record.Skill2_Index, record);
		}
		
		return mdicIdx;
	}
Пример #42
0
        private void ProcessProjectChange(Solution solution, ProjectId projectId)
        {
            this.AssertIsForeground();

            // Remove anything we have associated with this project.
            _projectToInstalledPackageAndVersion.TryRemove(projectId, out var projectState);

            var project = solution.GetProject(projectId);

            if (project == null)
            {
                // Project was removed.  Nothing needs to be done.
                return;
            }

            // We really only need to know the NuGet status for managed language projects.
            // Also, the NuGet APIs may throw on some projects that don't implement the
            // full set of DTE APIs they expect.  So we filter down to just C# and VB here
            // as we know these languages are safe to build up this index for.
            if (project.Language != LanguageNames.CSharp &&
                project.Language != LanguageNames.VisualBasic)
            {
                return;
            }

            // Project was changed in some way.  Let's go find the set of installed packages for it.
            var dteProject = _workspace.TryGetDTEProject(projectId);

            if (dteProject == null)
            {
                // Don't have a DTE project for this project ID.  not something we can query NuGet for.
                return;
            }

            var installedPackages = new MultiDictionary <string, string>();
            var isEnabled         = false;

            // Calling into NuGet.  Assume they may fail for any reason.
            try
            {
                var installedPackageMetadata = _packageServices.GetInstalledPackages(dteProject);
                foreach (var metadata in installedPackageMetadata)
                {
                    if (metadata.VersionString != null)
                    {
                        installedPackages.Add(metadata.Id, metadata.VersionString);
                    }
                }

                isEnabled = true;
            }
            catch (ArgumentException e) when(IsKnownNugetIssue(e))
            {
                // Nuget may throw an ArgumentException when there is something about the project
                // they do not like/support.
            }
            catch (InvalidOperationException e) when(e.StackTrace.Contains("NuGet.PackageManagement.VisualStudio.NetCorePackageReferenceProject.GetPackageSpecsAsync"))
            {
                // NuGet throws an InvalidOperationException if details
                // for the project fail to load. We don't need to report
                // these, and can assume that this will work on a future
                // project change
                // This should be removed with https://github.com/dotnet/roslyn/issues/33187
            }
            catch (Exception e) when(FatalError.ReportWithoutCrash(e))
            {
            }

            var state = new ProjectState(isEnabled, installedPackages);

            _projectToInstalledPackageAndVersion.AddOrUpdate(
                projectId, state, (_1, _2) => state);
        }
Пример #43
0
        public MultiDictionary<Vertex, int> GetDistanceTable()
        {
            var n = this.NumberOfVertices;
            MultiDictionary<Vertex, int> distanceTable = new MultiDictionary<Vertex, int>();
            for (int from = 0; from < n; from++)
            {
                var vFrom = Vertices[from];
                var distanceToAll = Algorithms.DijkstraToAll(vFrom, this);
                foreach (var dist in distanceToAll)
                {
                    var vTo = dist.Key;
                    if (vTo.VertexName > vFrom.VertexName)
                        continue;
                    distanceTable.Add(vFrom, vTo, dist.Value);
                }
            }

            return distanceTable;
        }
 private async Task AddLocationSpan(Location location, Solution solution, HashSet<ValueTuple<Document, TextSpan>> spanSet, MultiDictionary<Document, HighlightSpan> tagList, HighlightSpanKind kind, CancellationToken cancellationToken)
 {
     var span = await GetLocationSpanAsync(solution, location, cancellationToken).ConfigureAwait(false);
     if (span != null && !spanSet.Contains(span.Value))
     {
         spanSet.Add(span.Value);
         tagList.Add(span.Value.Item1, new HighlightSpan(span.Value.Item2, kind));
     }
 }
Пример #45
0
        private void ReconnectTerminals(Graph workingSolution, Graph problemInstance, Graph problemInstanceDistance)
        {
            Stopwatch reconnectStopwatch = new Stopwatch();
            reconnectStopwatch.Start();

            var components = workingSolution.CreateComponentTable();
            var componentsToConnect =
                components.Where(x => problemInstance.Terminals.Contains(x.Key))
                    .Select(x => x.Value)
                    .Distinct()
                    .ToList();

            if (componentsToConnect.Count <= 1) return;

            MultiDictionary<int, Tuple<Vertex, Vertex>> componentConnectingPathDictionary = new MultiDictionary<int, Tuple<Vertex, Vertex>>();
            List<Vertex> componentGraphVertices = new List<Vertex>();
            foreach (var i in componentsToConnect)
                componentGraphVertices.Add(new Vertex(i));
            Graph componentGraph = new Graph(componentGraphVertices);

            for (int i = 0; i < componentsToConnect.Count; i++)
            {
                int fromComponent = componentsToConnect[i];
                for (int j = i + 1; j < componentsToConnect.Count; j++)
                {
                    int toComponent = componentsToConnect[j];
                    int minDistance = int.MaxValue;

                    foreach (var fromVertex in components.Where(x => x.Value == fromComponent)
                                                         .Select(x => x.Key))
                    {
                        var distanceEdges = problemInstanceDistance.GetEdgesForVertex(fromVertex);
                        foreach (var toVertexEdge in distanceEdges)
                        {
                            var toVertex = toVertexEdge.Other(fromVertex);
                            if (components[toVertex] != toComponent)
                                continue;

                            int distance = toVertexEdge.Cost;
                            if (!componentConnectingPathDictionary.ContainsKey(fromComponent, toComponent))
                            {
                                componentConnectingPathDictionary.Add(fromComponent, toComponent, new Tuple<Vertex, Vertex>(fromVertex, toVertex));
                                componentGraph.AddEdge(new Edge(componentGraphVertices[i], componentGraphVertices[j], minDistance));
                            }

                            if (distance < minDistance)
                            {
                                minDistance = distance;
                                componentConnectingPathDictionary[fromComponent, toComponent] = new Tuple<Vertex, Vertex>(fromVertex, toVertex);
                                componentGraph.GetEdgesForVertex(componentGraphVertices[i])
                                    .Single(x => x.Other(componentGraphVertices[i]) == componentGraphVertices[j])
                                    .Cost = minDistance;
                            }
                        }
                    }
                }
            }
            componentGraph = Algorithms.Kruskal(componentGraph);
            foreach (var edge in componentGraph.Edges)
            {
                var v1 = edge.Either();
                var v2 = edge.Other(v1);
                var vertices = componentConnectingPathDictionary[v1.VertexName, v2.VertexName];
                var path = Algorithms.DijkstraPath(vertices.Item1, vertices.Item2, problemInstance);
                foreach (var pathEdge in path.Edges)
                    workingSolution.AddEdge(pathEdge);
            }

            reconnectStopwatch.Stop();
        }
Пример #46
0
        /// <summary>
        /// Runs an approximation of the Special Distance Test to reduce the graph.
        /// This test runs much faster and offers only a small difference in performance.
        /// </summary>
        /// <param name="graph">The graph on which to run the test.</param>
        /// <returns>The reduced graph.</returns>
        public static ReductionResult RunTest(Graph graph)
        {
            if (!graph.Terminals.All(graph.ContainsVertex))
                Debugger.Break();

            var tmst = Algorithms.Kruskal(graph.TerminalDistanceGraph);
            var terminalSpecialDistances = new MultiDictionary<Vertex, int>();
            for (int i = 0; i < graph.Terminals.Count - 1; i++)
            {
                var tFrom = graph.Terminals[i];
                var toAll = Algorithms.DijkstraPathToAll(tFrom, tmst);
                for (int j = i + 1; j < graph.Terminals.Count; j++)
                {
                    var tTo = graph.Terminals[j];
                    var path = toAll[tTo];
                    var sd = path.Edges.Max(x => x.Cost);
                    terminalSpecialDistances.Add(tFrom, tTo, sd);
                }
            }

            var result = new ReductionResult();

            // Find all special distances between terminals
            int count = 0;
            int e = graph.NumberOfEdges;

            Dictionary<Vertex, Path> nearest = new Dictionary<Vertex, Path>();
            HashSet<Edge> remove = new HashSet<Edge>();

            int edgesWithoutRemoval = 0;

            foreach (var edge in graph.Edges.OrderByDescending(x => x.Cost))
            {
                count++;
                var vFrom = edge.Either();
                var vTo = edge.Other(vFrom);

                int SDEstimate = int.MaxValue;
                Path pathToNearestFrom = null;
                if (nearest.ContainsKey(vFrom))
                    pathToNearestFrom = nearest[vFrom];
                else
                {
                    pathToNearestFrom = Algorithms.NearestTerminal(vFrom, graph);
                    nearest.Add(vFrom, pathToNearestFrom);
                }
                var aNearestTerminalFrom = pathToNearestFrom.End;

                Path pathToNearestTo = null;
                if (nearest.ContainsKey(vTo))
                    pathToNearestTo = nearest[vTo];
                else
                {
                    pathToNearestTo = Algorithms.NearestTerminal(vTo, graph);
                    nearest.Add(vTo, pathToNearestTo);
                }
                var bNearestTerminalTo = pathToNearestTo.End;

                // SD = Max( dist(v, z_a), dist(w, z_b), sd(z_a, z_b) )
                var sd = Math.Max(pathToNearestFrom.TotalCost, pathToNearestTo.TotalCost);
                if (aNearestTerminalFrom != bNearestTerminalTo)
                {
                    var sdTerminals = terminalSpecialDistances[aNearestTerminalFrom, bNearestTerminalTo];
                    sd = Math.Max(sd, sdTerminals);
                }

                if (sd < SDEstimate)
                    SDEstimate = sd;

                if (edge.Cost > SDEstimate)
                {
                    edgesWithoutRemoval = 0;
                    remove.Add(edge);
                }
                else if (++edgesWithoutRemoval >= graph.NumberOfEdges / 100) // Expecting a 1% reduction
                {
                    break;
                }
            }

            foreach (var edge in remove)
            {
                graph.RemoveEdge(edge);
                result.RemovedEdges.Add(edge);
            }

            return result;
        }
Пример #47
0
        /// <summary>
        /// Find all enabled abbreviations in the provided molecule. They are not
        /// added to the existing Sgroups and may need filtering.
        /// </summary>
        /// <param name="mol">molecule</param>
        /// <returns>list of new abbreviation Sgroups</returns>
        public IList <Sgroup> Generate(IAtomContainer mol)
        {
            // mark which atoms have already been abbreviated or are
            // part of an existing Sgroup
            var usedAtoms = new HashSet <IAtom>();
            var sgroups   = mol.GetCtabSgroups();

            if (sgroups != null)
            {
                foreach (var sgroup in sgroups)
                {
                    foreach (var atom in sgroup.Atoms)
                    {
                        usedAtoms.Add(atom);
                    }
                }
            }

            var newSgroups = new List <Sgroup>();

            // disconnected abbreviations, salts, common reagents, large compounds
            if (!usedAtoms.Any())
            {
                try
                {
                    var    copy   = AtomContainerManipulator.CopyAndSuppressedHydrogens(mol);
                    string cansmi = usmigen.Create(copy);
                    if (disconnectedAbbreviations.TryGetValue(cansmi, out string label) && !disabled.Contains(label) && ContractToSingleLabel)
                    {
                        var sgroup = new Sgroup
                        {
                            Type      = SgroupType.CtabAbbreviation,
                            Subscript = label
                        };
                        foreach (var atom in mol.Atoms)
                        {
                            sgroup.Atoms.Add(atom);
                        }
                        return(new[] { sgroup });
                    }
                    else if (cansmi.Contains("."))
                    {
                        var parts = ConnectivityChecker.PartitionIntoMolecules(mol);

                        // leave one out
                        Sgroup best = null;
                        for (int i = 0; i < parts.Count; i++)
                        {
                            var a = parts[i];
                            var b = a.Builder.NewAtomContainer();
                            for (int j = 0; j < parts.Count; j++)
                            {
                                if (j != i)
                                {
                                    b.Add(parts[j]);
                                }
                            }
                            var sgroup1 = GetAbbr(a);
                            var sgroup2 = GetAbbr(b);
                            if (sgroup1 != null && sgroup2 != null && ContractToSingleLabel)
                            {
                                var combined = new Sgroup();
                                label = null;
                                foreach (var atom in sgroup1.Atoms)
                                {
                                    combined.Atoms.Add(atom);
                                }
                                foreach (var atom in sgroup2.Atoms)
                                {
                                    combined.Atoms.Add(atom);
                                }
                                if (sgroup1.Subscript.Length > sgroup2.Subscript.Length)
                                {
                                    combined.Subscript = sgroup1.Subscript + String_Interpunct + sgroup2.Subscript;
                                }
                                else
                                {
                                    combined.Subscript = sgroup2.Subscript + String_Interpunct + sgroup1.Subscript;
                                }
                                combined.Type = SgroupType.CtabAbbreviation;
                                return(new[] { combined });
                            }
                            if (sgroup1 != null && (best == null || sgroup1.Atoms.Count > best.Atoms.Count))
                            {
                                best = sgroup1;
                            }
                            if (sgroup2 != null && (best == null || sgroup2.Atoms.Count < best.Atoms.Count))
                            {
                                best = sgroup2;
                            }
                        }
                        if (best != null)
                        {
                            newSgroups.Add(best);
                            foreach (var atom in best.Atoms)
                            {
                                usedAtoms.Add(atom);
                            }
                        }
                    }
                }
                catch (CDKException)
                {
                }
            }

            var fragments  = GenerateFragments(mol);
            var sgroupAdjs = new MultiDictionary <IAtom, Sgroup>();

            foreach (var frag in fragments)
            {
                try
                {
                    var smi = usmigen.Create(AtomContainerManipulator.CopyAndSuppressedHydrogens(frag));
                    if (!connectedAbbreviations.TryGetValue(smi, out string label) || disabled.Contains(label))
                    {
                        continue;
                    }

                    bool overlap = false;

                    // note: first atom is '*'
                    var numAtoms = frag.Atoms.Count;
                    var numBonds = frag.Bonds.Count;
                    for (int i = 1; i < numAtoms; i++)
                    {
                        if (usedAtoms.Contains(frag.Atoms[i]))
                        {
                            overlap = true;
                            break;
                        }
                    }

                    // overlaps with previous assignment
                    if (overlap)
                    {
                        continue;
                    }

                    // create new abbreviation Sgroup
                    var sgroup = new Sgroup
                    {
                        Type      = SgroupType.CtabAbbreviation,
                        Subscript = label
                    };

                    var   attachBond = frag.Bonds[0].GetProperty <IBond>(PropertyName_CutBond);
                    IAtom attachAtom = null;
                    sgroup.Bonds.Add(attachBond);
                    for (int i = 1; i < numAtoms; i++)
                    {
                        var atom = frag.Atoms[i];
                        usedAtoms.Add(atom);
                        sgroup.Atoms.Add(atom);
                        if (attachBond.Begin.Equals(atom))
                        {
                            attachAtom = attachBond.End;
                        }
                        else if (attachBond.End.Equals(atom))
                        {
                            attachAtom = attachBond.Begin;
                        }
                    }

                    if (attachAtom != null)
                    {
                        sgroupAdjs.Add(attachAtom, sgroup);
                    }
                    newSgroups.Add(sgroup);
                }
                catch (CDKException)
                {
                    // ignore
                }
            }

            if (!ContractOnHetero)
            {
                return(newSgroups);
            }

            // now collapse
            foreach (var attach in mol.Atoms)
            {
                if (usedAtoms.Contains(attach))
                {
                    continue;
                }

                // skip charged or isotopic labelled, C or R/*, H, He
                if ((attach.FormalCharge != null && attach.FormalCharge != 0) ||
                    attach.MassNumber != null ||
                    attach.AtomicNumber == 6 ||
                    attach.AtomicNumber < 2)
                {
                    continue;
                }

                var hcount   = attach.ImplicitHydrogenCount.Value;
                var xatoms   = new HashSet <IAtom>();
                var xbonds   = new HashSet <IBond>();
                var newbonds = new HashSet <IBond>();
                xatoms.Add(attach);

                var nbrSymbols = new List <string>();
                var todelete   = new HashSet <Sgroup>();
                foreach (var sgroup in sgroupAdjs[attach])
                {
                    if (ContainsChargeChar(sgroup.Subscript))
                    {
                        continue;
                    }
                    if (sgroup.Bonds.Count != 1)
                    {
                        continue;
                    }
                    var xbond = sgroup.Bonds.First();
                    xbonds.Add(xbond);
                    foreach (var a in sgroup.Atoms)
                    {
                        xatoms.Add(a);
                    }
                    if (attach.Symbol.Length == 1 &&
                        char.IsLower(sgroup.Subscript[0]))
                    {
                        if (ChemicalElement.OfSymbol(attach.Symbol + sgroup.Subscript[0]) != ChemicalElement.R)
                        {
                            goto continue_collapse;
                        }
                    }
                    nbrSymbols.Add(sgroup.Subscript);
                    todelete.Add(sgroup);
                }
                int numSGrpNbrs = nbrSymbols.Count;
                foreach (var bond in mol.GetConnectedBonds(attach))
                {
                    if (!xbonds.Contains(bond))
                    {
                        var nbr = bond.GetOther(attach);
                        // contract terminal bonds
                        if (mol.GetConnectedBonds(nbr).Count() == 1)
                        {
                            if (nbr.MassNumber != null ||
                                (nbr.FormalCharge != null && nbr.FormalCharge != 0))
                            {
                                newbonds.Add(bond);
                            }
                            else if (nbr.AtomicNumber == 1)
                            {
                                hcount++;
                                xatoms.Add(nbr);
                            }
                            else if (nbr.AtomicNumber > 0)
                            {
                                nbrSymbols.Add(NewSymbol(nbr.AtomicNumber, nbr.ImplicitHydrogenCount.Value, false));
                                xatoms.Add(nbr);
                            }
                        }
                        else
                        {
                            newbonds.Add(bond);
                        }
                    }
                }

                // reject if no symbols
                // reject if no bonds (<1), except if all symbols are identical... (HashSet.size==1)
                // reject if more that 2 bonds
                if (!nbrSymbols.Any() ||
                    newbonds.Count < 1 && (new HashSet <string>(nbrSymbols).Count != 1) ||
                    newbonds.Count > 2)
                {
                    continue;
                }

                // create the symbol
                var sb = new StringBuilder();
                sb.Append(NewSymbol(attach.AtomicNumber, hcount, newbonds.Count == 0));
                string prev  = null;
                int    count = 0;
                nbrSymbols.Sort((o1, o2) =>
                {
                    int cmp = o1.Length.CompareTo(o2.Length);
                    if (cmp != 0)
                    {
                        return(cmp);
                    }
                    return(o1.CompareTo(o2));
                });
                foreach (string nbrSymbol in nbrSymbols)
                {
                    if (nbrSymbol.Equals(prev))
                    {
                        count++;
                    }
                    else
                    {
                        bool useParen = count == 0 || CountUpper(prev) > 1 || (prev != null && nbrSymbol.StartsWith(prev));
                        AppendGroup(sb, prev, count, useParen);
                        prev  = nbrSymbol;
                        count = 1;
                    }
                }
                AppendGroup(sb, prev, count, false);

                // remove existing
                foreach (var e in todelete)
                {
                    newSgroups.Remove(e);
                }

                // create new
                var newSgroup = new Sgroup
                {
                    Type      = SgroupType.CtabAbbreviation,
                    Subscript = sb.ToString()
                };
                foreach (var bond in newbonds)
                {
                    newSgroup.Bonds.Add(bond);
                }
                foreach (var atom in xatoms)
                {
                    newSgroup.Atoms.Add(atom);
                }

                newSgroups.Add(newSgroup);
                foreach (var a in xatoms)
                {
                    usedAtoms.Add(a);
                }
continue_collapse:
                ;
            }

            return(newSgroups);
        }
Пример #48
0
 //INFO: using the old BasicReasoner which appears to be much slower
 //private static void AddSentencesTrueByRules(
 //    MultiDictionary<ISentenceForm, Fact> sentencesByForm,
 //    ISentenceFormModel model)
 //{
 //    BasicReasoner prover = GameContainer.Reasoner;
 //    var context = new ProofContext(new BasicKB(), GameContainer.Parser);
 //    foreach (ISentenceForm form in model.ConstantSentenceForms)
 //    {
 //        Fact query = form.GetSentenceFromTuple(GetVariablesTuple(form.TupleSize));
 //        IEnumerable<GroundFact> answers = prover.GetAllAnswers(query, context);
 //        foreach (GroundFact result in answers)
 //        {
 //            //ConcurrencyUtils.checkForInterruption();
 //            //Variables may end up being replaced with functions, which is not what we want here, so we have to double-check that the form is correct.
 //            if (form.Matches(result))
 //                sentencesByForm.Add(form, result);
 //        }
 //    }
 //}
 private static void AddSentencesTrueByRules(MultiDictionary<ISentenceForm, Fact> sentencesByForm, ISentenceFormModel model)
 {
     AimaProver prover = new AimaProver(model.Description);
     foreach (ISentenceForm form in model.ConstantSentenceForms)
     {
         Fact query = form.GetSentenceFromTuple(GetVariablesTuple(form.TupleSize));
         HashSet<Fact> context = new HashSet<Fact>();
         foreach (Fact result in prover.AskAll(query, context))
             if (form.Matches(result))
                 sentencesByForm.Add(form, result);
     }
 }
Пример #49
0
 public void Add(K1 firstKey, K2 secondKey, V elementValue)
 {
     firstKeyDictionary.Add(firstKey, elementValue);
     secondKeyDictionary.Add(secondKey, elementValue);
 }
        /// <summary>
        /// Reporting is done in a function that returns a string, to avoid any performance impact when the trace log is not enabled.
        /// </summary>
        private string ReportPermissions(IUserInfo userInfo, PrincipalInfo principal, Lazy<IDictionary<Guid, string>> roleNamesIndex,
            IEnumerable<Permission> userPermissions, IEnumerable<ClaimInfo> claims, IEnumerable<bool> userHasClaims)
        {
            var report = new List<string>();

            // Create an index of permissions:

            var permissionsByClaim = new MultiDictionary<Guid, Permission>();
            foreach (var permission in userPermissions)
                permissionsByClaim.Add(permission.ClaimID, permission);

            // Analyze permissions for required claims:

            foreach (var claimResult in claims.Zip(userHasClaims, (Claim, UserHasIt) => new { Claim, UserHasIt }))
            {
                var claimPermissions = claimResult.Claim.ID != null
                    ? permissionsByClaim.Get(claimResult.Claim.ID.Value)
                    : new Permission[] { };

                var permissionsDescription = claimPermissions
                    .Select(permission => new
                        {
                            permission.IsAuthorized,
                            PrincipalOrRoleName = permission.PrincipalID != null
                                ? ("principal " + (permission.PrincipalID.Value == principal.ID ? principal.Name : permission.PrincipalID.Value.ToString()))
                                : ("role " + GetRoleNameSafe(permission.RoleID.Value, roleNamesIndex))
                        })
                    .ToList();

                var allowedFor = permissionsDescription.Where(p => p.IsAuthorized).Select(p => p.PrincipalOrRoleName).ToList();
                var deniedFor = permissionsDescription.Where(p => !p.IsAuthorized).Select(p => p.PrincipalOrRoleName).ToList();

                string explanation = "User " + userInfo.UserName + " " + (claimResult.UserHasIt ? "has" : "doesn't have")
                    + " claim '" + claimResult.Claim.Resource + " " + claimResult.Claim.Right + "'. It is ";

                if (deniedFor.Count != 0)
                    if (allowedFor.Count != 0)
                        explanation += "denied for " + string.Join(", ", deniedFor) + " and allowed for " + string.Join(", ", allowedFor) + " (deny overrides allow).";
                    else
                        explanation += "denied for " + string.Join(", ", deniedFor) + ".";
                else
                    if (allowedFor.Count != 0)
                        explanation += "allowed for " + string.Join(", ", allowedFor) + ".";
                    else
                        if (claimResult.Claim.ID == null)
                            explanation += "denied by default (the claim does not exist or is no longer active).";
                        else
                            explanation += "denied by default (no permissions defined).";

                report.Add(explanation);
            }

            return string.Join("\r\n", report);
        }
Пример #51
0
 public void Add(T item)
 {
     _items.Add(item, item);
 }
Пример #52
0
        private static SymbolTreeInfo TryReadSymbolTreeInfo(
            ObjectReader reader,
            Checksum checksum,
            Func <string, ImmutableArray <Node>, Task <SpellChecker> > createSpellCheckerTask)
        {
            try
            {
                var concatenatedNames = reader.ReadString();

                var nodeCount = reader.ReadInt32();
                var nodes     = ArrayBuilder <Node> .GetInstance(nodeCount);

                for (var i = 0; i < nodeCount; i++)
                {
                    var start       = reader.ReadInt32();
                    var length      = reader.ReadInt32();
                    var parentIndex = reader.ReadInt32();

                    nodes.Add(new Node(new TextSpan(start, length), parentIndex));
                }

                var inheritanceMap         = new OrderPreservingMultiDictionary <int, int>();
                var inheritanceMapKeyCount = reader.ReadInt32();
                for (var i = 0; i < inheritanceMapKeyCount; i++)
                {
                    var key        = reader.ReadInt32();
                    var valueCount = reader.ReadInt32();

                    for (var j = 0; j < valueCount; j++)
                    {
                        var value = reader.ReadInt32();
                        inheritanceMap.Add(key, value);
                    }
                }

                MultiDictionary <string, ExtensionMethodInfo> simpleTypeNameToExtensionMethodMap;
                ImmutableArray <ExtensionMethodInfo>          extensionMethodOfComplexType;

                var keyCount = reader.ReadInt32();
                if (keyCount == 0)
                {
                    simpleTypeNameToExtensionMethodMap = null;
                }
                else
                {
                    simpleTypeNameToExtensionMethodMap = new MultiDictionary <string, ExtensionMethodInfo>();

                    for (var i = 0; i < keyCount; i++)
                    {
                        var typeName   = reader.ReadString();
                        var valueCount = reader.ReadInt32();

                        for (var j = 0; j < valueCount; j++)
                        {
                            var containerName = reader.ReadString();
                            var name          = reader.ReadString();

                            simpleTypeNameToExtensionMethodMap.Add(typeName, new ExtensionMethodInfo(containerName, name));
                        }
                    }
                }

                var arrayLength = reader.ReadInt32();
                if (arrayLength == 0)
                {
                    extensionMethodOfComplexType = ImmutableArray <ExtensionMethodInfo> .Empty;
                }
                else
                {
                    var builder = ArrayBuilder <ExtensionMethodInfo> .GetInstance(arrayLength);

                    for (var i = 0; i < arrayLength; ++i)
                    {
                        var containerName = reader.ReadString();
                        var name          = reader.ReadString();
                        builder.Add(new ExtensionMethodInfo(containerName, name));
                    }

                    extensionMethodOfComplexType = builder.ToImmutableAndFree();
                }

                var nodeArray        = nodes.ToImmutableAndFree();
                var spellCheckerTask = createSpellCheckerTask(concatenatedNames, nodeArray);
                return(new SymbolTreeInfo(
                           checksum, concatenatedNames, nodeArray, spellCheckerTask, inheritanceMap,
                           extensionMethodOfComplexType, simpleTypeNameToExtensionMethodMap));
            }
            catch
            {
                Logger.Log(FunctionId.SymbolTreeInfo_ExceptionInCacheRead);
            }

            return(null);
        }
Пример #53
0
            /// <summary>
            /// Optimizes local functions such that if a local function only references other local functions without closures, it itself doesn't need a closure.
            /// </summary>
            private void RemoveUnneededReferences()
            {
                // Note: methodGraph is the inverse of the dependency graph
                var methodGraph = new MultiDictionary<MethodSymbol, MethodSymbol>();
                var capturesThis = new HashSet<MethodSymbol>();
                var capturesVariable = new HashSet<MethodSymbol>();
                var visitStack = new Stack<MethodSymbol>();
                foreach (var methodKvp in CapturedVariablesByLambda)
                {
                    foreach (var value in methodKvp.Value)
                    {
                        var method = value as MethodSymbol;
                        if (method != null)
                        {
                            methodGraph.Add(method, methodKvp.Key);
                        }
                        else if (value == _topLevelMethod.ThisParameter)
                        {
                            if (capturesThis.Add(methodKvp.Key))
                            {
                                visitStack.Push(methodKvp.Key);
                            }
                        }
                        else if (capturesVariable.Add(methodKvp.Key) && !capturesThis.Contains(methodKvp.Key)) // if capturesThis contains methodKvp, it's already in the stack.
                        {
                            visitStack.Push(methodKvp.Key);
                        }
                    }
                }

                while (visitStack.Count > 0)
                {
                    var current = visitStack.Pop();
                    var setToAddTo = capturesVariable.Contains(current) ? capturesVariable : capturesThis;
                    foreach (var capturesCurrent in methodGraph[current])
                    {
                        if (setToAddTo.Add(capturesCurrent))
                        {
                            visitStack.Push(capturesCurrent);
                        }
                    }
                }

                var capturedVariablesNew = new MultiDictionary<Symbol, CSharpSyntaxNode>();
                foreach (var old in CapturedVariables)
                {
                    var method = old.Key as MethodSymbol;
                    // don't add if it's a method that only captures 'this'
                    if (method == null || capturesVariable.Contains(method))
                    {
                        foreach (var oldValue in old.Value)
                        {
                            capturedVariablesNew.Add(old.Key, oldValue);
                        }
                    }
                }
                CapturedVariables = capturedVariablesNew;
                var capturedVariablesByLambdaNew = new MultiDictionary<MethodSymbol, Symbol>();
                foreach (var old in CapturedVariablesByLambda)
                {
                    if (capturesVariable.Contains(old.Key))
                    {
                        foreach (var oldValue in old.Value)
                        {
                            capturedVariablesByLambdaNew.Add(old.Key, oldValue);
                        }
                    }
                    else if (capturesThis.Contains(old.Key))
                    {
                        capturedVariablesByLambdaNew.Add(old.Key, _topLevelMethod.ThisParameter);
                    }
                }
                CapturedVariablesByLambda = capturedVariablesByLambdaNew;
            }
Пример #54
0
        void m_kmlWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            KmlThreadArg arg = e.Argument as KmlThreadArg;

            e.Result = false;

            MultiDictionary <string, ImageInfo> filesGrouped4x4 = new MultiDictionary <string, ImageInfo>(false);

            {
                List <ImageInfo> allFiles = new List <ImageInfo>();
                List <string>    rows     = new List <string>();
                List <string>    columns  = new List <string>();

                Regex filePattern = new Regex(@"Img_(?<Row>\d+)_(?<Column>\d+)_(?<Zoom>\d+)\.*", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline);

                foreach (string item in Directory.GetFiles(arg.SelectedPath, "*.*", SearchOption.TopDirectoryOnly))
                {
                    Match match = filePattern.Match(item);
                    if (match.Success)
                    {
                        string row    = match.Groups["Row"].Value;
                        string column = match.Groups["Column"].Value;

                        allFiles.Add(new ImageInfo(item, row, column, match.Groups["Zoom"].Value));

                        if (!rows.Contains(row))
                        {
                            rows.Add(row);
                        }

                        if (!columns.Contains(column))
                        {
                            columns.Add(column);
                        }
                    }
                }

                rows.Sort();
                columns.Sort();

                int totalRowRun    = 0;
                int totalColumnRun = 0;

                if (rows.Count > 0)
                {
                    totalRowRun = (int)rows.Count / 4;
                    if (rows.Count % 4 > 0)
                    {
                        totalRowRun++;
                    }
                }

                if (columns.Count > 0)
                {
                    totalColumnRun = (int)columns.Count / 4;
                    if (columns.Count % 4 > 0)
                    {
                        totalColumnRun++;
                    }
                }

                string rowKey;
                string columnKey;

                string _4x4Key;

                for (int indexRow = 0; indexRow < totalRowRun; indexRow++)
                {
                    int    actualStartRow = indexRow * 4;
                    string rowStartKey    = rows[actualStartRow];

                    for (int indexX = actualStartRow; indexX < rows.Count && indexX < actualStartRow + 4; indexX++)
                    {
                        rowKey = rows[indexX];

                        for (int indexColumn = 0; indexColumn < totalColumnRun; indexColumn++)
                        {
                            int    actualStartColumn = indexColumn * 4;
                            string startColumnKey    = columns[actualStartColumn];
                            _4x4Key = String.Format("{0}x{1}", rowStartKey, startColumnKey);


                            for (int indexY = actualStartColumn; indexY < columns.Count && indexY < actualStartColumn + 4; indexY++)
                            {
                                columnKey = columns[indexY];
                                ImageInfo data = allFiles.GetData <ImageInfo>(rowKey, columnKey);

                                filesGrouped4x4.Add(_4x4Key, data);
                            }
                        }
                    }
                }
            }
            {
                string kmlFolder = String.Format("{0}\\{1}\\", arg.SelectedPath, arg.KmlName);

                if (Directory.Exists(kmlFolder))
                {
                    System.Windows.MessageBox.Show("Folder already exits, select diffrent folder");
                    return;
                }

                Directory.CreateDirectory(kmlFolder);

                ImageInfo imageInfo;

                TileDownLoader.Projection.MercatorProjection projections = new TileDownLoader.Projection.MercatorProjection();

                List <GroundOverlayType> overlays = new List <GroundOverlayType>();
                int index = 0;
                foreach (string imgkey in filesGrouped4x4.Keys)
                {
                    if (this.KmlWorker.CancellationPending)
                    {
                        return;
                    }

                    this.KmlWorker.ReportProgress((int)(((double)index / (double)filesGrouped4x4.Keys.Count) * 100.0));

                    imageInfo = filesGrouped4x4[imgkey].First <ImageInfo>();

                    string fileName = String.Format("{0}\\Img_{1}_{2}_{3}.jpeg", kmlFolder, imageInfo.Row, imageInfo.Column, imageInfo.Zoom);

                    MultiDictionary <string, ImageInfo> tempData = new MultiDictionary <string, ImageInfo>(false);

                    foreach (ImageInfo item in filesGrouped4x4[imgkey])
                    {
                        tempData.Add(item.Row, item);
                    }

                    int rowCount    = tempData.Keys.Count;
                    int columnCount = tempData[tempData.Keys.First <string>()].Count;
                    int imageWidth  = rowCount * 256;
                    int imageHeight = columnCount * 256;

                    TileDownLoader.Projection.Point imgPt = new TileDownLoader.Projection.Point(int.Parse(imageInfo.Row), int.Parse(imageInfo.Column));

                    TileDownLoader.Projection.Point imgXYInVirtualSingleImageStPoint = projections.FromTileXYToPixel(imgPt);

                    TileDownLoader.Projection.Point imgXYInVirtualSingleImageEtPoint = new TileDownLoader.Projection.Point(imgXYInVirtualSingleImageStPoint.X + imageWidth,
                                                                                                                           imgXYInVirtualSingleImageStPoint.Y + imageHeight);

                    TileDownLoader.Projection.Location latlng1 = projections.FromPixelToLatLng(imgXYInVirtualSingleImageStPoint, int.Parse(imageInfo.Zoom));
                    TileDownLoader.Projection.Location latlng2 = projections.FromPixelToLatLng(imgXYInVirtualSingleImageEtPoint, int.Parse(imageInfo.Zoom));


                    GroundOverlayType gndOverlay = new GroundOverlayType();

                    gndOverlay.LatLonBox = new LatLonBoxType();

                    gndOverlay.LatLonBox.north = latlng1.Latitude;
                    gndOverlay.LatLonBox.south = latlng2.Latitude;
                    gndOverlay.LatLonBox.east  = latlng2.Longitude;
                    gndOverlay.LatLonBox.west  = latlng1.Longitude;

                    gndOverlay.name      = System.IO.Path.GetFileNameWithoutExtension(fileName);
                    gndOverlay.color     = new byte[] { 0xff, 0xff, 0xff, 0xff };
                    gndOverlay.Icon      = new LinkType();
                    gndOverlay.Icon.href = System.IO.Path.GetFileName(fileName);

                    System.Drawing.Bitmap stichedBmp = new System.Drawing.Bitmap(imageWidth, imageHeight);

                    System.Drawing.Graphics grp = System.Drawing.Graphics.FromImage(stichedBmp);
                    int           rowLoop       = 0;
                    int           columnLoop    = 0;
                    List <string> keysTemp      = new List <string>(tempData.Keys);
                    keysTemp.Sort();
                    foreach (string key in keysTemp)
                    {
                        int x = rowLoop * 256;
                        columnLoop = 0;
                        foreach (ImageInfo imgData in tempData[key])
                        {
                            int y = columnLoop * 256;

                            grp.DrawImage(new System.Drawing.Bitmap(imgData.Path), new System.Drawing.Point(x, y));
                            columnLoop++;
                        }
                        rowLoop++;
                    }

                    grp.Dispose();

                    // EncoderParameter object in the array.

                    System.Drawing.Imaging.ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg");

                    System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);

                    System.Drawing.Imaging.EncoderParameter myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
                    myEncoderParameters.Param[0] = myEncoderParameter;

                    stichedBmp.Save(fileName, myImageCodecInfo, myEncoderParameters);

                    stichedBmp.Dispose();

                    overlays.Add(gndOverlay);

                    index++;
                }

                List <List <GroundOverlayType> > splitedOverlays = new List <List <GroundOverlayType> >();

                for (int localIndex = 0; localIndex < overlays.Count; localIndex += 100)
                {
                    int lastData = (localIndex + 100) < overlays.Count ? localIndex + 100 : overlays.Count;

                    List <GroundOverlayType> tempOverlays = new List <GroundOverlayType>();

                    for (int subIndex = localIndex; subIndex < lastData; subIndex++)
                    {
                        tempOverlays.Add(overlays[subIndex]);
                    }

                    splitedOverlays.Add(tempOverlays);
                }

                int fileCount = 1;

                foreach (List <GroundOverlayType> item in splitedOverlays)
                {
                    GenerateKmlFile(arg, kmlFolder, item, fileCount);
                    fileCount++;
                }
            }

            this.KmlWorker.ReportProgress(100);

            e.Result = true;
        }
Пример #55
0
        public static StoreMulti <Tuple <T, TG>, TK> GetDictMulti <T, TG, TK>(List <Tuple <T, TG> > entries, string primaryKeyName1, string primaryKeyName2)
        {
            if (entries.Count == 0)
            {
                return(null);
            }

            // TODO: Add new config option "Verify data against DB"
            if (!SQLConnector.Enabled)
            {
                return(null);
            }

            var tableAttrs = (DBTableNameAttribute[])typeof(TK).GetCustomAttributes(typeof(DBTableNameAttribute), false);

            if (tableAttrs.Length <= 0)
            {
                return(null);
            }
            var tableName = tableAttrs[0].Name;

            var fields = Utilities.GetFieldsAndAttribute <TK, DBFieldNameAttribute>();

            fields.RemoveAll(field => field.Item2.Name == null);

            var fieldCount = 2;
            var fieldNames = new StringBuilder();

            fieldNames.Append(primaryKeyName1 + ",");
            fieldNames.Append(primaryKeyName2 + ",");
            foreach (var field in fields)
            {
                fieldNames.Append(field.Item2);
                fieldNames.Append(",");
                fieldCount += field.Item2.Count;
            }

            // WHERE (a = x1 AND b = y1) OR (a = x2 AND b = y2) OR ...

            var whereClause = new StringBuilder();
            var ji          = 0;

            foreach (var tuple in entries)
            {
                ji += 1;
                whereClause.Append("(")
                .Append(primaryKeyName1)
                .Append(" = ")
                .Append(tuple.Item1)
                .Append(" AND ")
                .Append(primaryKeyName2)
                .Append(" = ")
                .Append(tuple.Item2)
                .Append(")");
                if (ji != entries.Count)
                {
                    whereClause.Append(" OR ");
                }
            }

            var query = string.Format("SELECT {0} FROM {1}.{2} WHERE {3}",
                                      fieldNames.ToString().TrimEnd(','), Settings.TDBDatabase, tableName, whereClause);

            var dict = new MultiDictionary <Tuple <T, TG>, TK>(true);

            using (var reader = SQLConnector.ExecuteQuery(query))
            {
                if (reader == null)
                {
                    return(null);
                }

                while (reader.Read())
                {
                    var instance = (TK)Activator.CreateInstance(typeof(TK));

                    var values = new object[fieldCount];
                    var count  = reader.GetValues(values);
                    if (count != fieldCount)
                    {
                        throw new InvalidConstraintException(
                                  "Number of fields from DB is different of the number of fields with DBFieldName attribute");
                    }

                    var i = 2;
                    foreach (var field in fields)
                    {
                        if (values[i] is DBNull && field.Item1.FieldType == typeof(string))
                        {
                            field.Item1.SetValueDirect(__makeref(instance), string.Empty);
                        }
                        else if (field.Item1.FieldType.BaseType == typeof(Enum))
                        {
                            field.Item1.SetValueDirect(__makeref(instance), Enum.Parse(field.Item1.FieldType, values[i].ToString()));
                        }
                        else if (field.Item1.FieldType.BaseType == typeof(Array))
                        {
                            var arr = Array.CreateInstance(field.Item1.FieldType.GetElementType(), field.Item2.Count);

                            for (var j = 0; j < arr.Length; j++)
                            {
                                var elemType = arr.GetType().GetElementType();
                                var val      = Convert.ChangeType(values[i + j], elemType);

                                arr.SetValue(val, j);
                            }
                            field.Item1.SetValueDirect(__makeref(instance), arr);
                        }
                        else if (field.Item1.FieldType == typeof(bool))
                        {
                            field.Item1.SetValueDirect(__makeref(instance), Convert.ToBoolean(values[i]));
                        }
                        else
                        {
                            field.Item1.SetValueDirect(__makeref(instance), values[i]);
                        }

                        i += field.Item2.Count;
                    }

                    var key = Tuple.Create((T)values[0], (TG)values[1]);
                    if (!dict.ContainsKey(key))
                    {
                        dict.Add(key, instance);
                    }
                }
            }

            return(new StoreMulti <Tuple <T, TG>, TK>(dict));
        }
            internal AnonymousTypeTemplateSymbol(AnonymousTypeManager manager, AnonymousTypeDescriptor typeDescr)
            {
                this.Manager           = manager;
                this.TypeDescriptorKey = typeDescr.Key;
                _smallestLocation      = typeDescr.Location;

                // Will be set when the type's metadata is ready to be emitted,
                // <anonymous-type>.Name will throw exception if requested
                // before that moment.
                _nameAndIndex = null;

                int fieldsCount  = typeDescr.Fields.Length;
                int membersCount = fieldsCount * 3 + 1;

                // members
                var membersBuilder = ArrayBuilder <Symbol> .GetInstance(membersCount);

                var propertiesBuilder = ArrayBuilder <AnonymousTypePropertySymbol> .GetInstance(fieldsCount);

                var typeParametersBuilder = ArrayBuilder <TypeParameterSymbol> .GetInstance(fieldsCount);

                // Process fields
                for (int fieldIndex = 0; fieldIndex < fieldsCount; fieldIndex++)
                {
                    AnonymousTypeField field = typeDescr.Fields[fieldIndex];

                    // Add a type parameter
                    AnonymousTypeParameterSymbol typeParameter =
                        new AnonymousTypeParameterSymbol(this, fieldIndex, GeneratedNames.MakeAnonymousTypeParameterName(field.Name));
                    typeParametersBuilder.Add(typeParameter);

                    // Add a property
                    AnonymousTypePropertySymbol property = new AnonymousTypePropertySymbol(this, field, TypeWithAnnotations.Create(typeParameter), fieldIndex);
                    propertiesBuilder.Add(property);

                    // Property related symbols
                    membersBuilder.Add(property);
                    membersBuilder.Add(property.BackingField);
                    membersBuilder.Add(property.GetMethod);
                }

                _typeParameters = typeParametersBuilder.ToImmutableAndFree();
                this.Properties = propertiesBuilder.ToImmutableAndFree();

                // Add a constructor
                membersBuilder.Add(new AnonymousTypeConstructorSymbol(this, this.Properties));
                _members = membersBuilder.ToImmutableAndFree();
                Debug.Assert(membersCount == _members.Length);

                // fill nameToSymbols map
                foreach (var symbol in _members)
                {
                    _nameToSymbols.Add(symbol.Name, symbol);
                }

                // special members: Equals, GetHashCode, ToString
                this.SpecialMembers = ImmutableArray.Create <MethodSymbol>(
                    new AnonymousTypeEqualsMethodSymbol(this),
                    new AnonymousTypeGetHashCodeMethodSymbol(this),
                    new AnonymousTypeToStringMethodSymbol(this));
            }
Пример #57
0
        public MultiDictionary<IMutationOperator, MutationTarget> FindTargets(CciModuleSource module, ProgressCounter subProgress)
        {
            _log.Info("Finding targets for module: " + module.Module.Name);
            _log.Info("Using mutation operators: " + _mutOperators.Select(_ => _.Info.Id)
                .MayAggregate((a, b) => a + "," + b).Else("None"));

            var mergedTargets = new MultiDictionary<IMutationOperator, MutationTarget>();
            _sharedTargets = new MultiDictionary<IMutationOperator, MutationTarget>();
            subProgress.Initialize(_mutOperators.Count);
            foreach (var mutationOperator in _mutOperators)
            {
                try
                {
                    subProgress.Progress();
                    var ded = mutationOperator.CreateVisitor();
                    IOperatorCodeVisitor operatorVisitor = ded;
                    operatorVisitor.Host = module.Host;
                    operatorVisitor.OperatorUtils = _operatorUtils;
                    operatorVisitor.Initialize();

                    var visitor = new VisualCodeVisitor(mutationOperator.Info.Id, operatorVisitor, module.Module.Module);

                    var traverser = new VisualCodeTraverser(_filter, visitor, module);

                    traverser.Traverse(module.Module.Module);
                    visitor.PostProcess();

                    IEnumerable<MutationTarget> mutations = LimitMutationTargets(visitor.MutationTargets);


                    mergedTargets.Add(mutationOperator, new HashSet<MutationTarget>(mutations));
                    _sharedTargets.Add(mutationOperator, new HashSet<MutationTarget>(visitor.SharedTargets));

                }
                catch (Exception e)
                {
                    _svc.Logging.ShowError("Finding targets operation failed in operator: {0}. Exception: {1}".Formatted(mutationOperator.Info.Name, e.ToString()));
                    //throw new MutationException("Finding targets operation failed in operator: {0}.".Formatted(mutationOperator.Info.Name), e);
                }
            }
            return mergedTargets;
        }
Пример #58
0
 public void Subscribe <T>(string name, Delegate handler)
 {
     subscriptions.Add(name, handler);
 }
Пример #59
0
 private static void AddSymbol(ISymbol symbol, MultiDictionary<string, ISymbol> symbolMap, Func<ISymbol, bool> useSymbol)
 {
     var nt = symbol as INamespaceOrTypeSymbol;
     if (nt != null)
     {
         foreach (var member in nt.GetMembers())
         {
             if (useSymbol(member))
             {
                 symbolMap.Add(member.Name, member);
             }
         }
     }
 }
Пример #60
0
        /// <summary>
        /// Reporting is done in a function that returns a string, to avoid any performance impact when the trace log is not enabled.
        /// </summary>
        private string ReportPermissions(IUserInfo userInfo, PrincipalInfo principal, Lazy <IDictionary <Guid, string> > roleNamesIndex,
                                         IEnumerable <Permission> userPermissions, IEnumerable <ClaimInfo> claims, IEnumerable <bool> userHasClaims)
        {
            var report = new List <string>();

            // Create an index of permissions:

            var permissionsByClaim = new MultiDictionary <Guid, Permission>();

            foreach (var permission in userPermissions)
            {
                permissionsByClaim.Add(permission.ClaimID, permission);
            }

            // Analyze permissions for required claims:

            foreach (var claimResult in claims.Zip(userHasClaims, (Claim, UserHasIt) => new { Claim, UserHasIt }))
            {
                var claimPermissions = claimResult.Claim.ID != null
                    ? permissionsByClaim.Get(claimResult.Claim.ID.Value)
                    : new Permission[]
                {
                };

                var permissionsDescription = claimPermissions
                                             .Select(permission => new
                {
                    permission.IsAuthorized,
                    PrincipalOrRoleName = permission.PrincipalID != null
                                ? ("principal " + (permission.PrincipalID.Value == principal.ID ? principal.Name : permission.PrincipalID.Value.ToString()))
                                : ("role " + GetRoleNameSafe(permission.RoleID.Value, roleNamesIndex))
                })
                                             .ToList();

                var allowedFor = permissionsDescription.Where(p => p.IsAuthorized).Select(p => p.PrincipalOrRoleName).ToList();
                var deniedFor  = permissionsDescription.Where(p => !p.IsAuthorized).Select(p => p.PrincipalOrRoleName).ToList();

                string explanation = "User " + userInfo.UserName + " " + (claimResult.UserHasIt ? "has" : "doesn't have")
                                     + " claim '" + claimResult.Claim.Resource + " " + claimResult.Claim.Right + "'. It is ";

                if (deniedFor.Count != 0)
                {
                    if (allowedFor.Count != 0)
                    {
                        explanation += "denied for " + string.Join(", ", deniedFor) + " and allowed for " + string.Join(", ", allowedFor) + " (deny overrides allow).";
                    }
                    else
                    {
                        explanation += "denied for " + string.Join(", ", deniedFor) + ".";
                    }
                }
                else
                if (allowedFor.Count != 0)
                {
                    explanation += "allowed for " + string.Join(", ", allowedFor) + ".";
                }
                else
                if (claimResult.Claim.ID == null)
                {
                    explanation += "denied by default (the claim does not exist or is no longer active).";
                }
                else
                {
                    explanation += "denied by default (no permissions defined).";
                }

                report.Add(explanation);
            }

            return(string.Join("\r\n", report));
        }