public void can_match_5()
 {
     soll = new[] { 1, 2, 3, 4, 5, 6 };
     ist = new[] { 1, 2, 3, 4, 5, 7 };
     Assert.That(ist.Intersect(soll).Count(), Is.EqualTo(5));
     Assert.That(ist.Intersect(soll).Count(), Is.EqualTo(soll.Intersect(ist).Count()));
 }
Beispiel #2
0
 public void String(IEnumerable<string> first, IEnumerable<string> second, IEqualityComparer<string> comparer, string[] expected)
 {
     if (comparer == null)
     {
         Assert.Equal(expected, first.Intersect(second));
     }
     Assert.Equal(expected, first.Intersect(second, comparer));
 }
        public async Task<bool> RequiresConsentAsync(Client client, ClaimsPrincipal user, IEnumerable<string> scopes)
        {
            if (client == null) throw new ArgumentNullException("client");
            if (user == null) throw new ArgumentNullException("user");

            if (!client.RequireConsent)
            {
                return false;
            }

            // TODO: validate that this is a correct statement
            if (!client.AllowRememberConsent)
            {
                return true;
            }

            if (scopes == null || !scopes.Any())
            {
                return false;
            }
            
            var consent = await _store.LoadAsync(user.GetSubjectId(), client.ClientId);
            if (consent != null && consent.Scopes != null)
            {
                var intersect = scopes.Intersect(consent.Scopes);
                return !(scopes.Count() == intersect.Count());
            }

            return true;
        }
        private IEnumerable<EmployeeLogin> SRVCUpdateLogins(Helpers.Log.SessionInfo logSession, Repository.Logic.Repository rep,
            long employeeId, IEnumerable<string> addLogins, IEnumerable<string> removeLogins)
        {
#pragma warning disable 618
            logSession.Add($"Try to get employee with id = {employeeId}");
            var emp = rep.Get<Repository.Model.Employee>(e => e.EmployeeId == employeeId, false, new string[] { "Logins" }).FirstOrDefault();
            if (emp == null)
                throw new Exception(string.Format(Properties.Resources.STUFFINGSERVICE_EmployeeNotFound, employeeId));

            var existedLogins = emp.Logins.Select(r => r.DomainLogin);

            #region Add logins

            if (addLogins != null && addLogins.Any())
            {
                logSession.Add($"Add logins...");
                var addLoginsUpper = addLogins
                    .Except(existedLogins)
                    .ToArray()
                    .Select(r => rep.New<Repository.Model.EmployeeLogin>((er) =>
                    {
                        er.EmployeeLoginId = emp.EmployeeId;
                        er.DomainLogin = r;
                    }))
                    .ToArray();

                logSession.Add($"Add this logins {addLoginsUpper.Concat(r => r.DomainLogin, ",")} for employee id = {employeeId}");
                foreach (var r in addLoginsUpper)
                    emp.Logins.Add(r);

                rep.AddRange(addLoginsUpper, saveAfterInsert: false);
            }

            #endregion
            #region Remove rights

            if (removeLogins != null && removeLogins.Any())
            {
                logSession.Add($"Remove logins...");
                var removeLoginsUpper = removeLogins
                    .Intersect(existedLogins)
                    .ToArray()
                    .Join(emp.Logins, r => r, er => er.DomainLogin.ToUpper(), (r, er) => er)
                    .ToArray();

                logSession.Add($"Remove this logins {removeLoginsUpper.Concat(r => r.DomainLogin, ",")} for employee id = {employeeId}");
                foreach (var r in removeLoginsUpper)
                    emp.Logins.Remove(r);

                rep.RemoveRange(removeLoginsUpper, saveAfterRemove: false);
            }

            #endregion

            rep.SaveChanges();

            return emp.Logins.Select(er => AutoMapper.Mapper.Map<EmployeeLogin>(er));
#pragma warning restore 618
        }
Beispiel #5
0
 static IEnumerable<int[]> Crossover(IEnumerable<int> father, IEnumerable<int> mother)
 {
     IEnumerable<int>
         intersect = father.Intersect(mother), motherRest = mother.Except(intersect), fatherRest = father.Except(intersect);
     int motherRestHalfSize = motherRest.Count() / 2, fatherRestRestHalfSize = fatherRest.Count() / 2;
     yield return intersect.Concat(motherRest.Take(motherRestHalfSize)).Concat(fatherRest.Skip(fatherRestRestHalfSize)).ToArray();
     yield return intersect.Concat(motherRest.Skip(motherRestHalfSize)).Concat(fatherRest.Take(fatherRestRestHalfSize)).ToArray();
 }
Beispiel #6
0
        public void AssertContainsAll(IEnumerable<int> expected, IEnumerable<int> actual)
        {
            int n1 = expected.Distinct().Count();
            int n2 = actual.Distinct().Count();

            Assert.AreEqual(n1, n2);
            Assert.AreEqual(n1, expected.Intersect(actual).Count());
            Assert.AreEqual(n2, actual.Intersect(expected).Count());
        }
        internal static string SuggestLanguage(IEnumerable<string> supportedLanguages, IEnumerable<string> preferredLanguages)
        {
            var intersection = preferredLanguages.Intersect(supportedLanguages);

            if (intersection.Any())
                return intersection.First();

            return supportedLanguages.First();
        }
        public override IEnumerable<double?[]> UpperApproximation(IEnumerable<double?[]> X)
        {
            Debug.WriteLine("Standard AS Upper Approximation");

            return IndiscernibilityClasses()
                .Where(Ix => X.Intersect(Ix).Any())
                .Aggregate(
                    Enumerable.Empty<double?[]>(),
                    (upX, Ix) => upX.Union(Ix))
                ;
        }
 /**
  * Verification of a living cell
  * if neighboring cells alive for at least two and no more than 3 then cell is alive
  * @param currentGeneration
  * @param cell
  * @param neighboringCells
  * @return if cells alive then true
  */
 bool CheckLiveCell(IEnumerable<Cell> currentGeneration, Cell cell, 
     IEnumerable<Cell> neighboringCells)
 {
     if (cell != null && neighboringCells != null)
     {
         int countIntersect = currentGeneration.Intersect(neighboringCells).Count();
         return (countIntersect == 2 || countIntersect == 3);
     }
     else
         return false;
 }
Beispiel #10
0
        public double GetJaccardSimilarity(IEnumerable<int> s1, IEnumerable<int> s2)
        {
            if (s1.Count() < ShingleSize || s2.Count() < ShingleSize)
            {
                return double.NaN;
            }

            int cap = s1.Intersect(s2).Count();
            int cup = s1.Union(s2).Count();

            return (double)cap / cup;
        }
Beispiel #11
0
        public bool Validate(IEnumerable<char> data)
        {
            foreach(var s in Statements)
            {
                if(data.Intersect(s.Data).Count() < s.ExpectedAtLeast)
                {
                    return false;
                }
            }

            return true && data.Count() >= MinLenght;
        }
        public static string Negotiate(IEnumerable<string> server, IEnumerable<string> client)
        {
            if (!server.Any() || !client.Any()) {
                return null;
            }

            var matches = client.Intersect(server);
            if (!matches.Any()) {
                throw new SubProtocolNegotiationFailureException("Unable to negotiate a subprotocol");
            }
            return matches.First();
        }
Beispiel #13
0
        public static FieldReference FindBackingField(this PropertyDefinition propertyDefinition)
        {
            IEnumerable <FieldReference> getFieldReferences = propertyDefinition.GetMethod?.Body?.Instructions
                                                              ?.Where(instruction => instruction.OpCode == OpCodes.Ldsfld || instruction.OpCode == OpCodes.Ldfld)
                                                              .Select(instruction => (FieldReference)instruction.Operand);
            IEnumerable <FieldReference> setFieldReferences = propertyDefinition.SetMethod?.Body?.Instructions
                                                              ?.Where(instruction => instruction.OpCode == OpCodes.Stsfld || instruction.OpCode == OpCodes.Stfld)
                                                              .Select(instruction => (FieldReference)instruction.Operand);

            return(getFieldReferences?.Intersect(
                       setFieldReferences ?? Enumerable.Empty <FieldReference>(),
                       FieldReferenceComparer.Instance)
                   .FirstOrDefault());
        }
        public static DetailedEvaluation Evaluate(this SentenceSegmenter segmenter, string paragraph,
            IEnumerable<int> realBoundaryIndices)
        {
            IEnumerable<int> predictedIndices = segmenter.GetBoundaryIndices(paragraph);

            // ReSharper disable PossibleMultipleEnumeration
            IEnumerable<int> misses = realBoundaryIndices.Except(predictedIndices);
            IEnumerable<int> falseAlarms = predictedIndices.Except(realBoundaryIndices);
            IEnumerable<int> hits = realBoundaryIndices.Intersect(predictedIndices);
            // ReSharper restore PossibleMultipleEnumeration

            int eosCandidateCount = GetEosCharCount(segmenter.EosCandidates, paragraph);

            return new DetailedEvaluation(hits, misses, falseAlarms, eosCandidateCount, paragraph);
        }
