Example #1
0
 public HtmlCreator(string text, List<Marker> markers)
 {
     this.text = text;
     this.markers = markers;
     if (markers.Any(m => m.LInclusive < 0 || m.RExclusive > text.Length))
         throw new ArgumentException();
     open = markers.ToLookup(g => g.LInclusive);
     close = markers.ToLookup(g => g.RExclusive);
     result = new StringBuilder();
     Create();
 }
        private void OnSerialize(StreamingContext context)
        {
            RepopulateHyperMedia();

            if (ResourceConverter.IsResourceConverterContext(context))
            {
                // put all embedded resources and lists of resources into Embedded for the _embedded serializer
                var resourceList = new List<IResource>();
                foreach (var prop in GetType().GetProperties().Where(p => IsEmbeddedResourceType(p.PropertyType)))
                {
                    var val = prop.GetValue(this, null);
                    if (val != null)
                    {
                        // remember embedded resource property for restoring after serialization
                        embeddedResourceProperties.Add(prop, val);
                        // add embedded resource to collection for the serializtion
                        var res = val as IResource;
                        if (res != null)
                            resourceList.Add(res);
                        else
                            resourceList.AddRange((IEnumerable<IResource>) val);
                        // null out the embedded property so it doesn't serialize separately as a property
                        prop.SetValue(this, null, null);
                    }
                }
                foreach (var res in resourceList.Where(r => string.IsNullOrEmpty(r.Rel)))
                    res.Rel = "unknownRel-" + res.GetType().Name;
                Embedded = resourceList.Count > 0 ? resourceList.ToLookup(r => r.Rel) : null;
            }
        }
Example #3
0
 public static ILookup<string, float> createDict()
 {
     List<KeyValuePair<string, float>> list = new List<KeyValuePair<string, float>>();
     list.Add(new KeyValuePair<string, float>("", 10));
     var dict = list.ToLookup(kvp => kvp.Key, kvp => kvp.Value);
     return dict;
 }
Example #4
0
        public void LoadEntries(DataFile file, IndexEntry indexEntry)
        {
            var list = new List<RootEntry>();
            var blteEntry = new BinaryReader(DataFile.LoadBLTEEntry(indexEntry, file.readStream));

            while (blteEntry.BaseStream.Position < blteEntry.BaseStream.Length)
            {
                var entries = new RootEntry[blteEntry.ReadInt32()];

                blteEntry.BaseStream.Position += 4;

                var locales = (Locales)blteEntry.ReadUInt32();

                blteEntry.BaseStream.Position += (entries.Length << 2);

                for (var i = 0; i < entries.Length; i++)
                {
                    list.Add(new RootEntry
                    {
                        MD5 = blteEntry.ReadBytes(16),
                        Hash = blteEntry.ReadUInt64(),
                        Locales = locales
                    });
                }
            }

            entries = list.ToLookup(re => re.Hash);
        }
Example #5
0
        /// <summary>
        /// This method will return all values from a given section in a dictionary
        /// </summary>
        /// <param name="section">The name of the section</param>
        /// <returns>A dictionary containing propertynames and values.</returns>
        public ILookup<int, string> GetAllValuesFromSection(string section)
        {
            string str;
            int name;
            string val;
            List<PrioritizedProcess> map = new List<PrioritizedProcess>();

            using (StreamReader reader = new StreamReader(_path))
            {
                while (!reader.EndOfStream)
                {
                    if ((str = reader.ReadLine()).Equals(@"[" + section + "]"))
                    {
                        while ((str = reader.ReadLine() ?? "").Contains("="))
                        {
                            if (!Int32.TryParse(str.Split('=')[0], out name))
                                continue;

                            val = str.Split('=')[1];

                            map.Add(new PrioritizedProcess() { Priority = name, Path = val });
                        }
                    }
                }
            }

            return map.ToLookup(p => p.Priority, p => p.Path);
        }
Example #6
0
        public override ILookup<string, HttpActionDescriptor> GetActionMapping(HttpControllerDescriptor controllerDescriptor)
        {
            if(controllerDescriptor.ControllerType == typeof(SlimApiGhostController)) {
            var newActions = new List<HttpActionDescriptor>();
            foreach(var contrInfo in _apiConfig.ControllerInfos) {
              var methods = contrInfo.Type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
              foreach(var method in methods) {
            var dtype = method.DeclaringType;
            if (dtype == typeof(object)) //skip ToString()
              continue;
            var action = new SlimApiActionDescriptor(controllerDescriptor, method, contrInfo, _apiConfig);
            if (action.RouteTemplates.Count > 0 && action.SupportedHttpMethods.Count > 0) {
              RegisterAction(action);
              newActions.Add(action);

            }
              }
            } //foreach ct

            var lkp = newActions.ToLookup(a => a.ActionName, StringComparer.OrdinalIgnoreCase);
            return lkp;
              }
              // otherwise call base
              return base.GetActionMapping(controllerDescriptor);
        }
Example #7
0
        private static void Lookup()
        {
            // Create a list of Packages to put into a Lookup data structure.
            List<Package> packages = new List<Package> { new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L },
                                                 new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L },
                                                 new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L },
                                                 new Package { Company = "Contoso Pharmaceuticals", Weight = 9.3, TrackingNumber = 670053128L },
                                                 new Package { Company = "Wide World Importers", Weight = 33.8, TrackingNumber = 4665518773L } };

            // Create a Lookup to organize the packages. Use the first character of Company as the key value.
            // Select Company appended to TrackingNumber for each element value in the Lookup.

            // a look up vs igrouping is like a dictionary vs keyvaluepair
            // look up is collection, igrouping is the item it has key and ienumerable of things
            Lookup<char, string> lookup = (Lookup<char, string>)packages.ToLookup(p => Convert.ToChar(p.Company.Substring(0, 1)),
                p => p.Company + " " + p.TrackingNumber);

            foreach (IGrouping<char, string> packageGroup in lookup)
            {
                // Print the key value of the IGrouping.
                Console.WriteLine(packageGroup.Key);
                // Iterate through each value in the IGrouping and print its value.
                foreach (string str in packageGroup)
                    Console.WriteLine("    {0}", str);
            }
        }
Example #8
0
 public static RuleSet GetResetPasswordRuleSet()
 {
     var rules = new List<KeyValuePair<string, Rule>>
                     {
                         new KeyValuePair<string, Rule>("UserName", new RequiredRule{ ErrorMessage = "Bạn chưa nhập địa chỉ tên đăng nhập của bạn"})
                     };
     return new RuleSet(rules.ToLookup(k => k.Key, v => v.Value));
 }