Beispiel #15
0
        /// <summary>
        /// Searches the index for words in the search query
        /// </summary>
        /// <param name="query">Search query</param>
        /// <returns>List of document IDs that match the query</returns>
        public List <int> SearchWord(string query)
        {
            var words             = _findWords.Matches(query);
            IEnumerable <int> rtn = null;

            for (var i = 0; i < words?.Count; i++)
            {
                var word = words[i].Value;
                if (_index.ContainsKey(word))
                {
                    rtn = rtn?.Intersect(_index[word].Keys) ?? _index[word].Keys;
                }
                else
                {
                    return(new List <int>());
                }
            }

            return(rtn?.ToList() ?? new List <int>());
        }
        /// <summary>
        /// Checks if consent is required.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="subject">The user.</param>
        /// <param name="scopes">The scopes.</param>
        /// <returns>Boolean if consent is required.</returns>
        public virtual async Task<bool> RequiresConsentAsync(Client client, ClaimsPrincipal subject, IEnumerable<string> scopes)
        {
            if (client == null) throw new ArgumentNullException("client");
            if (subject == null) throw new ArgumentNullException("subject");

            if (!client.RequireConsent)
            {
                return false;
            }

            // TODO: validate that this is a correct statement
            if (!client.AllowRememberConsent)
            {
                return true;
            }

            if (scopes == null || !scopes.Any())
            {
                return false;
            }

            // we always require consent for offline access if
            // the client has not disabled RequireConsent 
            if (scopes.Contains(Constants.StandardScopes.OfflineAccess))
            {
                return true;
            }
            
            var consent = await _store.LoadAsync(subject.GetSubjectId(), client.ClientId);
            if (consent != null && consent.Scopes != null)
            {
                var intersect = scopes.Intersect(consent.Scopes);
                return !(scopes.Count() == intersect.Count());
            }

            return true;
        }
        /// <summary>
        /// Add a formatted message representing a change in a relationship.
        /// </summary>
        public void AddChangedRelationship(string relName, IEnumerable <long> removed, IEnumerable <long> added, int count)
        {
            var sb = new StringBuilder();

            var change = new ChangeRecord {
                Field = relName
            };

            _changes.Add(change);

            change.UpdateType = null;

            var overlapping = removed.Intersect(added);

            var reallyRemoved = removed.Except(overlapping);

            if (reallyRemoved.Any())
            {
                sb.Append("removed ");
                AddRelList(sb, reallyRemoved);
            }

            var reallyAdded = added.Except(overlapping);

            if (reallyAdded.Any())
            {
                if (reallyRemoved.Any())
                {
                    sb.Append(' ');
                }

                sb.Append("added ");
                AddRelList(sb, reallyAdded.Except(overlapping));
            }

            change.Summary = sb.ToString();
        }
        public static TOwner HaveChecked <TData, TOwner>(this IFieldVerificationProvider <TData, CheckBoxList <TData, TOwner>, TOwner> should, TData value)
            where TOwner : PageObject <TOwner>
        {
            should.CheckNotNull(nameof(should));

            IEnumerable <TData> expectedIndividualValues = should.Component.GetIndividualValues(value);
            string expectedIndividualValuesAsString      = should.Component.ConvertIndividualValuesToString(expectedIndividualValues, true);

            string expectedMessage = new StringBuilder().
                                     Append("have checked").
                                     AppendIf(expectedIndividualValues.Count() > 1, ":").
                                     Append($" {expectedIndividualValuesAsString}").ToString();

            AtataContext.Current.Log.Start(new VerificationLogSection(should.Component, $"{should.GetShouldText()} {expectedMessage}"));

            IEnumerable <TData> actualIndividualValues = null;

            bool doesSatisfy = AtataContext.Current.Driver.Try().Until(
                _ =>
            {
                actualIndividualValues = should.Component.GetIndividualValues(should.Component.Get());
                int intersectionsCount = expectedIndividualValues.Intersect(actualIndividualValues).Count();
                return(should.IsNegation ? intersectionsCount == 0 : intersectionsCount == expectedIndividualValues.Count());
            },
                should.GetRetryOptions());

            if (!doesSatisfy)
            {
                throw should.CreateAssertionException(
                          expectedMessage,
                          should.Component.ConvertIndividualValuesToString(actualIndividualValues, true));
            }

            AtataContext.Current.Log.EndSection();

            return(should.Owner);
        }
Beispiel #19
0
        /// <summary>
        /// All the optional parameter are required if <see cref="T"/> does not implement <see cref="IComparable"/>.
        /// </summary>
        /// <param name="referenceCol">Reference collection</param>
        /// <param name="newCol">New collection</param>
        /// <param name="keySortGetter"></param>
        /// <returns></returns>
        public IEnumerable <ComparisonResult <T> > Compare(IEnumerable <T> referenceCol, IEnumerable <T> newCol,
                                                           IEqualityComparer <T> identityComparer = null,
                                                           IEqualityComparer <T> contentComparer  = null,
                                                           Func <T, Object> keySortGetter         = null)
        {
            if (identityComparer == null)
            {
                identityComparer = EqualityComparer <T> .Default;
            }
            if (contentComparer == null)
            {
                contentComparer = EqualityComparer <T> .Default;
            }

            var removedItems = referenceCol.Except(newCol, identityComparer);
            var addedItems   = newCol.Except(referenceCol, identityComparer);

            var remainingItemsInRef = referenceCol.Intersect(newCol, identityComparer);

            var changedItems = remainingItemsInRef.Except(newCol, contentComparer);

            var UnChangedItems = remainingItemsInRef.Except(changedItems);

            var r = new List <ComparisonResult <T> >();


            r.AddRange(removedItems.Select(itemRef => new ComparisonResult <T>(ComparisonStatus.Removed, itemRef)));
            r.AddRange(addedItems.Select(itemNew => new ComparisonResult <T>(ComparisonStatus.Added, itemNew)));
            r.AddRange(changedItems.Select(itemNew => new ComparisonResult <T>(ComparisonStatus.Modified, itemNew)));
            r.AddRange(UnChangedItems.Select(itemNew => new ComparisonResult <T>(ComparisonStatus.Unchanged, itemNew)));

            //            var sorter = new Sorter(comparer);
            var r2 = r.OrderBy(c => (keySortGetter == null) ? c.Item : keySortGetter(c.Item));

            return(r2);
        }
Beispiel #20
0
        private void InitializeProperties(IEnumerable <string> updatableProperties)
        {
            _allProperties = _propertyCache.GetOrAdd(
                _structuredType,
                (backingType) => backingType
                .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                .Where(p => (p.GetSetMethod() != null || TypeHelper.IsCollection(p.PropertyType)) && p.GetGetMethod() != null)
                .Select <PropertyInfo, PropertyAccessor <T> >(p => new FastPropertyAccessor <T>(p))
                .ToDictionary(p => p.Property.Name));

            if (updatableProperties != null)
            {
                _updatableProperties = updatableProperties.Intersect(_allProperties.Keys).ToList();
            }
            else
            {
                _updatableProperties = new List <string>(_allProperties.Keys);
            }

            if (_dynamicDictionaryPropertyinfo != null)
            {
                _updatableProperties.Remove(_dynamicDictionaryPropertyinfo.Name);
            }
        }