Example #9
0
        private static void Remove(List<int> collection)
        {
            var listOfItemsToBeRemoved = collection
                                        .ToLookup(x => x)
                                        .Where(g => g.Count() % 2 != 0)
                                        .SelectMany(g => g);

            collection.RemoveAll(listOfItemsToBeRemoved.Contains);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="course"></param>
        /// <param name="user"></param>
        /// <returns>a lookup true = successfully emailed, false = email failed</returns>
        public static async Task<ILookup<bool, CourseParticipant>> SendEmail(Course course, IPrincipal user)
        {
            using (var cal = Appointment.CreateCourseAppointment(course, user.Identity))
            {
                using (var appt = new AppointmentStream(cal))
                {
                    var map = ((Expression<Func<CourseParticipant, CourseParticipantDto>>)new CourseParticipantMaps().MapToDto).Compile();
                    var faculty = course.CourseParticipants.Where(cp => !map(cp).IsEmailed)
                        .ToLookup(cp => cp.IsFaculty);

                    IEnumerable<Attachment> attachments = new Attachment[0];
                    using (var client = new SmtpClient())
                    {
                        var mailMessages = new List<ParticipantMail>();
                        var sendMail = new Action<CourseParticipant>(cp =>
                        {
                            var mail = new MailMessage();
                            mail.To.AddParticipants(cp.Participant);
                            var confirmEmail = new CourseInvite { CourseParticipant = cp };
                            mail.CreateHtmlBody(confirmEmail);
                            appt.AddAppointmentsTo(mail);
                            foreach (var a in attachments)
                            {
                                a.ContentStream.Position = 0;
                                mail.Attachments.Add(a);
                            }
                            mailMessages.Add(new ParticipantMail { Message = mail, SendTask = client.SendMailAsync(mail), CourseParticipant = cp });
                        });

                        foreach (var cp in faculty[false])
                        {
                            sendMail(cp);
                        }
                        if (faculty[true].Any())
                        {
                            if (course.FacultyMeetingUtc.HasValue)
                            {
                                using (var fm = Appointment.CreateFacultyCalendar(course))
                                {
                                    appt.Add(fm);
                                }
                            }
                            attachments = GetFilePaths(course).Select(fp => new Attachment(fp.Value, System.Net.Mime.MediaTypeNames.Application.Zip) { Name = fp.Key })
                                .Concat(new[] { new Attachment(CreateDocxTimetable.CreateTimetableDocx(course, WebApiConfig.DefaultTimetableTemplatePath), OpenXmlDocxExtensions.DocxMimeType) { Name = CreateDocxTimetable.TimetableName(course)} });
                            foreach (var cp in faculty[true])
                            {
                                sendMail(cp);
                            }
                        }
                        await Task.WhenAll(mailMessages.Select(mm => mm.SendTask));
                        mailMessages.ForEach(mm => mm.Message.Dispose());
                        return mailMessages.ToLookup(k => k.SendTask.Status == TaskStatus.RanToCompletion, v => v.CourseParticipant);
                    }
                }
            }
        }
Example #11
0
 public static RuleSet GetContactRuleSet()
 {
     var rules = new List<KeyValuePair<string, Rule>>
                     {
                         new KeyValuePair<string, Rule>("Name", new RequiredRule{ ErrorMessage = "Bạn hãy nhập họ và tên của bạn"}),
                         new KeyValuePair<string, Rule>("Email", new RequiredRule{ ErrorMessage = "Bạn hãy nhập địa chỉ email của bạn"}),
                         new KeyValuePair<string, Rule>("Email", new RegularExpressionRule(Constants.Regulars.Email) {ErrorMessage = "Địa chỉ email của bạn không hợp lệ"}),
                         new KeyValuePair<string, Rule>("Content", new RequiredRule{ ErrorMessage = "Bạn hãy nhập nội dung phản hồi của bạn"}),
                     };
     return new RuleSet(rules.ToLookup(k => k.Key, v => v.Value));
 }
Example #12
0
 public static RuleSet GetChangePasswordRuleSet()
 {
     var rules = new List<KeyValuePair<string, Rule>>
                     {
                         new KeyValuePair<string, Rule>("OldPassword", new RequiredRule{ ErrorMessage = "Bạn chưa nhập mật khẩu cũ"}),
                         new KeyValuePair<string, Rule>("NewPassword", new RequiredRule{ ErrorMessage = "Bạn chưa nhập mật khẩu mới"}),
                         new KeyValuePair<string, Rule>("ConfirmNewPassword", new RequiredRule{ ErrorMessage = "Mật khẩu xác nhận không giống nhau"}),
                         new KeyValuePair<string, Rule>("ConfirmNewPassword", new ComparisonRule("NewPassword", ComparisonRule.Operator.Equals){ ErrorMessage = "Mật khẩu xác nhận không giống nhau"})
                     };
     return new RuleSet(rules.ToLookup(k => k.Key, v => v.Value));
 }
        /// <summary>
        /// Get a list with schema entity names for its vocabularies. 
        /// Using vocabulary name rather than prefix from json, as the prefixes can be different in the view. 
        /// </summary>
        /// <remarks>
        /// Using <see cref="ILookup{TKey,TElement}"/> rather than a <see cref="Dictionary{TKey,TValue}"/> because it will allow for duplicate keys.
        /// Duplicate keys make no sense, but we might have them, so this prevents runtime exceptions.
        /// </remarks>
        /// <returns>List with entity names indexed by vocabulary</returns>
        public ILookup<string, string> GetEntityNames()
        {
            List<KeyValuePair<string, string>> entityNames = new List<KeyValuePair<string, string>>();
            foreach (SchemaSemantics schemaSemantics in Semantics)
            {
                string vocab = SemanticMapping.GetVocabulary(schemaSemantics.Prefix, Localization);
                entityNames.Add(new KeyValuePair<string, string>(vocab, schemaSemantics.Entity));
            }

            return entityNames.ToLookup(x => x.Key, x => x.Value);
        }
Example #14
0
        static void Main(string[] args)
        {
            List<int> numbers = new List<int> { 4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2 };

            var elementsToRemove = numbers.ToLookup(x => x).Where(xs => xs.Count() % 2 != 0);
            foreach (var item in elementsToRemove)
            {
                numbers.RemoveAll(x => x == item.Key);
            }

            Console.WriteLine(string.Join(", ", numbers));
        }
Example #15
0
        public static ProjectContextSnapshot Create(ProjectContext context, string configuration, IEnumerable<string> currentSearchPaths)
        {
            var snapshot = new ProjectContextSnapshot();

            var allDependencyDiagnostics = new List<DiagnosticMessage>();
            allDependencyDiagnostics.AddRange(context.LibraryManager.GetAllDiagnostics());
            allDependencyDiagnostics.AddRange(DependencyTypeChangeFinder.Diagnose(context, currentSearchPaths));

            var diagnosticsLookup = allDependencyDiagnostics.ToLookup(d => d.Source);

            var allExports = context.CreateExporter(configuration)
                                    .GetAllExports()
                                    .ToDictionary(export => export.Library.Identity.Name);

            var allSourceFiles = new List<string>(context.ProjectFile.Files.SourceFiles);
            var allFileReferences = new List<string>();
            var allProjectReferences = new List<ProjectReferenceDescription>();
            var allDependencies = new Dictionary<string, DependencyDescription>();

            // All exports are returned. When the same library name have a ReferenceAssembly type export and a Package type export
            // both will be listed as dependencies. Prefix "fx/" will be added to ReferenceAssembly type dependency.
            foreach (var export in allExports.Values)
            {
                allSourceFiles.AddRange(export.SourceReferences.Select(f => f.ResolvedPath));
                var diagnostics = diagnosticsLookup[export.Library].ToList();
                var description = DependencyDescription.Create(export.Library, diagnostics, allExports);
                allDependencies[description.Name] = description;

                var projectDescription = export.Library as ProjectDescription;
                if (projectDescription != null)
                {
                    if (projectDescription.Identity.Name != context.ProjectFile.Name)
                    { 
                        allProjectReferences.Add(ProjectReferenceDescription.Create(projectDescription));
                    }
                }
                else
                {
                    allFileReferences.AddRange(export.CompilationAssemblies.Select(asset => asset.ResolvedPath));
                }
            }

            snapshot.RootDependency = context.ProjectFile.Name;
            snapshot.TargetFramework = context.TargetFramework;
            snapshot.SourceFiles = allSourceFiles.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(path => path).ToList();
            snapshot.CompilerOptions = context.GetLanguageSpecificCompilerOptions(context.TargetFramework, configuration);
            snapshot.ProjectReferences = allProjectReferences.OrderBy(reference => reference.Name).ToList();
            snapshot.FileReferences = allFileReferences.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(path => path).ToList();
            snapshot.DependencyDiagnostics = allDependencyDiagnostics;
            snapshot.Dependencies = allDependencies;

            return snapshot;
        }
        private void inwersyjnaPrzycisk_Click(object sender, RoutedEventArgs e)
        {
            var brands = dataClass.ToLookup(data => data.brand);
            List <List <DataClass> > wynik    = new List <List <DataClass> >();
            List <DataClass>         kluczowe = new List <DataClass>();
            List <DataClass>         wyswietl = new List <DataClass>();

            foreach (var p in brands)
            {
                foreach (var a in dataClass)
                {
                    if (p.Key.Equals(a.brand))
                    {
                        kluczowe.Add(a);
                    }
                }
                wynik.Add(kluczowe);
            }
            var timer = System.Diagnostics.Stopwatch.StartNew(); //licznik czasu

            for (int p = 0; p < wynik[0].Count(); p++)           //to dodaje do wyniku/tj.wyswietlania/tylko jeden/inaczej wszystkie są w wynik
            {
                if (wynik[0][p].brand == lancuchowa.Text)
                {
                    wyswietl.Add(wynik[0][p]);
                }
                else
                {
                    continue;
                }
            }
            timer.Stop();
            MessageBox.Show("Czas szukania binarnego to mili -> " + timer.ElapsedMilliseconds + "\nIlość ticków -> " + timer.ElapsedTicks
                            + "\nCzas w nanosekundach -> " + timer.ElapsedTicks * 1000000000 / System.Diagnostics.Stopwatch.Frequency
                            ); //czas wykonywania -> komunikat

            Tabela.ItemsSource = null;
            Tabela.ItemsSource = wyswietl;
        }
Example #17
0
        private void GroupBySid(List <LogLine> readAllLines)
        {
            var counter = 0;

            foreach (var group in readAllLines.ToLookup(l => l.Sid, l => l))
            {
                counter++;
                foreach (var logLine in group)
                {
                    logLine.Sid = counter.ToString();
                }
            }
        }
Example #18
0
        //requirement 4
        public static List<int> GetMostCommonNumbers(List<int> input)
        {
            var returnValue = new List<int>();

            if (input.Any())
            {
                var grouped = input.ToLookup(x => x);
                var maxRepetitions = grouped.Max(x => x.Count());
                returnValue = grouped.Where(x => x.Count() == maxRepetitions).Select(x => x.Key).ToList();
            }

            return returnValue;
        }
Example #19
0
        private async Task ProcessProjectRecommendationsReaction(SlackEventFullDto <ReactionEventDto> slackEventDto, string workspaceMemberId)
        {
            string     workspaceId = slackEventDto.TeamId;
            UserEntity user        = await GetUserEntity(workspaceId, workspaceMemberId);

            var userTechnologies = user.UserTechnologies.Select(t => t.Name);

            // retrieve all slack member records with matching technologies
            List <ProjectTechnologies> projects = await _technologiesStorage.GetProjectTechnologiesAsync(userTechnologies.ToArray());

            // Remove self technologies and convert to lookup
            if (projects.Count == 0)
            {
                // no projects with associated technologies,
                // no project recommendations available
                await _slackService.ChatPostMessage(_privateIntroChannelId, $"no project recommendations for <@{workspaceMemberId}> and tech {string.Join(", ", userTechnologies)}");

                return;
            }

            var projectsLookup = projects.ToLookup(p => p.Id.ToString(), p => p.TechnologyName);
            // hashset used to filter out duplicates from list in order to generate powerset
            var uniqueTechnologiesList = new HashSet <string>(projects.Select(p => p.TechnologyName)).ToList();
            List <List <string> > technologiesPowerSet = GeneratePowerSet(uniqueTechnologiesList);
            string message = Messages.ProjectRecommendationsBasedOnSkillsMessage(workspaceMemberId);
            Dictionary <string, List <string> > projectRecommendations = FindRecommendations(technologiesPowerSet, projectsLookup);

            foreach (var recommendation in projectRecommendations)
            {
                if (recommendation.Value.Count == 0)
                {
                    // exclude the empty set
                    continue;
                }

                string techList = $"{recommendation.Key}\n";
                string projectRecommendationList = string.Empty;

                foreach (var projectId in recommendation.Value)
                {
                    var project = projects.Find(p => p.Id.ToString() == projectId);
                    projectRecommendationList = $"{projectRecommendationList}\nProject: {project.ProjectName}\nDescription: {project.ProjectDescription}\nWorkspace: {project.ProjectWorkspaceLink}\n\n";
                }

                message = $"{message}{techList}{projectRecommendationList}";
            }

            await _slackService.ChatPostMessage(workspaceMemberId, message, true, false);

            return;
        }
Example #20
0
        private async Task ProcessDeveloperRecommendationsReaction(SlackEventFullDto <ReactionEventDto> slackEventDto, string workspaceMemberId)
        {
            string     workspaceId = slackEventDto.TeamId;
            UserEntity user        = await GetUserEntity(workspaceId, workspaceMemberId);

            var userTechnologies = user.UserTechnologies.Select(t => t.Name);

            // retrieve all slack member records with matching technologies
            List <DeveloperTechnologies> technologies = await _chatAppUserStorage.GetDeveloperTechnologiesAsync(userTechnologies.ToArray());

            // Remove self technologies and convert to lookup
            technologies.RemoveAll(t => t.WorkspaceMemberId == workspaceMemberId);
            if (technologies.Count == 0)
            {
                // no members with technologies, no
                // recommendations available
                await _slackService.ChatPostMessage(_privateIntroChannelId, $"no collaborator recommendations for <@{workspaceMemberId}> and tech {string.Join(", ", userTechnologies)}");

                return;
            }

            var technologiesLookup = technologies.ToLookup(t => t.WorkspaceMemberId, t => t.Name);
            // hashset used to filter out duplicates from list in order to generate powerset
            var uniqueTechnologiesList = new HashSet <string>(technologies.Select(t => t.Name)).ToList();
            List <List <string> > technologiesPowerSet = GeneratePowerSet(uniqueTechnologiesList);
            string message = Messages.DeveloperRecommendationsBasedOnSkillsMessage(workspaceMemberId);
            Dictionary <string, List <string> > developerRecommendations = FindRecommendations(technologiesPowerSet, technologiesLookup);

            foreach (var recommendation in developerRecommendations)
            {
                if (recommendation.Value.Count == 0)
                {
                    // exclude the empty set
                    continue;
                }

                string memberList = string.Empty;
                foreach (var memberId in recommendation.Value)
                {
                    var tech = technologies.Find(t => t.WorkspaceMemberId == memberId);
                    memberList = $"{memberList}\n<@{memberId}>,  <{_mainUrl}/profile/{tech.UserId}|contact>";
                }

                string techList = $"\n{recommendation.Key}\n";
                message = $"{message}{techList}{memberList}\n";
            }

            await _slackService.ChatPostMessage(workspaceMemberId, message, true, false);

            return;
        }
Example #21
0
        private SemanticModel GetSemanticModelInternal()
        {
            var builtinNamespaces = new NamespaceSymbol[] { new SystemNamespaceSymbol(), new AzNamespaceSymbol() }.ToImmutableArray();
            var bindings       = new Dictionary <SyntaxBase, Symbol>();
            var cyclesBySyntax = new Dictionary <SyntaxBase, ImmutableArray <DeclaredSymbol> >();

            // create this in locked mode by default
            // this blocks accidental type or binding queries until binding is done
            // (if a type check is done too early, unbound symbol references would cause incorrect type check results)
            var symbolContext = new SymbolContext(new TypeManager(bindings, cyclesBySyntax), bindings);

            // collect declarations
            var declarations       = new List <DeclaredSymbol>();
            var declarationVisitor = new DeclarationVisitor(symbolContext, declarations);

            declarationVisitor.Visit(this.ProgramSyntax);

            // in cases of duplicate declarations we will see multiple declaration symbols in the result list
            // for simplicitly we will bind to the first one
            // it may cause follow-on type errors, but there will also be errors about duplicate identifiers as well
            var uniqueDeclarations = declarations
                                     .ToLookup(x => x.Name, LanguageConstants.IdentifierComparer)
                                     .ToImmutableDictionary(x => x.Key, x => x.First(), LanguageConstants.IdentifierComparer);

            // bind identifiers to declarations
            var binder = new NameBindingVisitor(uniqueDeclarations, bindings, builtinNamespaces);

            binder.Visit(this.ProgramSyntax);

            var shortestCycleBySyntax = CyclicCheckVisitor.FindCycles(this.ProgramSyntax, uniqueDeclarations, bindings);

            foreach (var kvp in shortestCycleBySyntax)
            {
                cyclesBySyntax.Add(kvp.Key, kvp.Value);
            }

            // name binding is done
            // allow type queries now
            symbolContext.Unlock();

            // TODO: Avoid looping 4 times?
            var file = new FileSymbol("main",
                                      this.ProgramSyntax,
                                      builtinNamespaces,
                                      declarations.OfType <ParameterSymbol>(),
                                      declarations.OfType <VariableSymbol>(),
                                      declarations.OfType <ResourceSymbol>(),
                                      declarations.OfType <OutputSymbol>());

            return(new SemanticModel(file, symbolContext.TypeManager, bindings));
        }
            private void DiscoverStateMethods()
            {
                hashToAnimString = new Dictionary <int, string>();
                var components = gameObject.GetComponents <MonoBehaviour>();

                var enterStateMethods  = new List <StateMethod>();
                var updateStateMethods = new List <StateMethod>();
                var exitStateMethods   = new List <StateMethod>();

                foreach (var component in components)
                {
                    if (component == null)
                    {
                        continue;
                    }

                    var type    = component.GetType();
                    var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public |
                                                  BindingFlags.DeclaredOnly |
                                                  BindingFlags.InvokeMethod);

                    foreach (var method in methods)
                    {
                        var attributes = method.GetCustomAttributes(typeof(AnimatorStay), true);
                        updateStateMethods.AddRange(from AnimatorStay attribute in attributes
                                                    let parameters = method.GetParameters()
                                                                     where parameters.Length == 0
                                                                     select CreateStateMethod(attribute.state, method, component));


                        attributes = method.GetCustomAttributes(typeof(AnimatorEnter), true);
                        enterStateMethods.AddRange(from AnimatorEnter attribute in attributes
                                                   let parameters = method.GetParameters()
                                                                    where parameters.Length == 0
                                                                    select CreateStateMethod(attribute.state, method, component));

                        attributes = method.GetCustomAttributes(typeof(AnimatorExit), true);
                        exitStateMethods.AddRange(from AnimatorExit attribute in attributes
                                                  let parameters = method.GetParameters()
                                                                   where parameters.Length == 0
                                                                   select CreateStateMethod(attribute.state, method, component));
                    }
                }

                stateHashToUpdateMethod =
                    (Lookup <int, Action>)updateStateMethods.ToLookup(p => p.stateHash, p => p.method);
                stateHashToEnterMethod =
                    (Lookup <int, Action>)enterStateMethods.ToLookup(p => p.stateHash, p => p.method);
                stateHashToExitMethod =
                    (Lookup <int, Action>)exitStateMethods.ToLookup(p => p.stateHash, p => p.method);
            }
Example #23
0
        public static void ILookupExample()
        {
            // Create a list of Packages to put into an ILookup data structure.
            List <Package> packages = new List <Package> {
                new Package {
                    Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L
                },
                new Package {
                    Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L
                },
                new Package {
                    Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L
                },
                new Package {
                    Company = "Contoso Pharmaceuticals", Weight = 9.3, TrackingNumber = 670053128L
                },
                new Package {
                    Company = "Wide World Importers", Weight = 33.8, TrackingNumber = 4665518773L
                }
            };

            // Create a Lookup to organize the packages. Use the first character of Company as the key value.
            // Select Company appended to TrackingNumber for each element value in the ILookup object.
            ILookup <char, string> packageLookup = packages.ToLookup(
                p => p.Company[0],
                p => p.Company + " " + p.TrackingNumber
                );

            // Iterate through each value in the ILookup and output the contents.
            foreach (var packageGroup in packageLookup)
            {
                // Print the key value.
                Console.WriteLine(packageGroup.Key);
                // Iterate through each value in the collection.
                foreach (string str in packageGroup)
                {
                    Console.WriteLine("    {0}", str);
                }
            }

            // This code produces the following output:
            //
            // C
            //     Coho Vineyard 89453312
            //     Contoso Pharmaceuticals 670053128
            // L
            //     Lucerne Publishing 89112755
            // W
            //     Wingtip Toys 299456122
            //     Wide World Importers 4665518773
        }