Beispiel #21
0
        public IEnumerable <TemplateAsset> GetResultWithoutFilter <T>(IFilter <T> filter)
        {
            IEnumerable <TemplateAsset> result = null;

            foreach (var f in StandardFilters.Values.Concat(CustomFilters.Where(cf => cf.SelectedFilter != null).Select(cf => cf.SelectedFilter)).Except(new[] { filter }))
            {
                if (f.SavedItems != null)
                {
                    if (result == null)
                    {
                        result = f.SavedItems;
                    }
                    else
                    {
                        result = result.Intersect(f.SavedItems);
                    }
                }
            }
            if (result == null)
            {
                result = Base;
            }
            return(result);
        }
Beispiel #22
0
        public static IEnumerable <T> IntersectMany <T>(this IEnumerable <IEnumerable <T> > src)
        {
            IEnumerable <T> ret = null;

            foreach (var subSrc in src)
            {
                if (ret == null)
                {
                    ret = subSrc;
                }
                else
                {
                    if (!ret.Any())
                    {
                        yield break;
                    }
                    ret = ret.Intersect(subSrc);
                }
            }
            foreach (var item in (ret ?? Enumerable.Empty <T>()))
            {
                yield return(item);
            }
        }
Beispiel #23
0
        public static IEnumerable <T> FilteredData(IEnumerable <FilterParams> filterParams, IEnumerable <T> data)
        {
            var distinctColumns = filterParams.Where(x => !string.IsNullOrEmpty(x.ColumnName))
                                  .Select(x => x.ColumnName).Distinct();

            foreach (var colName in distinctColumns)
            {
                var filterColumn = typeof(T).GetProperty(colName,
                                                         BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public);
                if (filterColumn != null)
                {
                    var filterValues =
                        filterParams.Where(x => x.ColumnName.Equals(colName)).Distinct();

                    if (filterValues.Count() > 1)
                    {
                        var sameColData = Enumerable.Empty <T>();

                        foreach (var val in filterValues)
                        {
                            sameColData = sameColData.Concat(FilterData(val.FilterOption, data, filterColumn,
                                                                        val.FilterValue));
                        }

                        data = data.Intersect(sameColData);
                    }
                    else
                    {
                        data = FilterData(filterValues.FirstOrDefault().FilterOption, data, filterColumn,
                                          filterValues.FirstOrDefault().FilterValue);
                    }
                }
            }

            return(data);
        }
Beispiel #24
0
        private static bool IsValidPpmLocation(string directory)
        {
            if (directory == null)
            {
                return false;
            }

            string[] requiredFiles =
            {
                Constants.PeloponneseExeName,
                Constants.PeloponneseExeName + ".config",
                "Microsoft.Research.Peloponnese.wrapper.cmd",
            };

            IEnumerable<string> requiredFilesLower = requiredFiles.Select(x => x.ToLower());

            IEnumerable<string> filesPresent =
                Directory.EnumerateFiles(directory, "*.exe", SearchOption.TopDirectoryOnly)
                .Concat(Directory.EnumerateFiles(directory, "*.config", SearchOption.TopDirectoryOnly))
                .Concat(Directory.EnumerateFiles(directory, "*.cmd", SearchOption.TopDirectoryOnly))
                .Select(x => Path.GetFileName(x).ToLower());

            return (filesPresent.Intersect(requiredFilesLower).Count() == requiredFilesLower.Count());
        }
Beispiel #25
0
        public ActionResult Filter(FiltrationViewModel filter)
        {
            IQueryable <Person> people = db.People;

            if (!string.IsNullOrEmpty(filter.Name))
            {
                people = people.Where(p => p.Name.ToLower().Contains(filter.Name.ToLower()));
            }
            if (!string.IsNullOrEmpty(filter.SecondName))
            {
                people = people.Where(p => p.SecondName.ToLower().Contains(filter.SecondName.ToLower()));
            }
            if (filter.PhoneNumber != null)
            {
                people = people.Where(p => p.PhoneNumber.ToString().Contains(filter.PhoneNumber.ToString()));
            }
            if (filter.CompanyId != 0)
            {
                people = people.Where(p => p.CompanyId.ToString().Contains(filter.CompanyId.ToString()));
            }
            IEnumerable <Person> people1 = people.Include(p => p.Company).ToList();

            if (filter.Skills != null)
            {
                List <Person> peopleSkilled = new List <Person>();
                Skill[]       skillet       = new Skill[filter.Skills.Length];
                for (int i = 0; i < filter.Skills.Length; i++)
                {
                    skillet[i] = db.Skills.Find(filter.Skills[i]);
                    people1    = people1.Intersect(skillet[i].People);
                }
            }
            filter.People           = people1;
            TempData["filterModel"] = filter;
            return(RedirectToAction("Index"));
        }
Beispiel #26
0
        private IEnumerable <Book> AllAnd(List <IEnumerable <Book> > listofbooks)
        {
            IEnumerable <Book> books = null;

            foreach (var listofbook in listofbooks)
            {
                if (listofbook != null)
                {
                    books = listofbook;
                    break;
                }
            }
            if (books != null)
            {
                foreach (IEnumerable <Book> listofbook in listofbooks)
                {
                    if (listofbook != null)
                    {
                        books = books.Intersect(listofbook).ToList();
                    }
                }
            }
            return(books);
        }
Beispiel #27
0
        public static void Main(string[] args)
        {
            WriteLine("# Part 2");
            WriteLine("--------");
            WriteLine();
            // const string fname = "example.txt";
            const string fname = "input.txt";

            var groups = FileUtils.Read(fname).Split("\n\n");

            var total = 0;

            foreach (var group in groups)
            {
                var elems = group.Split("\n");
                IEnumerable <char> common = elems[0];
                foreach (var elem in elems)
                {
                    common = common.Intersect(elem);
                }
                total += common.Count();
            }
            WriteLine(total);
        }
Beispiel #28
0
 public override bool Equals(object obj)
 {
     if (obj is Projection <T> )
     {
         var otherProjection = obj as Projection <T>;
         if (item != null && otherProjection.item != null)
         {
             IEnumerable <string> properties = this.properties;
             if (otherProjection.properties != null)
             {
                 properties = properties?.Intersect(otherProjection.properties) ?? otherProjection.properties;
             }
             if (properties != null)
             {
                 return(Compare(item, otherProjection.item, properties));
             }
         }
     }
     else if (obj != null && obj.GetType() == typeof(T))
     {
         return(Compare(item, (T)obj, properties));
     }
     return(base.Equals(obj));
 }
Beispiel #29
0
        private IEnumerable <Ksiazka> WszystkieI(List <IEnumerable <Ksiazka> > listaksiazek)
        {
            IEnumerable <Ksiazka> ksiazki = null;

            foreach (var listaksiazki in listaksiazek)
            {
                if (listaksiazki != null)
                {
                    ksiazki = listaksiazki;
                    break;
                }
            }
            if (ksiazki != null)
            {
                foreach (IEnumerable <Ksiazka> listaksiazki in listaksiazek)
                {
                    if (listaksiazki != null)
                    {
                        ksiazki = ksiazki.Intersect(listaksiazki).ToList();
                    }
                }
            }
            return(ksiazki);
        }
Beispiel #30
0
        public IEnumerable <T?> Call(IEnumerable <T> input)
        {
            if (input.Contains(_current))
            {
                return(NoOutput);
            }

            var matching = input.Intersect(_options);

            if (matching.Any())
            {
                _current = matching.First();
                return(new[] { _current });
            }
            else if (_current is not null)
            {
                _current = null;
                return(new[] { _current });
            }
            else
            {
                return(NoOutput);
            }
        }
        public GeneticDiff(
            IEnumerable <Gene <T> > genes1,
            IEnumerable <Gene <T> > genes2,
            IGeneChoice <T> geneChoice = null)
        {
            int maxInvoNb;
            IEnumerable <int>       commonInnovNbs;
            IEnumerable <Gene <T> > allGenes;

            commonInnovNbs = genes1.Select(x => x.InnovNb)
                             .Intersect(genes2.Select(x => x.InnovNb));

            if (geneChoice == null)
            {
                Matching = genes1.Intersect(genes2, new GeneInovEq <T>())
                           .ToArray();
            }
            else
            {
                Matching = commonInnovNbs.Select(x =>
                {
                    return(geneChoice.Choice(genes1.First(y => y.InnovNb == x),
                                             genes2.First(y => y.InnovNb == x)));
                }).ToArray();
            }

            allGenes  = genes1.Concat(genes2);
            maxInvoNb = allGenes.Max(x => x.InnovNb);
            Disjoint  = allGenes.Where(x =>
                                       !commonInnovNbs.Contains(x.InnovNb) &&
                                       x.InnovNb <= maxInvoNb).ToArray();

            Excess = allGenes.Where(x =>
                                    !commonInnovNbs.Contains(x.InnovNb) &&
                                    x.InnovNb > maxInvoNb).ToArray();
        }
 /// <summary>
 /// Initializes a new instance of the search input.
 /// </summary>
 /// <param name="options">Represents the search input options.</param>
 /// <param name="searchString">Represents the text to search for.</param>
 /// <param name="searchIn">Represents the fields in which to search for the given text.</param>
 /// <param name="filter">Represents the filters to be applied to the results.</param>
 /// <param name="sortBy">Represents the field based which to sort the results.</param>
 /// <param name="sortDirection">Represents the direction in which to sort the results.</param>
 /// <param name="itemsPerPage">Represents the number of items to be displayed at one time, on a single page.</param>
 /// <param name="currentPage">Represents the current page of the search.</param>
 public SearchInputViewModel(SearchOptionsViewModel options, string id = null, string searchString = null, IEnumerable <string> searchIn = null, IEnumerable <string> filter = null, string sortBy = null, string sortDirection = null, int?itemsPerPage = null, int?currentPage = 1)
 {
     // Check the search options for possible errors.
     if (options.Filter == null || options.ItemsPerPage == null || options.SearchIn == null || options.SortBy == null || options.SortDirection == null)
     {
         // Throw an exception.
         throw new ArgumentException();
     }
     // Assign the search options.
     Options = options;
     // Check if the given parameters are the default ones.
     NeedsRedirect = searchIn == null || filter == null || string.IsNullOrEmpty(sortBy) || !Options.SortBy.ContainsKey(sortBy) || string.IsNullOrEmpty(sortDirection) || !Options.SortDirection.ContainsKey(sortDirection) || itemsPerPage == null || itemsPerPage.Value < 1;
     // Get the default values for those that are null or invalid.
     searchString  = string.IsNullOrEmpty(searchString) ? string.Empty : searchString;
     searchIn      = searchIn ?? Enumerable.Empty <string>();
     filter        = filter ?? Enumerable.Empty <string>();
     sortBy        = string.IsNullOrEmpty(sortBy) || !Options.SortBy.ContainsKey(sortBy) ? Options.SortBy.FirstOrDefault().Key : sortBy;
     sortDirection = string.IsNullOrEmpty(sortDirection) || !Options.SortDirection.ContainsKey(sortDirection) ? Options.SortDirection.FirstOrDefault().Key : sortDirection;
     itemsPerPage  = itemsPerPage == null || itemsPerPage.Value < 1 ? Options.ItemsPerPage.FirstOrDefault().Key : itemsPerPage.Value;
     currentPage   = currentPage == null || currentPage.Value < 1 ? 1 : currentPage.Value;
     // Define the properties.
     Id            = id;
     SearchString  = searchString;
     SortBy        = sortBy;
     SortDirection = sortDirection;
     ItemsPerPage  = itemsPerPage.Value;
     CurrentPage   = currentPage.Value;
     SearchIn      = searchIn.Intersect(Options.SearchIn.Keys);
     Filter        = filter.Intersect(Options.Filter.Keys);
     // Check if there is a search string applied, but there are no values selected to search in.
     if (!string.IsNullOrEmpty(SearchString) && !SearchIn.Any())
     {
         // Select all of them.
         SearchIn = Options.SearchIn.Keys;
     }
 }
        private void SearchByMultipleRadical(string Radicals, Action UpdateStatusRadicalCountTextFunc, Action UpdateDataViewToEmpty)
        {
            IEnumerable <char> IntersectedChars = null;

            foreach (var Radical in Radicals)
            {
                if (Radical2Chars.TryGetValue(Radical, out string Chars))
                {
                    if (IntersectedChars == null)
                    {
                        IntersectedChars = Chars.ToList();
                        continue;
                    }
                    IntersectedChars = IntersectedChars.Intersect(Chars.ToList());
                }
                else
                {
                    IntersectedChars = null;
                    break;
                }
            }

            if (IntersectedChars == null)
            {
                UpdateDataViewToEmpty();
                return;
            }

            Dictionary <char, List <string> > result = new Dictionary <char, List <string> >();

            foreach (var Char in IntersectedChars)
            {
                result.Add(Char, Char2Radicals[Char]);
            }
            RefreshDataViewWithChars(result, UpdateStatusRadicalCountTextFunc);
        }
        private static bool AreEqual(IEnumerable <string> collectionA, IEnumerable <string> collectionB)
        {
            if (collectionA == null && collectionB == null)
            {
                return(true);
            }

            if (collectionA == null && collectionB != null)
            {
                return(false);
            }

            if (collectionA != null && collectionB == null)
            {
                return(false);
            }

            if (collectionA.Count() != collectionB.Count())
            {
                return(false);
            }

            return(collectionA.Intersect(collectionB).Count() == collectionA.Count());
        }
Beispiel #35
0
        /// <summary>
        /// Checks if consent is required.
        /// </summary>
        /// <param name="subject">The user.</param>
        /// <param name="client">The client.</param>
        /// <param name="scopes">The scopes.</param>
        /// <returns>
        /// Boolean if consent is required.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// client
        /// or
        /// subject
        /// </exception>
        public virtual async Task <bool> RequiresConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable <string> scopes)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }
            if (subject == null)
            {
                throw new ArgumentNullException(nameof(subject));
            }

            if (!client.RequireConsent)
            {
                return(false);
            }

            if (!client.AllowRememberConsent)
            {
                return(true);
            }

            if (scopes == null || !scopes.Any())
            {
                return(false);
            }

            var consent = await _userConsentStore.GetUserConsentAsync(subject.GetSubjectId(), client.ClientId);

            if (consent?.Scopes != null)
            {
                var intersect = scopes.Intersect(consent.Scopes);
                return(!(scopes.Count() == intersect.Count()));
            }

            return(true);
        }