Example #24
0
        public static void GroupingPackages()
        {
            List <Package> packages = new List <Package>
            {
                new Package {
                    Company = "Coho Vineyard",
                    Weight  = 25.2, TrackingNumber = 89453312L
                },
                new Package {
                    Company = "Lucerne Publishing",
                    Weight  = 18.7, TrackingNumber = 89112755L
                },
                new Package {
                    Company = "Wingtip Toys",
                    Weight  = 6.0, TrackingNumber = 299456122L
                },
                new Package {
                    Company = "Contoso Pharmaceuticals",
                    Weight  = 9.3, TrackingNumber = 670053128L
                },
                new Package {
                    Company = "Wide World Importers",
                    Weight  = 33.8, TrackingNumber = 4665518773L
                }
            };

            /*
             * ToLookup의 리턴값이 ILookup이라는 것을 명확하게 보여준다.
             * 평소의 나라면 아무생각 없이 <string, string>을 사용했을텐데
             * 이 예제에서는 <char, string>을 사용했다.
             * 그러기위해 Convert.ToChar 메서드를 이용했다.
             * string을 남용하지말고 char를 사용하는 것도 항상 염두에 두자.
             */
            ILookup <char, string> lookup =
                packages
                .ToLookup(p => Convert.ToChar(p.Company.Substring(0, 1)),
                          p => p.Company + " " + p.TrackingNumber);

            /*
             * foreach문에서 dictionay를 KeyValuePair<>로 받는 것 처럼
             * ToLookup은 IGrouping<>으로 처리한다.
             */
            foreach (IGrouping <char, string> packageGroup in lookup)
            {
                Console.WriteLine(packageGroup.Key);
                foreach (string str in packageGroup)
                {
                    Console.WriteLine("    {0}", str);
                }
            }
        }
Example #25
0
        public void view()
        {
            int j    = 0;
            var dict = kvp3.ToLookup(kvp1 => kvp1.Key, kvp1 => kvp1.Value);

            for (j = 0; j < no_enteries; j++)
            {
                foreach (string X in dict[j])
                {
                    Console.Write(X + "\t\t");
                }
            }
            Console.WriteLine("\n");
        }
        /// <summary>
        ///     Инициализирует объекты настроек кэширования для быстрого поиска настроек кэширования для входящего запроса.
        /// </summary>
        private void _init()
        {
            var cacheSettings = (CacheSettingsSection) ConfigurationManager.GetSection("cacheSettingsSection");
            var lookupItems = new List<KeyValuePair<CachePathSegments, CacheSettingsElement>>();

            foreach (var cahceSettingElement in cacheSettings.CacheSettings.Cast<CacheSettingsElement>())
            {
                var segments = new CachePathSegments(cahceSettingElement.Pattern);
                var lookupItem = new KeyValuePair<CachePathSegments, CacheSettingsElement>(segments, cahceSettingElement);
                lookupItems.Add(lookupItem);
            }

            _cacheSettingsLookup = lookupItems.ToLookup(i => i.Key.Segments.Count);
        }
Example #27
0
        public async Task <ILookup <int, Order> > GetOrdersByUserIdAsync(IEnumerable <int> arg)
        {
            var orders = new List <Order>
            {
                new Order {
                    Id = 1, Description = "Order 1"
                },
                new Order {
                    Id = 2, Description = "Order 2"
                }
            };

            return(orders.ToLookup(x => x.Id));
        }
Example #28
0
        public List <int> GetEvek()
        {
            List <int> evek = new List <int>();

            var eveklookup = idojarasadatok.ToLookup(x => x.Ev).OrderBy(x => x.Key);

            foreach (var i in eveklookup)
            {
                evek.Add(i.Key);
            }


            return(evek);
        }
        public override async Task EvaluateAsync(
            IMergePolicyEvaluationContext context,
            MergePolicyProperties properties)
        {
            var ignoreChecks = new HashSet <string>(properties.Get <string[]>("ignoreChecks") ?? Array.Empty <string>());

            IList <Check> checks = await context.Darc.GetPullRequestChecksAsync(context.PullRequestUrl);

            List <Check> notIgnoredChecks = checks.Where(c => !ignoreChecks.Contains(c.Name)).ToList();

            if (notIgnoredChecks.Count < 1)
            {
                context.Fail("No un-ignored checks.");
                return;
            }

            ILookup <CheckState, Check> statuses = notIgnoredChecks.ToLookup(
                c =>
            {
                // unify the check statuses to success, pending, and error
                switch (c.Status)
                {
                case CheckState.Success:
                case CheckState.Pending:
                    return(c.Status);

                default:
                    return(CheckState.Error);
                }
            });

            string ListChecks(CheckState state)
            {
                return(string.Join(", ", statuses[state].Select(c => c.Name)));
            }

            if (statuses.Contains(CheckState.Error))
            {
                context.Fail($"Unsuccessful checks: {ListChecks(CheckState.Error)}");
                return;
            }

            if (statuses.Contains(CheckState.Pending))
            {
                context.Pending($"Waiting on checks: {ListChecks(CheckState.Pending)}");
                return;
            }

            context.Succeed($"Successful checks: {ListChecks(CheckState.Success)}");
        }