Beispiel #36
0
        public static async Task PackageGame(string[] args)
        {
            var currentDirectory = Directory.GetCurrentDirectory();
            var directoryInfo    = new DirectoryInfo(currentDirectory);
            var gameName         = directoryInfo.Name;

            DirectoryInfo[]      directories    = directoryInfo.GetDirectories();
            IEnumerable <string> directoryNames = directories.Select((directoryInfo) => directoryInfo.Name);
            IEnumerable <string> expectedNames  = knownSuffixes.Select((suffix) => $"{gameName}.{suffix}");
            var detectedTargets = directoryNames.Intersect(expectedNames).ToList();

            // Bail if not in a known directory
            if (detectedTargets.Count() == 0)
            {
                Console.WriteLine("Expected directory structure not found.");
                Environment.Exit(-2);
            }


            if (args.Length == 1 || args[1] == "--all")
            {
                // Default to packaging whatever it can find.
                foreach (var target in detectedTargets)
                {
                    var suffix = target.Split(".").Last().ToLower();
                    await PackageTarget($"--{suffix}", gameName);
                }

                return;
            }

            for (var i = 1; i < args.Length; i++)
            {
                await PackageTarget(args[i], gameName);
            }
        }
        private void SearchNOW_Clicked(object sender, EventArgs e)
        {
            SaveSearchingStops(StartRouteSearchBar.Text, ReachRouteSearchBar.Text);
            List <string> startStopUids = StopSQLiteRepository.Instance
                                          .Get(StartRouteSearchBar.Text).Select(entity => entity.StopID).ToList();
            List <string> endStopUids = StopSQLiteRepository.Instance
                                        .Get(ReachRouteSearchBar.Text).Select(entity => entity.StopID).ToList();

            if (startStopUids.Count() <= 0 || endStopUids.Count() <= 0)
            {
                DisplayAlert("提醒", "查無此站牌", "重新輸入");
                StartRouteSearchBar.Text = "";
                ReachRouteSearchBar.Text = "";
                return;
            }

            StopOnRouteSQLiteRepository stopOnRouteRepository      = StopOnRouteSQLiteRepository.Instance;
            IEnumerable <string>        subrouteUidsPassStartStops = stopOnRouteRepository.Retrieve(startStopUids).Select(stopOnRoute => stopOnRoute.SubRouteUID).Distinct();
            IEnumerable <string>        subrouteUidsPassEndStops   = stopOnRouteRepository.Retrieve(endStopUids).Select(stopOnRoute => stopOnRoute.SubRouteUID).Distinct();
            IEnumerable <string>        subrouteUids = subrouteUidsPassStartStops.Intersect(subrouteUidsPassEndStops);
            IEnumerable <Route>         routes       = RouteSQLiteRepository.Instance.GetSubroute(subrouteUids);

            MainSrollView.Content = CreateLayoutFromRoutes(routes);
        }
        /// <summary>
        /// Lookup for a content item based on a <see cref="ContentIdentity"/>. If multiple
        /// resolvers can give a result, the one with the highest priority is used. As soon as
        /// only one content item is returned from resolvers, it is returned as the result.
        /// </summary>
        /// <param name="contentIdentity">The <see cref="ContentIdentity"/> instance to lookup</param>
        /// <returns>The <see cref="ContentItem"/> instance represented by the identity object.</returns>
        public ContentItem ResolveIdentity(ContentIdentity contentIdentity)
        {
            var resolvers = _identityResolverSelectors.Value
                            .Select(x => x.GetResolver(contentIdentity))
                            .Where(x => x != null)
                            .OrderByDescending(x => x.Priority);

            if (!resolvers.Any())
            {
                return(null);
            }

            IEnumerable <ContentItem> contentItems = null;

            foreach (var resolver in resolvers)
            {
                var resolved = resolver.Resolve(contentIdentity).ToArray();

                // first pass
                if (contentItems == null)
                {
                    contentItems = resolved;
                }
                else   // subsquent passes means we need to intersect
                {
                    contentItems = contentItems.Intersect(resolved).ToArray();
                }

                if (contentItems.Count() == 1)
                {
                    return(contentItems.First());
                }
            }

            return(contentItems.FirstOrDefault());
        }
Beispiel #39
0
        private static IEnumerable <Project> GetProjectsToExamineWorker(
            Solution solution,
            IImmutableSet <Project> projects,
            IEnumerable <ProjectId> projectsThatCouldReferenceType)
        {
            var dependencyGraph = solution.GetProjectDependencyGraph();

            // Take the projects that were passed in, and find all the projects that
            // they depend on (including themselves).  i.e. if we have a solution that
            // looks like:
            //      A <- B <- C <- D
            //          /
            //         └
            //        E
            // and we're passed in 'B, C, E' as the project to search, then this set
            // will be A, B, C, E.
            var allProjectsThatTheseProjectsDependOn = projects
                                                       .SelectMany(p => dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(p.Id))
                                                       .Concat(projects.Select(p => p.Id)).ToSet();

            // We then intersect this set with the actual set of projects that could reference
            // the type.  Say this list is B, C, D.  The intersection of this list and the above
            // one will then be 'B' and 'C'.
            //
            // In other words, there is no point searching A and E (because they can't even
            // reference the type).  And there's no point searching 'D' because it can't contribute
            // any information that would affect the result in the projects we are asked to search
            // within.

            // Finally, because we're searching metadata and source symbols, this needs to be a project
            // that actually supports compilations.
            return(projectsThatCouldReferenceType.Intersect(allProjectsThatTheseProjectsDependOn)
                   .Select(id => solution.GetRequiredProject(id))
                   .Where(p => p.SupportsCompilation)
                   .ToList());
        }
        public ActionResult BooksCollection(Publication gotten, bool CB_Id = false, bool CB_Name = false, bool CB_Author = false, bool CB_BBK = false, bool CB_Pub = false, bool CB_Avail = false, string AvailableT = "")
        {
            if (Session["CurUsr"] == null)
            {
                Response.Redirect("~/Library/SignIn");
            }
            IEnumerable <Publication> pubs = DM.Book.publications();

            if (CB_Id)
            {
                pubs = pubs.Intersect(DM.Book.publicationsById(gotten.Id));
            }
            if (CB_Name && gotten.Name != null)
            {
                pubs = pubs.Intersect(DM.Book.publicationsByName(gotten.Name));
            }
            if (CB_Author && gotten.Author != null)
            {
                pubs = pubs.Intersect(DM.Book.publicationsByAuthor(gotten.Author));
            }
            if (CB_BBK && gotten.BBK != null)
            {
                pubs = pubs.Intersect(DM.Book.publicationsByBBK(gotten.BBK));
            }
            if (CB_Pub && gotten.Publisher != null && gotten.Publisher.Name != null)
            {
                pubs = pubs.Intersect(DM.Book.publicationsByPub(gotten.Publisher.Name));
            }
            if (CB_Avail)
            {
                bool Avail = true;
                if (AvailableT == "Нет в наличии")
                {
                    Avail = false;
                }
                pubs = pubs.Intersect(DM.Book.publicationsByAvail(Avail));
            }
            ViewData["Books"] = pubs;
            return(View());
        }
 private static IEnumerable<Language> GetAvailableLanguagesMatchingSearchQuery(SearchQuery query, IEnumerable<Language> languages)
 {
     return languages.Intersect(query.Languages);
 }
Beispiel #42
0
 public void NullableInt(IEnumerable<int?> first, IEnumerable<int?> second, int?[] expected)
 {
     Assert.Equal(expected, first.Intersect(second));
     Assert.Equal(expected, first.Intersect(second, null));
 }
 /// <summary>Are there any common values between a and b?</summary>
 public static bool SharesAnyValueWith <T>(this IEnumerable <T> a, IEnumerable <T> b)
 => a == null || b == null
     ? false
     : a.Intersect(b).Any();
Beispiel #44
0
 public static bool IsDirectedAtRobot(IEnumerable<string> tokens, IEnumerable<string> robotNames)
 {
     return tokens.Intersect(robotNames, StringComparer.OrdinalIgnoreCase).Any();
 }
        public static HtmlString AlphabeticPager(
            this IHtmlHelper html,
            string selectedLetter,
            string alphabet,
            IEnumerable<string> firstLetters,
            string allLabel,
            string allValue,
            bool includeNumbers,
            Func<string, string> pageLink)
        {
            //TagBuilder got funky in beta7 http://stackoverflow.com/questions/32416425/tagbuilder-innerhtml-in-asp-net-5-mvc-6
            // so just using stringbuilder as of 2015-09-06
            // probably can change back to TagBuilder after beta 8 as it should then have an .Append method to set innerhtml

            var numbers = Enumerable.Range(0, 10).Select(i => i.ToString());
            List<string> alphabetList;
            if (string.IsNullOrEmpty(alphabet))
            {
                alphabetList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray().ToStringList();
            }
            else
            {
                alphabetList = alphabet.ToCharArray().ToStringList();
            }

            if (string.IsNullOrEmpty(allLabel))
            {
                allLabel = "All";
            }
            alphabetList.Insert(0, allLabel);
            if (includeNumbers)
            {
                alphabetList.Insert(1, "0-9");
            }

            var sb = new StringBuilder();

            //var ul = new TagBuilder("ul");
            //ul.AddCssClass("pagination");
            //ul.AddCssClass("alpha");
            sb.Append("<ul class='pagination alpha'>");


            //BufferedHtmlContent innerHtml = new BufferedHtmlContent();

            foreach (var letter in alphabetList)
            {
                //var li = new TagBuilder("li");
                sb.Append("<li");

                // firstletters is a list of which alpha chars actually have results
                // so that ones without data can be non links
                // if not provided then always make a link for every letter

                if (letter == "All" || firstLetters == null || firstLetters.Contains(letter)
                    || (firstLetters.Intersect(numbers).Any() && letter == "0-9"))
                {
                    if (selectedLetter == letter || string.IsNullOrEmpty(selectedLetter) && letter == "All")
                    {
                        //li.AddCssClass("active");
                        //var span = new TagBuilder("span");
                        //span.SetInnerText(letter);
                        //li.InnerHtml = span;
                        sb.Append(" class='active'>");
                        sb.Append("<span>" + letter + "</span>");
                        sb.Append("</li>");

                    }
                    else
                    {
                        sb.Append(">");

                        //var a = new TagBuilder("a");
                        sb.Append("<a href='");

                        if (letter == allLabel)
                        {
                            sb.Append(pageLink(allValue) + "'");
                            //a.MergeAttribute("href", pageLink(allValue));
                        }
                        else
                        {
                            sb.Append(pageLink(letter) + "'");
                            // a.MergeAttribute("href", pageLink(letter));
                        }
                        sb.Append(">");

                        //a.SetInnerText(letter);
                        sb.Append(letter);
                        sb.Append("</a>");
                        //li.InnerHtml = a;
                        sb.Append("</li>");

                    }
                }
                else
                {
                    sb.Append(" class='inactive'>");
                    sb.Append("<span>" + letter + "</span>");
                    sb.Append("</li>");

                    //li.AddCssClass("inactive");
                    //var span = new TagBuilder("span");
                    //span.SetInnerText(letter);
                    //li.InnerHtml = span;

                    

                }
                //sb.Append(li.ToString());
            }
            //ul.InnerHtml = sb.ToString();
            //ul.InnerHtml = new HtmlString(sb.ToString());
            sb.Append("</ul>");



            return new HtmlString(sb.ToString());
        }