Example #30
0
        public static void ToLookupEx1()
        {
            // Create a list of Packages.
            List <Package> packages =
                new List <Package>
            {
                new Package {
                    Company = "Coho Vineyard",
                    Weight  = 25.2, TrackingNumber = 89453312L
                },
                new Package {
                    Company = "Lucerne Publishing",
                    Weight  = 18.7, TrackingNumber = 89112755L
                },
                new Package {
                    Company = "Wingtip Toys",
                    Weight  = 6.0, TrackingNumber = 299456122L
                },
                new Package {
                    Company = "Contoso Pharmaceuticals",
                    Weight  = 9.3, TrackingNumber = 670053128L
                },
                new Package {
                    Company = "Wide World Importers",
                    Weight  = 33.8, TrackingNumber = 4665518773L
                }
            };

            // Create a Lookup to organize the packages.
            // Use the first character of Company as the key value.
            // Select Company appended to TrackingNumber
            // as the element values of the Lookup.
            ILookup <char, string> lookup =
                packages
                .ToLookup(p => Convert.ToChar(p.Company.Substring(0, 1)),
                          p => p.Company + " " + p.TrackingNumber);

            // Iterate through each IGrouping in the Lookup.
            foreach (IGrouping <char, string> packageGroup in lookup)
            {
                // Print the key value of the IGrouping.
                Console.WriteLine(packageGroup.Key);
                // Iterate through each value in the
                // IGrouping and print its value.
                foreach (string str in packageGroup)
                {
                    Console.WriteLine("    {0}", str);
                }
            }
        }
Example #31
0
 public static RuleSet GetRegisterRuleSet()
 {
     var rules = new List<KeyValuePair<string, Rule>>
                     {
                         new KeyValuePair<string, Rule>("UserName", new RequiredRule{ ErrorMessage = "Bạn chưa nhập tên đăng nhập"}),
                         new KeyValuePair<string, Rule>("UserName", new RegularExpressionRule(Constants.Regulars.User){ ErrorMessage = "Tên đăng nhập chỉ chấp nhận chữ cái, số và dấu _"}),
                         new KeyValuePair<string, Rule>("Password", new RequiredRule{ ErrorMessage = "Bạn chưa nhập mật khẩu"}),
                         new KeyValuePair<string, Rule>("ConfirmPassword", new RequiredRule{ ErrorMessage = "Mật khẩu xác nhận không giống nhau"}),
                         new KeyValuePair<string, Rule>("ConfirmPassword", new ComparisonRule("Password", ComparisonRule.Operator.Equals){ ErrorMessage = "Mật khẩu xác nhận không giống nhau"}),
                         new KeyValuePair<string, Rule>("Email", new RequiredRule{ ErrorMessage = "Bạn chưa nhập địa chỉ email của bạn"}),
                         new KeyValuePair<string, Rule>("Email", new RegularExpressionRule(Constants.Regulars.Email) {ErrorMessage = "Địa chỉ email của bạn không hợp lệ"})
                     };
     return new RuleSet(rules.ToLookup(k => k.Key, v => v.Value));
 }
Example #32
0
 /// <summary>
 /// Maps the posts for a specific topic
 /// </summary>
 /// <param name="posts"></param>
 /// <param name="votes"></param>
 /// <param name="permission"></param>
 /// <param name="topic"></param>
 /// <param name="loggedOnUser"></param>
 /// <param name="settings"></param>
 /// <param name="favourites"></param>
 /// <returns></returns>
 public static List<PostViewModel> CreatePostViewModels(IEnumerable<Post> posts, List<Vote> votes, PermissionSet permission, Topic topic, MembershipUser loggedOnUser, Settings settings, List<Favourite> favourites)
 {
     var viewModels = new List<PostViewModel>();
     var groupedVotes = votes.ToLookup(x => x.Post.Id);
     var groupedFavourites = favourites.ToLookup(x => x.Post.Id);
     foreach (var post in posts)
     {
         var id = post.Id;
         var postVotes = (groupedVotes.Contains(id) ? groupedVotes[id].ToList() : new List<Vote>());
         var postFavs = (groupedFavourites.Contains(id) ? groupedFavourites[id].ToList() : new List<Favourite>());
         viewModels.Add(CreatePostViewModel(post, postVotes, permission, topic, loggedOnUser, settings, postFavs));
     }
     return viewModels;
 }
Example #33
0
    // Here is the method
    static List <Item> BuildTreeAndReturnRootNodes(List <Item> flatItems)
    {
        var byIdLookup = flatItems.ToLookup(i => i.Id);

        foreach (var item in flatItems)
        {
            if (item.ParentId != null)
            {
                var parent = byIdLookup[item.ParentId.Value].First();
                parent.Children.Add(item);
            }
        }
        return(flatItems.Where(i => i.ParentId == null).ToList());
    }
Example #34
0
        public async Task <IActionResult> Index()
        {
            var schedulers = await TimerUtil.GetSchedulers().ConfigureAwait(false);

            List <JobDetailVM> jobs = new List <JobDetailVM>();

            foreach (var item in schedulers)
            {
                var partial = await item.GetCurrentlyExecutingJobs().ConfigureAwait(false);

                jobs.AddRange(partial.Select(o => new JobDetailVM(o)));
            }
            return(View(jobs.ToLookup(o => o.SchedulerName)));
        }
Example #35
0
        public static ProjectContextSnapshot Create(ProjectContext context, string configuration, IEnumerable <string> currentSearchPaths)
        {
            var snapshot = new ProjectContextSnapshot();

            var allDependencyDiagnostics = new List <DiagnosticMessage>();

            allDependencyDiagnostics.AddRange(context.LibraryManager.GetAllDiagnostics());
            allDependencyDiagnostics.AddRange(DependencyTypeChangeFinder.Diagnose(context, currentSearchPaths));

            var diagnosticsLookup = allDependencyDiagnostics.ToLookup(d => d.Source);

            var allExports = context.CreateExporter(configuration)
                             .GetAllExports()
                             .ToDictionary(export => export.Library.GetUniqueName());
            var allSourceFiles       = new List <string>(context.ProjectFile.Files.SourceFiles);
            var allFileReferences    = new List <string>();
            var allProjectReferences = new List <ProjectReferenceDescription>();
            var allDependencies      = new Dictionary <string, DependencyDescription>();

            // All exports are returned. When the same library name have a ReferenceAssembly type export and a Package type export
            // both will be listed as dependencies. Prefix "fx/" will be added to ReferenceAssembly type dependency.
            foreach (var pair in allExports)
            {
                var export = pair.Value;

                allSourceFiles.AddRange(export.SourceReferences);
                allFileReferences.AddRange(export.CompilationAssemblies.Select(asset => asset.ResolvedPath));

                var diagnostics = diagnosticsLookup[export.Library].ToList();
                var description = DependencyDescription.Create(export.Library, diagnostics, allExports);
                allDependencies[description.Name] = description;

                var projectDescription = export.Library as ProjectDescription;
                if (projectDescription != null && projectDescription.Identity.Name != context.ProjectFile.Name)
                {
                    allProjectReferences.Add(ProjectReferenceDescription.Create(projectDescription));
                }
            }

            snapshot.RootDependency        = context.ProjectFile.Name;
            snapshot.TargetFramework       = context.TargetFramework;
            snapshot.SourceFiles           = allSourceFiles.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(path => path).ToList();
            snapshot.CompilerOptions       = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);
            snapshot.ProjectReferences     = allProjectReferences.OrderBy(reference => reference.Name).ToList();
            snapshot.FileReferences        = allFileReferences.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(path => path).ToList();
            snapshot.DependencyDiagnostics = allDependencyDiagnostics;
            snapshot.Dependencies          = allDependencies;

            return(snapshot);
        }
Example #36
0
        private void Form1_Load(object sender, EventArgs e)
        {
            //var stream = Resources.ResourceManager.GetStream("LookupTable");
            //customers = (Lookup<string, Dictionary<string, string>>)(new BinaryFormatter().Deserialize(stream));
            try
            {
                using (var ms = new MemoryStream())
                {
                    byte[] data = (byte[])Resources.ResourceManager.GetObject("LookupTableBIN");
                    ms.Write(data, 0, data.Length);
                    customers = Jil.JSON.Deserialize <Lookup <string, Dictionary <string, string> > >((string)(new BinaryFormatter().Deserialize(ms)));
                    ms.Dispose();
                    ms.Close();
                }
            }
            catch
            {
                List <string> lines  = new List <string>(File.ReadAllLines(@"C:\Users\ZACH-GAMING\Documents\InsightLocations.txt"));
                string[]      labels = lines[0].Split('\t');
                lines.RemoveAt(0);

                customers = (Lookup <string, Dictionary <string, string> >)lines.ToLookup(
                    l => l.Split('\t')[5],
                    l => l.Split('\t').Select(
                        (x, i) => new { Item = x, Index = i }
                        ).ToDictionary(
                        k => labels[k.Index], k => k.Item
                        )
                    );

                using (var ms = new MemoryStream())
                {
                    new BinaryFormatter().Serialize(
                        ms,
                        Jil.JSON.Serialize <Lookup <string, Dictionary <string, string> > >(
                            customers
                            )
                        );
                    var            data = ms.ToArray();
                    ResourceWriter rw   = new ResourceWriter("Resources.LookupTableBIN");
                    rw.AddResourceData("LookupTableBIN", "ByteArray", data);
                    rw.Generate();
                    rw.Dispose();
                    rw.Close();
                    //ms.Read((byte[])Resources.LookupTableBIN.SyncRoot, 0, data.Length);
                    ms.Dispose();
                    ms.Close();
                }
            }
        }
Example #37
0
        private static void Interfaces(List <Customer> customers, List <Order> orders)
        {
            // Hashset
            HashSet <string> hashSets = customers.Select(c => c.Name).ToHashSet();
            bool             inSet    = hashSets.Contains("Frank Bakker");

            // Dictionary 1 => 1
            Dictionary <string, Customer> dictionary = customers.ToDictionary(c => c.Name);
            Customer customer = dictionary["Frank Bakker"];

            // Lookup 1 => 0..*
            ILookup <string, Order> lookup     = orders.ToLookup(o => o.CustomerName);
            IEnumerable <Order>     enumerable = lookup["Frank Bakker"];
        }
Example #38
0
        public async Task <ILookup <int, Datasource> > GetDatasourcesPerProject(IEnumerable <int> projectIds)
        {
            List <Datasource> datasources = new List <Datasource>();

            foreach (var projectId in projectIds.Distinct())
            {
                var context = _contextProvider.GetContext(projectId);
                var result  = await context.Datasource.Where(x => projectId == x.ProjectId).ToListAsync();

                datasources.AddRange(result);
            }

            return(datasources.ToLookup(x => x.ProjectId));
        }
        /// <summary>
        /// Returns a map, keyed by action string, of all <see cref="T:System.Web.Http.Controllers.HttpActionDescriptor" /> that the selector can select.  This is primarily called by <see cref="T:System.Web.Http.Description.IApiExplorer" /> to discover all the possible actions in the controller.
        /// </summary>
        /// <param name="controllerDescriptor">The controller descriptor.</param>
        /// <returns>
        /// A map of <see cref="T:System.Web.Http.Controllers.HttpActionDescriptor" /> that the selector can select, or null if the selector does not have a well-defined mapping of <see cref="T:System.Web.Http.Controllers.HttpActionDescriptor" />.
        /// </returns>
        public ILookup <string, HttpActionDescriptor> GetActionMapping(HttpControllerDescriptor controllerDescriptor)
        {
            // Exercised only by ASP.NET Web API’s API explorer feature

            List <HttpActionDescriptor> descriptors = new List <HttpActionDescriptor> {
                ActionDescriptor
            };

            ILookup <string, HttpActionDescriptor> result = descriptors.ToLookup(
                p => "generic",
                p => p);

            return(result);
        }
Example #40
0
        internal void CreateIndex()
        {
            if (this.NpcList == null)
            {
                return;
            }

            idToTemplate = new Dictionary <int, NpcTemplate>();
            List <KeyValuePair <string, int> > temp = null;

            foreach (var npc in this.NpcList)
            {
                if (!idToTemplate.ContainsKey(npc.npc_id))
                {
                    idToTemplate.Add(npc.npc_id, npc);
                }
                if (Utility.StringIndex == null)
                {
                    continue;
                }
                if (idToTitle == null)
                {
                    idToTitle = new Dictionary <int, string>();
                }

                if (!idToTitle.ContainsKey(npc.npc_id))
                {
                    var descr = Utility.StringIndex.GetStringDescription(npc.title_id);
                    if (descr != null)
                    {
                        string title = descr.body.Trim('<', '>');
                        idToTitle.Add(npc.npc_id, title);
                        string[] titleWords = title.Split(' ', '-');
                        var      lookup     = titleWords.Select(w => new KeyValuePair <string, int>(w, npc.npc_id));
                        if (temp == null)
                        {
                            temp = lookup.ToList();
                        }
                        else
                        {
                            temp.AddRange(lookup);
                        }
                    }
                }
            }
            if (temp != null)
            {
                titleToIds = temp.ToLookup(a => a.Key, a => a.Value, StringComparer.InvariantCultureIgnoreCase);
            }
        }
Example #41
0
        public List <int> GetEvek()
        {
            List <int> evek = new List <int>();

            var evekegyszer = adatlista.ToLookup(x => x.Ev).OrderBy(x => x.Key);

            foreach (var e in evekegyszer)
            {
                evek.Add(e.Key);
            }


            return(evek);
        }
Example #42
0
        /// <summary>
        /// Replacement for HttpUtility.ParseQueryString
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static ILookup <string, string> ParseQueryString(this string input)
        {
            var result  = new List <KeyValuePair <string, string> >();
            var entries = input.Split('&');

            foreach (var entry in entries)
            {
                var parts = entry.Split('=');
                var key   = parts[0];
                var value = string.Join("=", parts.Skip(1));
                result.Add(new KeyValuePair <string, string>(key, value));
            }
            return(result.ToLookup(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase));
        }
Example #43
0
        public BaseViewModel()
        {
            List<KeyValuePair<string, string>> _properties = new List<KeyValuePair<string, string>>();
            foreach (var property in GetType().GetProperties())
            {
                foreach (var d in (DependsUponAttribute[])property.GetCustomAttributes(typeof(DependsUponAttribute), true))
                {
                    _properties.Add(new KeyValuePair<string, string>(d.DependancyName, property.Name));
                }
            }

            DependentProperties = (Lookup<string, string>)_properties.ToLookup(p => p.Key, p => p.Value);

        }
        private static void Search(int collectionSize, int searchItemsCount)
        {
            Console.WriteLine($"V množině o velikost {collectionSize:n0} hledáno {searchItemsCount:n0}x:");

            #region Sample data
            var sw = new System.Diagnostics.Stopwatch();
            var list = new List<Guid>();
            var dictionary = new Dictionary<Guid, object>();
            foreach (var guid in Enumerable.Range(0, collectionSize).Select(g => Guid.NewGuid()))
            {
                list.Add(guid);
                dictionary.Add(guid, null);
            }
            var lookup = list.ToLookup(i => i);
            var sortedArray = list.ToArray();
            Array.Sort(sortedArray);

            // vytvoření sample-dat, které budeme hledat
            var rand = new Random();
            var hledane = Enumerable.Range(0, searchItemsCount).Select(g => (rand.NextDouble() > 0.5) ? Guid.NewGuid() : list[rand.Next(list.Count)]).ToList();

            #endregion

            // Contains = sekvenční vyhledávání = O(n)
            sw.Start();
            int found = hledane.Count(t => list.Contains(t));
            sw.Stop();
            Console.WriteLine($"\tList<>.Contains():          Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");

            // binární půlení = O(log(n))
            sw.Restart();
            found = hledane.Count(t => Array.BinarySearch<Guid>(sortedArray, t) >= 0);
            sw.Stop();
            Console.WriteLine($"\tArray.BinarySearch<>():     Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");

            // Dictionary = Hashtable, O(1)
            sw.Restart();
            found = hledane.Count(t => dictionary.ContainsKey(t));
            sw.Stop();
            Console.WriteLine($"\tDictionary<>.ContainsKey(): Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");

            // Dictionary = Hashtable, O(1)
            sw.Restart();
            found = hledane.Count(i => lookup.Contains(i));
            sw.Stop();
            Console.WriteLine($"\tLINQ ILookup:               Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");

            Console.WriteLine();
        }