Beispiel #46
0
        /// <summary>
        /// Attempts to execute a plan.
        /// </summary>
        /// <param name="disabledPluginKeys">Plugins that must be disabled.</param>
        /// <param name="stoppedPluginKeys">Plugins that must be stopped.</param>
        /// <param name="runningPluginKeys">Plugins that must be running.</param>
        /// <returns>A <see cref="IExecutionPlanError"/> that details the error if any.</returns>
        public IExecutionPlanResult Execute( IEnumerable<IPluginInfo> disabledPluginKeys, IEnumerable<IPluginInfo> stoppedPluginKeys, IEnumerable<IPluginInfo> runningPluginKeys )
        {
            if( PluginCreator == null ) throw new InvalidOperationException( R.PluginCreatorIsNull );
            if( ServiceReferencesBinder == null ) throw new InvalidOperationException( R.PluginConfiguratorIsNull );

            int nbIntersect;
            nbIntersect = disabledPluginKeys.Intersect( stoppedPluginKeys ).Count();
            if( nbIntersect != 0 ) throw new CKException( R.DisabledAndStoppedPluginsIntersect, nbIntersect );
            nbIntersect = disabledPluginKeys.Intersect( runningPluginKeys ).Count();
            if( nbIntersect != 0 ) throw new CKException( R.DisabledAndRunningPluginsIntersect, nbIntersect );
            nbIntersect = stoppedPluginKeys.Intersect( runningPluginKeys ).Count();
            if( nbIntersect != 0 ) throw new CKException( R.StoppedAndRunningPluginsIntersect, nbIntersect );

            List<PluginProxy> toDisable = new List<PluginProxy>();
            List<PluginProxy> toStop = new List<PluginProxy>();
            List<PluginProxy> toStart = new List<PluginProxy>();

            foreach( IPluginInfo k in disabledPluginKeys )
            {
                PluginProxy p = EnsureProxy( k );
                if( p.Status != RunningStatus.Disabled )
                {
                    toDisable.Add( p );
                    if( p.Status != RunningStatus.Stopped )
                    {
                        toStop.Add( p );
                    }
                }
            }
            foreach( IPluginInfo k in stoppedPluginKeys )
            {
                PluginProxy p = EnsureProxy( k );
                if( p.Status != RunningStatus.Stopped )
                {
                    toStop.Add( p );
                }
            }
            // The lists toDisable and toStop are correctly filled.
            // A plugin can be in both lists if it must be stopped and then disabled.

            // Now, we attempt to activate the plugins that must run: if an error occurs,
            // we leave and return the error since we did not change anything.
            foreach( IPluginInfo k in runningPluginKeys )
            {
                PluginProxy p = EnsureProxy( k );
                if( !p.IsLoaded )
                {
                    if( !p.TryLoad( _serviceHost, PluginCreator ) )
                    {
                        Debug.Assert( p.LoadError != null );
                        _serviceHost.LogMethodError( PluginCreator.Method, p.LoadError );
                        // Unable to load the plugin: leave now.
                        return new ExecutionPlanResult() { Culprit = p.PluginKey, Status = ExecutionPlanResultStatus.LoadError };
                    }
                    Debug.Assert( p.LoadError == null );
                    Debug.Assert( p.Status == RunningStatus.Disabled );
                    _newlyLoadedPlugins.Add( p );
                }
                if( p.Status != RunningStatus.Started )
                {
                    toStart.Add( p );
                }
            }
            // The toStart list is ready: plugins inside are loaded without error.

            // We stop all "toStop" plugin.
            // Their "stop" methods will be called.
            foreach( PluginProxy p in toStop )
            {
                if( p.Status > RunningStatus.Stopped )
                {
                    try
                    {
                        SetPluginStatus( p, RunningStatus.Stopping );
                        p.RealPlugin.Stop();
                        _log.Debug( String.Format( "The {0} plugin has been successfully stopped.", p.PublicName ) );
                    }
                    catch( Exception ex )
                    {
#if DEBUG
                    //Helps the developper identify the culprit of exception
                    Debugger.Break();
#endif 
                        _log.ErrorFormat( "There has been a problem when stopping the {0} plugin.", ex, p.PublicName );
                        _serviceHost.LogMethodError( p.GetImplMethodInfoStop(), ex );
                    }
                }
            }

            // We un-initialize all "toStop" plugin.
            // Their "Teardown" methods will be called.
            // After that, they are all "stopped".
            foreach( PluginProxy p in toStop )
            {
                try
                {
                    if( p.Status > RunningStatus.Stopped )
                    {
                        SetPluginStatus( p, RunningStatus.Stopped );
                        p.RealPlugin.Teardown();
                        _log.Debug( String.Format( "The {0} plugin has been successfully torn down.", p.PublicName ) );
                    }
                }
                catch( Exception ex )
                {
#if DEBUG
                    //Helps the developper identify the culprit of exceptions
                    Debugger.Break();
#endif
                    _log.ErrorFormat( "There has been a problem when tearing down the {0} plugin.", ex, p.PublicName );
                    _serviceHost.LogMethodError( p.GetImplMethodInfoTeardown(), ex );
                }
            }
            Debug.Assert( toStop.All( p => p.Status <= RunningStatus.Stopped ) );


            // Prepares the plugins to start so that they become the implementation
            // of their Service and are at least stopped (instead of disabled).
            foreach( PluginProxy p in toStart )
            {
                ServiceProxyBase service = p.Service;
                // The call to service.SetImplementation, sets the implementation and takes
                // the _status of the service into account: this status is at most Stopped
                // since we necessarily stopped the previous implementation (if any) above.
                if( service != null )
                {
                    Debug.Assert( service.Status <= RunningStatus.Stopped );
                    service.SetPluginImplementation( p );
                }
                // This call will trigger an update of the service status.
                if( p.Status == RunningStatus.Disabled ) SetPluginStatus( p, RunningStatus.Stopped );
            }

            // Now that services have been associated to their new implementation (in Stopped status), we
            // can disable the plugins that must be disabled.
            foreach( PluginProxy p in toDisable )
            {
                SetPluginStatus( p, RunningStatus.Disabled );
                try
                {
                    p.DisposeIfDisposable();
                }
                catch( Exception ex )
                {
#if DEBUG
                    //Helps the developper identify the culprit of exceptions
                    Debugger.Break();
#endif
                    _log.ErrorFormat( "There has been a problem when disposing the {0} plugin.", ex, p.PublicName );
                    _serviceHost.LogMethodError( p.GetImplMethodInfoDispose(), ex );
                }
            }

            // Before starting 
            for( int i = 0; i < toStart.Count; i++ )
            {
                PluginProxy p = toStart[i];
                // We configure plugin's edition properties.
                if( PluginConfigurator != null ) PluginConfigurator( p );

                SetPluginStatus( p, RunningStatus.Starting );
                IPluginSetupInfo info = new IPluginSetupInfo();
                try
                {
                    p.RealPlugin.Setup( info );
                    info.Clear();
                    _log.Debug( String.Format( "The {0} plugin has been successfully set up.", p.PublicName ) );
                }
                catch( Exception ex )
                {
#if DEBUG
                    //Helps the developper identify the culprit of exceptions
                    Debugger.Break();
#endif
                    _log.ErrorFormat( "There has been a problem when setting up the {0} plugin.", ex, p.PublicName );
                    _serviceHost.LogMethodError( p.GetImplMethodInfoSetup(), ex );

                    // Revoking the call to Setup for all plugins that haven't been started yet.
                    //Will pass the plugin to states : Stopping and then Stopped
                    for( int j = 0; j <= i; j++ )
                    {
                        RevokeSetupCall( toStart[j] );
                    }

                    info.Error = ex;
                    return new ExecutionPlanResult() { Culprit = p.PluginKey, Status = ExecutionPlanResultStatus.SetupError, SetupInfo = info };
                }
            }

            // Since we are now ready to start new plugins, it is now time to make the external world
            // aware of the existence of any new plugins and configure them to run.
            foreach( PluginProxy p in _newlyLoadedPlugins )
            {
                _loadedPlugins.Add( p.PluginKey.UniqueId, p );
            }
            Debug.Assert( ServiceReferencesBinder != null );
            try
            {
                var listNew = new ReadOnlyCollectionOnICollection<PluginProxy>( _newlyLoadedPlugins );
                //var disabled = new ReadOnlyCollectionAdapter<IPluginProxy, PluginProxy>( toDisable );
                ServiceReferencesBinder( listNew );
            }
            catch( Exception ex )
            {
                _serviceHost.LogMethodError( ServiceReferencesBinder.Method, ex );
            }
            _newlyLoadedPlugins.Clear();

            for( int i = 0; i < toStart.Count; i++ )
            {
                PluginProxy p = toStart[i];
                try
                {
                    SetPluginStatus( p, RunningStatus.Started );
                    p.RealPlugin.Start();
                    _log.Debug( String.Format( "The {0} plugin has been successfully started.", p.PublicName ) );
                }
                catch( Exception ex )
                {
                    // Emitted as low level log.
                    _log.ErrorFormat( "There has been a problem when starting the {0} plugin.", ex, p.PublicName );

                    // Emitted as a log event.
                    _serviceHost.LogMethodError( p.GetImplMethodInfoStart(), ex );

                    //All the plugins already started  when the exception was thrown have to be stopped + teardown (including this one in exception)
                    for( int j = 0; j <= i; j++ )
                    {
                        RevokeStartCall( toStart[j] );
                    }

                    // Revoking the call to Setup for all plugins that hadn't been started when the exception occured.
                    for( int j = i + 1; j < toStart.Count; j++ )
                    {
                        RevokeSetupCall( toStart[j] );
                    }

                    return new ExecutionPlanResult() { Culprit = p.PluginKey, Status = ExecutionPlanResultStatus.LoadError, Error = ex };
                }
            }
            return new ExecutionPlanResult();
        }
Beispiel #47
0
        private bool IsTagNeeded(IEnumerable<string> filterTags, IEnumerable<string> currentTags)
        {
            if (IsEmptyTagList(filterTags))
                return true;

            if (currentTags == null)
                return false;

            return filterTags.Intersect(currentTags).Any();
        }
 private static bool HasAnyRole(DeploymentProcessResource deploymentProcess, IEnumerable<string> roles)
 {
     foreach (var step in deploymentProcess.Steps) 
     {
         PropertyValueResource targetRolesProperty;
         if (step.Properties.TryGetValue("Octopus.Action.TargetRoles", out targetRolesProperty))
         {
             var targetRoles = targetRolesProperty.Value.Split(',');
             if (roles.Intersect(targetRoles).Any())
             {
                 return true;
             }
         }
     }
     
     return false;
 }
 /// <summary>
 /// Evaluate a term.
 /// </summary>
 /// <param name="factor">
 /// Left term already read as part of the expression.
 /// </param>
 /// <returns>Test methods described by the expression.</returns>
 /// <remarks>
 /// Non-terminal created for left-factoring:
 ///     {Term'} :=
 ///     	#empty#
 ///     	^ {Factor}{Term'}
 /// </remarks>
 private IEnumerable<ITestMethod> ReadTerm(IEnumerable<ITestMethod> factor)
 {
   if (TryMatch(Intersection))
   {
     return ReadTerm(factor.Intersect(ReadFactor()));
   }
   else
   {
     return factor;
   }
 }
        private static bool IsModifed(NavigationProperty navigationProperty, IEnumerable<string> modifiedMembers)
        {
            var association = navigationProperty.RelationshipType as AssociationType;
            if (association == null)
                return false;

            var referentialConstraint = association.ReferentialConstraints.FirstOrDefault();
            if (referentialConstraint == null)
                return false;

            var toProperties = referentialConstraint
                .ToProperties
                .Select(p => p.Name)
                .ToList();

            return modifiedMembers.Intersect(toProperties).Any();
        }
Beispiel #51
0
        /// <summary>
        /// Causes the Graph Pattern to be optimised if it isn't already
        /// </summary>
        /// <param name="gp">Graph Pattern</param>
        /// <param name="variables">Variables that have occurred prior to this Pattern</param>
        public void Optimise(GraphPattern gp, IEnumerable<String> variables)
        {
            //Our Variables is initially only those in our Triple Patterns since
            //anything else is considered to be out of scope
            List<String> ourVariables = (from tp in gp.TriplePatterns
                                         from v in tp.Variables
                                         select v).Distinct().ToList();

            //Start by sorting the Triple Patterns in the list according to the ranking function
            gp.TriplePatterns.Sort(this.GetRankingComparer());

            //Apply reordering unless an optimiser has chosen to disable it
            if (this.ShouldReorder)
            {
                if (gp.TriplePatterns.Count > 0)
                {
                    //After we sort which gives us a rough optimisation we then may want to reorder
                    //based on the Variables that occurred previous to us OR if we're the Root Graph Pattern

                    if (!variables.Any())
                    {
                        //Optimise this Graph Pattern
                        //No previously occurring variables so must be the first Graph Pattern
                        if (gp.TriplePatterns.Count > 1)
                        {
                            HashSet<String> currVariables = new HashSet<String>();
                            gp.TriplePatterns[0].Variables.ForEach(v => currVariables.Add(v));
                            for (int i = 1; i < gp.TriplePatterns.Count - 1; i++)
                            {
                                if (currVariables.Count == 0)
                                {
                                    gp.TriplePatterns[i].Variables.ForEach(v => currVariables.Add(v));
                                    continue;
                                }
                                else if (currVariables.IsDisjoint(gp.TriplePatterns[i].Variables))
                                {
                                    this.TryReorderPatterns(gp, currVariables.ToList(), i + 1, i);
                                    gp.TriplePatterns[i].Variables.ForEach(v => currVariables.Add(v));
                                }
                                else
                                {
                                    gp.TriplePatterns[i].Variables.ForEach(v => currVariables.Add(v));
                                }
                            }
                        }
                    }
                    else
                    {
                        //Optimise this Graph Pattern based on previously occurring variables
                        if (gp.TriplePatterns.Count > 1 && !gp.TriplePatterns[0].Variables.Any(v => variables.Contains(v)) && variables.Intersect(ourVariables).Any())
                        {
                            this.TryReorderPatterns(gp, variables.ToList(), 1, 0);
                        }
                        else if (gp.TriplePatterns.Count > 2)
                        {
                            //In the case where there are more than 2 patterns then we can try and reorder these
                            //in order to further optimise the pattern
                            this.TryReorderPatterns(gp, gp.TriplePatterns[0].Variables, 2, 1);
                        }
                    }
                }
            }

            if (this.ShouldPlaceAssignments)
            {
                //First we need to place Assignments (LETs) in appropriate places within the Pattern
                //This happens before Filter placement since Filters may use variables assigned to in LETs
                if (gp.UnplacedAssignments.Any())
                {
                    //Need to ensure that we sort Assignments
                    //This way those that use fewer variables get placed first
                    List<IAssignmentPattern> ps = gp.UnplacedAssignments.OrderBy(x => x).ToList();

                    //This next bit goes in a do loop as we want to keep attempting to place assignments while
                    //we are able to do so.  If the count of unplaced assignments has decreased but is not
                    //zero it may be that we were unable to place some patterns as they relied on variables
                    //assigned in other LETs which weren't placed when we attempted to place them
                    //When we reach the point where no further placements have occurred or all assignments
                    //are placed we stop trying to place assignments
                    int c;
                    do
                    {
                        c = ps.Count;

                        int i = 0;
                        while (i < ps.Count)
                        {
                            if (this.TryPlaceAssignment(gp, ps[i]))
                            {
                                //Remove from Unplaced Assignments since it's been successfully placed in the Triple Patterns
                                //Don't increment the counter since the next Assignment is now at the index we're already at
                                ps.RemoveAt(i);
                            }
                            else
                            {
                                //Unable to place so increment counter
                                i++;
                            }
                        }
                    } while (c > ps.Count && ps.Count > 0);
                }
            }

            //Regardless of what we've placed already we now place all remaining assignments
            foreach (IAssignmentPattern assignment in gp.UnplacedAssignments.ToList())
            {
                gp.InsertAssignment(assignment, gp.TriplePatterns.Count);
            }

            if (this.ShouldPlaceFilters)
            {
                //Then we need to place the Filters in appropriate places within the Pattern
                if (gp.UnplacedFilters.Any())
                {
                    if (gp.TriplePatterns.Count == 0)
                    {
                        //Where there are no Triple Patterns the Graph Pattern just contains this Filter and possibly some
                        //child Graph Patterns.  In such a case then we shouldn't place the Filters
                    }
                    else
                    {
                        foreach (ISparqlFilter f in gp.UnplacedFilters.ToList())
                        {
                            this.TryPlaceFilter(gp, f);
                        }
                    }
                }
            }

            //Finally optimise the Child Graph Patterns
            foreach (GraphPattern cgp in gp.ChildGraphPatterns)
            {
                //At each point the variables that have occurred are those in the Triple Patterns and
                //those in previous Graph Patterns
                cgp.Optimise(this, ourVariables);
                ourVariables.AddRange(cgp.Variables);
            }

            //Note: Any remaining Unplaced Filters/Assignments are OK since the ToAlgebra() method of a GraphPattern
            //will take care of placing these appropriately
        }
 /// <summary>
 /// Verifica se o usuário possui qualquer um dos papéis informado.
 /// </summary>
 /// <param name="roleIds">Os ids dos papéis.</param>
 /// <returns>
 /// True se possui.
 /// </returns>
 public bool HasAnyRole(IEnumerable<int> roleIds)
 {
     return roleIds.Contains(RoleId) || roleIds.Intersect(SubstituingRoleIds).Any();
 }