Example #45
0
        /// <summary>
        /// Find entities with a field of a particular value.
        /// </summary>
        /// <param name="fieldValues">The field values.</param>
        /// <returns>
        /// Dictionary matching field values to one or more entities that were found. N, or null if none were found.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// typeId
        /// or
        /// fieldId
        /// or
        /// fieldValues
        /// </exception>
        public ILookup <object, long> GetEntitiesByField(IReadOnlyCollection <object> fieldValues)
        {
            if (fieldValues == null)
            {
                throw new ArgumentNullException("fieldValues");
            }

            // Get user
            long userId = RequestContext.GetContext( ).Identity.Id;

            string sql = _queryResult.Sql;


            // Run query
            var entities = new List <Tuple <long, object> >( );

            using (DatabaseContext ctx = DatabaseContext.GetContext( ))
            {
                using (IDbCommand command = ctx.CreateCommand(sql))
                {
                    ctx.AddParameter(command, "@user", DbType.Int64, userId);
                    ctx.AddParameter(command, "@tenant", DbType.Int64, RequestContext.TenantId);
                    command.AddListParameter("@valueList", _fieldType, fieldValues);

                    if (_queryResult.SharedParameters != null)
                    {
                        foreach (KeyValuePair <ParameterValue, string> parameter in _queryResult.SharedParameters)
                        {
                            ctx.AddParameter(command, parameter.Value, parameter.Key.Type, parameter.Key.Value);
                        }
                    }

                    using (IDataReader reader = command.ExecuteReader( ))
                    {
                        while (reader.Read( ))
                        {
                            long   entityId   = reader.GetInt64(0);
                            object fieldValue = reader.GetValue(1);

                            Tuple <long, object> entry = new Tuple <long, object>(entityId, fieldValue);
                            entities.Add(entry);
                        }
                    }
                }
            }
            var results = entities.ToLookup(t => t.Item2, t => t.Item1);

            return(results);
        }
Example #46
0
        public List <ProviderAdjustment> CalculateDelta(
            List <ProviderAdjustment> historicPayments,
            List <ProviderAdjustment> currentPayments)
        {
            var groupedPreviousPayments = historicPayments.ToLookup(x => new ProviderAdjustmentPaymentGrouping(x));

            var groupedEarnings = EarningsGroupsThatHaveNotBeenProcessed(currentPayments);

            var payments = CalculatePayments(groupedEarnings, groupedPreviousPayments);
            var processedEarningsGroups = new HashSet <ProviderAdjustmentPaymentGrouping>(groupedEarnings.Select(x => x.Key));

            var refunds = CalculateRefunds(groupedPreviousPayments, processedEarningsGroups);

            return(payments.Union(refunds).ToList());
        }
Example #47
0
        internal static ILookup <string, HttpActionDescriptor> CreateActionMap(params string[] actionNames)
        {
            List <HttpActionDescriptor> actionMap = new List <HttpActionDescriptor>();

            foreach (string actionName in actionNames)
            {
                Mock <HttpActionDescriptor> actionDescriptor = new Mock <HttpActionDescriptor> {
                    CallBase = true
                };
                actionDescriptor.Setup(a => a.ActionName).Returns(actionName);
                actionMap.Add(actionDescriptor.Object);
            }

            return(actionMap.ToLookup(a => a.ActionName));
        }
Example #48
0
        public async Task <ILookup <int, AvTagsAssociatedGear> > GetTagsByEquipment(
            IReadOnlyList <int> equipment,
            System.Threading.CancellationToken cancellationToken)
        {
            var filters = new List <int>();

            foreach (int gear in equipment)
            {
                filters.Add(gear);
            }

            List <AvTagsAssociatedGear> tags = await _db.AvTagsAssociatedGear.Where(a => filters.Contains(a.EquipmentId)).ToListAsync();

            return(tags.ToLookup(t => t.EquipmentId));
        }
        private void bgwConsulta_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (sError.Equals(string.Empty))
            {
                if (bgwConsultaFriolala.IsBusy == false)
                {
                    lstEtiquetas = lstEtiquetas.ToLookup(o => o.NumeroDeEtiqueta).Select(col => col.First()).ToList();

                    gridEtiquetas.DataSource = lstEtiquetas;
                    gvEtiquetas.BestFitColumns();
                    pbCargando.Visible   = false;
                    btnConsultar.Enabled = true;
                }
            }
            else
            {
                MessageBox.Show(sError, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            tiempoConsultaFinal = DateTime.Now.TimeOfDay;
            TimeSpan tiempoTotal = tiempoConsultaFinal - tiempoConsultaInicial;

            lbltiempo.Text = "Tiempo de consulta ACC: " + tiempoTotal.Seconds + " segundos.";
        }
Example #50
0
        static void Main(string[] args)
        {
            List <string> names = new List <string>();

            names.Add("Smith");
            names.Add("Stevenson");
            names.Add("Jones");

            ILookup <char, string> namesByInitial = names.ToLookup((n) => n[0]);

            // count the names
            Console.WriteLine("J's: {0}", namesByInitial['J'].Count());
            Console.WriteLine("S's: {0}", namesByInitial['S'].Count());
            Console.WriteLine("Z's: {0}", namesByInitial['Z'].Count());
        }
Example #51
0
        static OUILookup()
        {
            OUIList = new List <OUIInfo>();

            XmlDocument document = new XmlDocument();

            document.Load(OUIFilePath);

            foreach (XmlNode node in document.SelectNodes("/OUIs/OUI"))
            {
                OUIList.Add(new OUIInfo(node.SelectSingleNode("MACAddress").InnerText, node.SelectSingleNode("Vendor").InnerText));
            }

            OUIs = (Lookup <string, OUIInfo>)OUIList.ToLookup(x => x.MACAddress);
        }
        static void Main()
        {
            var racers = new List<Racer>();
            racers.Add(new Racer(26, "Jacques", "Villeneuve", "Canada", 11));
            racers.Add(new Racer(18, "Alan", "Jones", "Australia", 12));
            racers.Add(new Racer(11, "Jackie", "Stewart", "United Kingdom", 27));
            racers.Add(new Racer(15, "James", "Hunt", "United Kingdom", 10));
            racers.Add(new Racer(5, "Jack", "Brabham", "Australia", 14));

            var lookupRacers = racers.ToLookup(r => r.Country);

            foreach (Racer r in lookupRacers["Australia"])
            {
                WriteLine(r);
            }
        }
 private static void MarkAmbiguousNamespaceTypes(string rootName, NamespaceHierarchyItem item, List<TypeModel> parentTypes)
 {
     var visibleTypes = new List<TypeModel>(parentTypes);
     visibleTypes.AddRange(item.TypeModels);
     var visibleTypesLookup = visibleTypes.ToLookup(x => x.Name);
     var isAmbiguous = visibleTypesLookup.Contains(rootName);
     if (isAmbiguous)
     {
         MarkAmbiguousNamespaceTypes(item);
     }
     else
     {
         foreach (var subItem in item.SubNamespaces)
             MarkAmbiguousNamespaceTypes(rootName, subItem, visibleTypes);
     }
 }
Example #54
0
        public static ProjectContextSnapshot Create(ProjectContext context, string configuration, IEnumerable<string> currentSearchPaths)
        {
            var snapshot = new ProjectContextSnapshot();
            
            var allDependencyDiagnostics = new List<DiagnosticMessage>();
            allDependencyDiagnostics.AddRange(context.LibraryManager.GetAllDiagnostics());
            allDependencyDiagnostics.AddRange(DependencyTypeChangeFinder.Diagnose(context, currentSearchPaths));

            var diagnosticsLookup = allDependencyDiagnostics.ToLookup(d => d.Source);

            var allSourceFiles = new List<string>(context.ProjectFile.Files.SourceFiles);
            var allFileReferences = new List<string>();
            var allProjectReferences = new List<ProjectReferenceDescription>();
            var allDependencies = new Dictionary<string, DependencyDescription>();
            
            foreach (var export in context.CreateExporter(configuration).GetDependencies())
            {
                allSourceFiles.AddRange(export.SourceReferences);
                allFileReferences.AddRange(export.CompilationAssemblies.Select(asset => asset.ResolvedPath));

                var library = export.Library;
                var diagnostics = diagnosticsLookup[library].ToList();
                var description = DependencyDescription.Create(library, diagnostics);
                allDependencies[description.Name] = description;

                var projectDescription = library as ProjectDescription;

                if (projectDescription != null)
                {
                    allProjectReferences.Add(ProjectReferenceDescription.Create(projectDescription));
                }
            }

            snapshot.RootDependency = context.ProjectFile.Name;
            snapshot.TargetFramework = context.TargetFramework;
            snapshot.SourceFiles = allSourceFiles.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(path => path).ToList();
            snapshot.CompilerOptions = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);
            snapshot.ProjectReferences = allProjectReferences.OrderBy(reference => reference.Name).ToList();
            snapshot.FileReferences = allFileReferences.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(path => path).ToList();
            snapshot.DependencyDiagnostics = allDependencyDiagnostics;
            snapshot.Dependencies = allDependencies;

            return snapshot;
        }
Example #55
0
        static void Main(string[] args)
        {
            var cards = new List<Card>();
            foreach (var m in (Mast[])Enum.GetValues(typeof(Mast)))
                foreach (var r in (Rank[])Enum.GetValues(typeof(Rank)))
                    cards.Add(new Card { mast = m, rank = r });

            const int total = 1000000000;
            var bingo = 0;
            for (var i = 0; i < total; i++)
            {
                var rand = new Random();
                cards.Sort((x, y) => rand.Next(2) == 0 ? -1 : 1);
                //WriteLine(string.Join(", ", cards));
                var mastlookup = cards.ToLookup(c => c.mast);

                var list1 = new List<Card>();
                var list2 = new List<Card>();
                foreach (var m in (Mast[])Enum.GetValues(typeof(Mast)))
                {
                    var ce = mastlookup[m].ToArray();
                    if (ce.Length != 2) throw new Exception("Not 2");
                    list1.Add(ce[0]);
                    list2.Add(ce[1]);
                }
                //WriteLine(string.Join(", ", list1));
                //WriteLine(string.Join(", ", list2));

                var c1 = list1[rand.Next(3)];
                var c2 = list2[rand.Next(3)];
                //WriteLine($"{c1} : {c2}");

                if (c1.rank == c2.rank)
                {
                    bingo++;
                    //WriteLine("Bingo!");
                }
                //ReadKey();
            }

            WriteLine($"{(double)bingo / total} {bingo}/{total}");
            ReadKey();
        }
Example #56
0
        static void Main()
        {
            var racers = new List<Racer>();
            racers.Add(new Racer(26, "Jacques", "Villeneuve", "Canada", 11));
            racers.Add(new Racer(18, "Alan", "Jones", "Australia", 12));
            racers.Add(new Racer(11, "Jackie", "Stewart", "United Kingdom", 27));
            racers.Add(new Racer(15, "James", "Hunt", "United Kingdom", 10));
            racers.Add(new Racer(5, "Jack", "Brabham", "Australia", 14));
            racers.Add(new Racer(25, "Adi", "ADDD", "Australia", 28));

            var lookupRacers = racers.ToLookup(r => r.Country);

            foreach (Racer r in lookupRacers["Australia"])
            {
                Console.WriteLine(r);
            }
            // public delegate bool Predicate<T>(T obj);
            int index = racers.FindIndex(new FindCountry("Australia").FindCountryPredicate);
            Console.WriteLine("index:{0}",index);
            //下面是等价的
            int index2 = racers.FindIndex(r => r.Country == "Australia");
            Console.WriteLine("index2:{0}", index2);
            //返回第一个匹配的
            //FindLast 最后一个匹配的
            Console.WriteLine("Find get first match object");
            Racer racerFirst = racers.Find(c => c.Country == "Australia");
            Console.WriteLine(racerFirst.FirstName);
            Console.WriteLine(racerFirst.LastName);

            Console.WriteLine("FindLast get last match object");
            Racer racerLast = racers.FindLast(c => c.Country == "Australia");
            Console.WriteLine(racerLast.FirstName);
            Console.WriteLine(racerLast.LastName);

            Console.WriteLine("FindAll get All match object");
            List<Racer> racerAll = racers.FindAll(r => r.Wins > 20);
            foreach (Racer r in racerAll)
            {
                Console.WriteLine("{0:A}",r);
            }
            Console.ReadKey();
            
        }
Example #57
0
        public Form1()
        {
            InitializeComponent();

            List<string> list = new List<string>
                                    {
                                        "tabel1.kol1", 
                                        "tabel1.kol2", 
                                        "tabel2.kol1b", 
                                        "tabel2.kol1b"
                                    };

            int i = 0;
            ILookup<string, string> lookup = list.ToLookup(
                p => p.Substring(0, 6),
                p => p.Substring(7, p.Length-7));

            var kols = lookup["tabel1"].ToList();
            comboBox1.DataSource = kols;
        }
        private void DoCalculateData()
        {
            _ratingsByUser = _commonData.AllRatings.ToLookup(key => key.User);

            var variance = new List<Tuple<KeyNode, ValueNode>>();
            foreach (var combo in GetAllTwoMovieCombinations())
            {
                var valuesForKeyByMovie3 = GetAllKeyedValues(combo).ToLookup(key => key.Movie3);

                foreach (var v in valuesForKeyByMovie3)
                {
                    double score1 = v.Average(x => x.Rating1);
                    double score2 = v.Average(x => x.Rating2);
                    double score3 = v.Average(x => x.Rating3);

                    var meanValueNode = new ValueNode(score1, score2, v.Key, score3);
                    variance.Add(Tuple.Create(combo, meanValueNode));
                }
            }

            _variance = variance.ToLookup(key => key.Item1, val => val.Item2);
        }
Example #59
0
        public CommandLineParser(params string[] args)
        {
            var queue = new Queue<string>(args);

            var assemblyPaths = new List<string>();
            var optionList = new List<KeyValuePair<string, string>>();
            var errors = new List<string>();

            while (queue.Any())
            {
                var item = queue.Dequeue();

                if (IsKey(item))
                {
                    if (!queue.Any() || IsKey(queue.Peek()))
                    {
                        errors.Add(string.Format("Option {0} is missing its required value.", item));
                        break;
                    }

                    var key = KeyName(item);
                    var value = queue.Dequeue();

                    optionList.Add(new KeyValuePair<string, string>(key, value));
                }
                else
                {
                    assemblyPaths.Add(item);
                }
            }

            if (!errors.Any() && !assemblyPaths.Any())
                errors.Add("Missing required test assembly path(s).");

            AssemblyPaths = assemblyPaths.ToArray();
            Options = optionList.ToLookup(x => x.Key, x => x.Value);
            Errors = errors.ToArray();
        }
Example #60
0
        static void Main()
        {
            Console.WriteLine("Remove from given sequence all numbers that occur odd number of times\n");

            List<int> intNumbers = new List<int> {4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2};
            Console.WriteLine("Original list of numbers:");
            foreach (var item in intNumbers)
            {
                Console.Write("{0} ", item);
            }
            Console.WriteLine();
            var oddCountElements = intNumbers.ToLookup(n => n).Where(ng => ng.Count() % 2 != 0);
            foreach (var item in oddCountElements)
            {
                intNumbers.RemoveAll(n => n == item.Key);
            }
            Console.WriteLine("\nList of numbers with odd occurences removed:");
            foreach (var item in intNumbers)
            {
                Console.Write("{0} ", item);
            }
            Console.WriteLine();
        }