Beispiel #53
0
 /// <summary>
 /// The list does not contain the expected values.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="actual"></param>
 /// <param name="expected"></param>
 public static void MustNotContain <T>(this IEnumerable <T> actual, params T[] expected)
 {
     Assert.False(actual.Intersect(expected).Any());
 }
        //Jaccard or Tanimoto
        protected double JaccardDistance(IEnumerable<int> t1, IEnumerable<int> t2)
        {
            var common = t1.Intersect(t2).Count();

            return 1.0 - (1.0*common/(t1.Count() + t2.Count() - common));
        }
        private static IEnumerable GenerateEnumerable(Type objectType, FeatureLayerInfo layerInfo, IEnumerable<Graphic> graphics, string[] types, IEnumerable<Graphic> filter)
        {
            IEnumerable graphicsAfterFilter = filter != null ? graphics.Intersect<Graphic>(filter) : graphics;
            var listType = typeof(ObservableCollection<>).MakeGenericType(new[] { objectType });
            var listOfCustom = Activator.CreateInstance(listType);

            foreach (Graphic g in graphicsAfterFilter)
            {
                var row = AttributeListToObject(objectType, layerInfo, g, null, types);
                listType.GetMethod("Add").Invoke(listOfCustom, new[] { row });
            }
            return listOfCustom as IEnumerable;
        }
        private void buildIndexTables(IEnumerable<ITag> originalRootTags, TagUserAuthorizations auths)
        {
            //Search for visible tags and authorized photos
            Dictionary<string, IPhoto> authorizedPhotos = new Dictionary<string, IPhoto>();
            List<ITag> authorizedTags = getAuthorizedTags(originalRootTags, auths).ToList();
            HashSet<ITag> visibleTags = new HashSet<ITag>();
            foreach (var tag in authorizedTags)
            {
                foreach (var photo in tag.Photos)
                {
                    //even not directly authorized tags can be traversed or can reference authorized photo.
                    //We register them, but not theirs photos.
                    photo.Tags
                        .ForEach(t => getTagsHierarchy(t)
                            .ForEach(t2 => visibleTags.Add(t2)));

                    //Register photos from a directly authorized tag.
                    authorizedPhotos[photo.Id] = photo;
                }
            }

            //root tags
            this.rootTags = (from rootTag in originalRootTags.Intersect(visibleTags)
                                select new InternalTag(rootTag, authorizedTags, visibleTags, null)).ToList();

            //tag index
            tags = new Dictionary<string, InternalTag>();
            foreach (var rootTag in rootTags)
            {
                tags[rootTag.Id] = rootTag;
                foreach(var subTag in rootTag.AllTags)
                    tags[subTag.Id] = subTag;
            }

            //Order photo in a timeline list.
            var tempTimeline = new List<IPhoto>(authorizedPhotos.Values);
            tempTimeline.Sort((p1, p2) => p2.Date.CompareTo(p1.Date));
            timelinePhotos = new LinkedList<IPhoto>(tempTimeline);

            //day index for timeline.
            photosByDays = new Dictionary<DateTime, LinkedListNode<IPhoto>>();
            for (var item = timelinePhotos.First; item != null; item = item.Next)
                if (item == timelinePhotos.First || item.Previous.Value.Date.Date != item.Value.Date.Date)
                    photosByDays[item.Value.Date.Date] = item;

            //photo ids index for timeline.
            photosByIds = new Dictionary<string, LinkedListNode<IPhoto>>();
            for (var item = timelinePhotos.First; item != null; item = item.Next)
                photosByIds[item.Value.Id] = item;
        }
Beispiel #57
0
 /// <summary>
 /// Combines the result of two collections and returns a collection of all objects that exist in both. Used to combine filters.
 /// </summary>
 /// <param name="list1"></param>
 /// <param name="list2"></param>
 /// <returns>Returns a collection of objects that exist in both lists</returns>
 public IEnumerable <Loan> CombineFilteredLists(IEnumerable <Loan> list1, IEnumerable <Loan> list2)
 {
     return(list1.Intersect(list2));
 }
 public override IEnumerable<string> Execute(IEnumerable<string> firstReferences, IEnumerable<string> secondReferences)
 {
     var intersection = firstReferences.Intersect(secondReferences);
     return intersection;
 }
 public bool CanEnforcePolicies(IEnumerable <LoadingDockPolicy> loadingDockPolicies)
 {
     return(loadingDockPolicies.Intersect(SupportedPolicies).Any());
 }
Beispiel #60
0
        //<summary>
        // Filter an element list using another selector. A null selector results in no filtering.
        //</summary>
        //<param name="?"></param>
        //<param name="selector"></param>
        protected IEnumerable<IDomObject> filterElementsIgnoreNull(IEnumerable<IDomObject> elements, string selector)
        {
            if (selector=="")
            {
                return Objects.EmptyEnumerable<IDomObject>();
            }
            else if (selector == null)
            {
                return elements;
            }
            else
            {
                SelectorChain selectors = new SelectorChain(selector);
                if (selectors.Count > 0)
                {
                    selectors.ForEach(item=>item.TraversalType = TraversalType.Filter);
                }
                // this is kind of unfortunate but is required to keep the order correct. Probably a more efficient
                // way to do it but works fine for now

                return elements.Intersect(selectors.Select(Document, elements));
            }
        }