Ejemplo n.º 1
0
 public static bool AllEqual(this IList <ExpressionNode> arguments, IList <ExpressionNode> otherArguments)
 {
     if (arguments is null && otherArguments is null)
     {
         return(true);
     }
     return(arguments?.SequenceEqual(otherArguments ?? ZeroArguments) ?? false);
 }
Ejemplo n.º 2
0
Archivo: 645.cs Proyecto: pudae/lplpl
 private static IList<int> performTheExperiment(IList<int> xs)
 {
     var xs2 = xs.ToObservable().StartWith(0).Concat(Observable.Return(0))
     .Buffer(3, 1)
     .Where(l => l.Count == 3)
     .Select(l => changeSize(l[0], l[1], l[2]))
     .ToList()
     .First();
       if (xs.SequenceEqual(xs2))
     return xs;
       return performTheExperiment(xs2);
 }
Ejemplo n.º 3
0
 private void ViewModel_PropertyChanged(object?sender, PropertyChangedEventArgs e)
 {
     switch (e.PropertyName)
     {
     case nameof(ImportViewModel.SelectedItems):
         IList <ImportItem>?selectedItems = ViewModel.SelectedItems;
         if (!selectedItems?.SequenceEqual(DataGrid.SelectedItems.OfType <ImportItem>()) != true)
         {
             DataGrid.SelectionChanged -= DataGrid_SelectionChanged;
             DataGrid.SelectedItems.Clear();
             foreach (var item in selectedItems ?? Enumerable.Empty <ImportItem>())
             {
                 DataGrid.SelectedItems.Add(item);
             }
             DataGrid.SelectionChanged += DataGrid_SelectionChanged;
         }
         break;
     }
 }
		public static IMember Resolve(ITypeResolveContext context,
		                              EntityType entityType,
		                              string name,
		                              ITypeReference explicitInterfaceTypeReference = null,
		                              IList<string> typeParameterNames = null,
		                              IList<ITypeReference> parameterTypeReferences = null)
		{
			if (context.CurrentTypeDefinition == null)
				return null;
			if (parameterTypeReferences == null)
				parameterTypeReferences = EmptyList<ITypeReference>.Instance;
			if (typeParameterNames == null || typeParameterNames.Count == 0) {
				// non-generic member
				// In this case, we can simply resolve the parameter types in the given context
				var parameterTypes = parameterTypeReferences.Resolve(context);
				if (explicitInterfaceTypeReference == null) {
					foreach (IMember member in context.CurrentTypeDefinition.Members) {
						if (member.IsExplicitInterfaceImplementation)
							continue;
						if (IsNonGenericMatch(member, entityType, name, parameterTypes))
							return member;
					}
				} else {
					IType explicitInterfaceType = explicitInterfaceTypeReference.Resolve(context);
					foreach (IMember member in context.CurrentTypeDefinition.Members) {
						if (!member.IsExplicitInterfaceImplementation)
							continue;
						if (member.ImplementedInterfaceMembers.Count != 1)
							continue;
						if (IsNonGenericMatch(member, entityType, name, parameterTypes)) {
							if (explicitInterfaceType.Equals(member.ImplementedInterfaceMembers[0].DeclaringType))
								return member;
						}
					}
				}
			} else {
				// generic member
				// In this case, we must specify the correct context for resolving the parameter types
				foreach (IMethod method in context.CurrentTypeDefinition.Methods) {
					if (method.EntityType != entityType)
						continue;
					if (method.Name != name)
						continue;
					if (method.Parameters.Count != parameterTypeReferences.Count)
						continue;
					// Compare type parameter count and names:
					if (!typeParameterNames.SequenceEqual(method.TypeParameters.Select(tp => tp.Name)))
						continue;
					// Once we know the type parameter names are fitting, we can resolve the
					// type references in the context of the method:
					var contextForMethod = context.WithCurrentMember(method);
					var parameterTypes = parameterTypeReferences.Resolve(contextForMethod);
					if (!IsParameterTypeMatch(method, parameterTypes))
						continue;
					if (explicitInterfaceTypeReference == null) {
						if (!method.IsExplicitInterfaceImplementation)
							return method;
					} else if (method.IsExplicitInterfaceImplementation && method.ImplementedInterfaceMembers.Count == 1) {
						IType explicitInterfaceType = explicitInterfaceTypeReference.Resolve(contextForMethod);
						if (explicitInterfaceType.Equals(method.ImplementedInterfaceMembers[0].DeclaringType))
							return method;
					}
				}
			}
			return null;
		}
Ejemplo n.º 5
0
 /// <summary>
 /// Helper method will check if two lists have the exact same contents
 /// in a specific order.
 /// </summary>
 /// <param name="l1">list 1</param>
 /// <param name="l2">list 2</param>
 /// <returns>if equal</returns>
 static bool areListsEqual(IList <string> l1, IList <string> l2)
 {
     return(l1.SequenceEqual <string>(l2));
 }
Ejemplo n.º 6
0
 public bool IsListSorted(IList <string> list, IList <string> listSorted) => list.SequenceEqual(listSorted);
Ejemplo n.º 7
0
 protected bool Equals(DependencyGroup other)
 {
     return(_dependencies.SequenceEqual(other._dependencies) && string.Equals(Name, other.Name));
 }
Ejemplo n.º 8
0
        public void TestValidationOneSelectorManyFilters()
        {
            var             container      = GetConfiguredContainer();
            IRuleManager    ruleManager    = container.Resolve <IRuleManager>();
            IAccountManager accountManager = container.Resolve <IAccountManager>();

            int actId1 = 10000;

            AccountGroup accountGroup = new AccountGroup("1", "Group activity 1");
            AccountUser  account      = new AccountUserBuilder("0")
                                        .WithDisplayName("User 1")
                                        .WithEmail("*****@*****.**")
                                        .Build();

            accountManager.GetStore().SaveGroup(accountGroup);
            accountManager.GetStore().SaveAccounts(new List <AccountUser>()
            {
                account
            });
            accountManager.GetStore().Attach(account.Id, accountGroup.Id);

            // Selector created to Item 1
            SelectorDefinition selector_1 = new SelectorDefinition(null, DateTime.Now, actId1, accountGroup.Id);

            ruleManager.AddSelector(selector_1);

            RuleFilterDefinition filterDefinition_1_1 = new RuleFilterDefinition(null, "Division", "=", "BTL", selector_1.Id);

            ruleManager.AddFilter(filterDefinition_1_1);

            RuleFilterDefinition filterDefinition_1_2 = new RuleFilterDefinition(null, "Entity", "=", "ENT", selector_1.Id);

            ruleManager.AddFilter(filterDefinition_1_2);

            MyDummyDtObject myDummyDtObject = new MyDummyDtObject();

            myDummyDtObject.Division = "BTL";

            RuleContext ruleContext = new RuleContext(myDummyDtObject, RuleConstants.EmptyRuleConstants);

            // The entity is not set to ENT. The selector should not match
            IList <AccountUser> selectedAccounts_1 = ruleManager.SelectAccounts(actId1, ruleContext);

            Assert.IsNotNull(selectedAccounts_1);
            Assert.AreEqual(selectedAccounts_1.Count, 0);

            //We set the entity to 'ENT'
            myDummyDtObject.Entity = "ENT";
            ruleContext            = new RuleContext(myDummyDtObject, RuleConstants.EmptyRuleConstants);
            // The selector should match now.
            IList <AccountUser> selectedAccounts_2 = ruleManager.SelectAccounts(actId1, ruleContext);

            Assert.IsNotNull(selectedAccounts_2);
            Assert.AreEqual(selectedAccounts_2.Count, 1);
            Assert.IsTrue(selectedAccounts_2.SequenceEqual(new List <AccountUser>()
            {
                account
            }, new AccountEqualityComparer()));

            //We set the entity to 'XXX'
            myDummyDtObject.Entity = "XXX";
            ruleContext            = new RuleContext(myDummyDtObject, RuleConstants.EmptyRuleConstants);
            // The selector should not match .
            IList <AccountUser> selectedAccounts_3 = ruleManager.SelectAccounts(actId1, ruleContext);

            Assert.IsNotNull(selectedAccounts_3);
            Assert.AreEqual(selectedAccounts_3.Count, 0);
        }
 public override bool Equals(MultipartKey other)
 {
     return(parts.SequenceEqual(other.Parts));
 }
Ejemplo n.º 10
0
        public override bool Equals(object o)
        {
            if (this == o)
            {
                return(true);
            }
            if (o == null || this.GetType() != o.GetType())
            {
                return(false);
            }

            ProcedureSignature that = ( ProcedureSignature )o;

//JAVA TO C# CONVERTER WARNING: LINQ 'SequenceEqual' is not always identical to Java AbstractList 'equals':
//ORIGINAL LINE: return name.equals(that.name) && inputSignature.equals(that.inputSignature) && outputSignature.equals(that.outputSignature) && isVoid() == that.isVoid();
            return(_name.Equals(that._name) && _inputSignature.SequenceEqual(that._inputSignature) && _outputSignature.SequenceEqual(that._outputSignature) && Void == that.Void);
        }
Ejemplo n.º 11
0
 public bool Equals(IList <int>?x, IList <int>?y) => x != null && y != null && x.SequenceEqual(y);
 public bool Equals(IList <T> x, IList <T> y)
 {
     return(x.SequenceEqual(y));
 }
Ejemplo n.º 13
0
 private static bool IsOrderingTestSuccessfull <T>(IList <T> parent, IList <T> child, Func <T, bool> selection)
 {
     return(child.SequenceEqual(parent.Where(selection)));
 }
Ejemplo n.º 14
0
 protected bool Equals(ValidationNode other)
 {
     return(_strategies.SequenceEqual(other._strategies));
 }
Ejemplo n.º 15
0
        /// <summary>
        /// The merge modifies the target list so that all items equals the source list. This has some advantages over Clear and AddRange when
        /// the target list is bound to the UI or used by an ORM (Object Relational Mapping).
        /// </summary>
        /// <typeparam name="T">The type of the items.</typeparam>
        /// <param name="target">The target list.</param>
        /// <param name="source">The sort list.</param>
        /// <param name="comparer">Optional, a custom comparer can be provided.</param>
        /// <param name="insertAction">Optional, a custom action can be provided that is called for inserts.</param>
        /// <param name="removeAtAction">Optional, a custom action can be provided that is called for remove at.</param>
        /// <param name="resetAction">Optional, a custom action can be provided that is called for reset.</param>
        /// <param name="moveAction">Optional, a custom action can be provided that is called for move.</param>
        /// <exception cref="ArgumentNullException">target and source must not be <c>null</c>.</exception>
        public static void Merge <T>(this IList <T> target, IReadOnlyList <T> source, IEqualityComparer <T> comparer,
                                     Action <int, T> insertAction, Action <int> removeAtAction, Action resetAction, Action <int, int> moveAction)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            comparer = comparer ?? EqualityComparer <T> .Default;
            if (target.SequenceEqual(source, comparer))
            {
                return;
            }

            insertAction   = insertAction ?? target.Insert;
            removeAtAction = removeAtAction ?? target.RemoveAt;
            resetAction    = resetAction ?? (() =>
            {
                foreach (var item in target.ToArray())
                {
                    target.Remove(item);
                }                                                                // Avoid Clear because of CollectionChanged events
                foreach (var item in source)
                {
                    target.Add(item);
                }
            });

            // Item(s) added or removed
            if (target.Count != source.Count)
            {
                // Change of more than 1 item added or removed is not supported -> Reset
                if (Math.Abs(target.Count - source.Count) != 1)
                {
                    resetAction();
                    return;
                }

                if (target.Count < source.Count)
                {
                    int newItemIndex = -1;
                    for (int t = 0, s = 0; t < target.Count; t++, s++)
                    {
                        if (!comparer.Equals(target[t], source[s]))
                        {
                            if (newItemIndex != -1)
                            {
                                // Second change is not supported -> Reset
                                resetAction();
                                return;
                            }
                            newItemIndex = s;
                            t--;
                        }
                    }
                    if (newItemIndex == -1)
                    {
                        newItemIndex = source.Count - 1;
                    }
                    insertAction(newItemIndex, source[newItemIndex]);
                    return;
                }
                else
                {
                    int oldItemIndex = -1;
                    for (int t = 0, s = 0; s < source.Count; t++, s++)
                    {
                        if (!comparer.Equals(target[t], source[s]))
                        {
                            if (oldItemIndex != -1)
                            {
                                // Second change is not supported -> Reset
                                resetAction();
                                return;
                            }
                            oldItemIndex = t;
                            s--;
                        }
                    }
                    if (oldItemIndex == -1)
                    {
                        oldItemIndex = target.Count - 1;
                    }
                    removeAtAction(oldItemIndex);
                    return;
                }
            }
            else if (moveAction != null)  // Item(s) moved
            {
                var count = target.Count;
                for (int i = 0; i < count; i++)
                {
                    if (!comparer.Equals(target[i], source[i]))
                    {
                        if (i + 1 < count && comparer.Equals(target[i + 1], source[i]))
                        {
                            int newIndex = -1;
                            T   item     = target[i];
                            for (int s = i + 1; s < count; s++)
                            {
                                if (comparer.Equals(source[s], item))
                                {
                                    newIndex = s;
                                    break;
                                }
                            }
                            if (newIndex < 0)
                            {
                                // Item was replaced instead of moved
                                resetAction();
                                return;
                            }
                            for (int j = i + 1; j < count; j++)
                            {
                                if (!comparer.Equals(source[j <= newIndex ? j - 1 : j], target[j]))
                                {
                                    // Second move operation is not supported -> Reset
                                    resetAction();
                                    return;
                                }
                            }
                            moveAction(i, newIndex);
                            return;
                        }
                        else
                        {
                            int oldIndex = -1;
                            T   item     = source[i];
                            for (int t = i + 1; t < count; t++)
                            {
                                if (comparer.Equals(target[t], item))
                                {
                                    oldIndex = t;
                                    break;
                                }
                            }
                            if (oldIndex < 0)
                            {
                                // Item was replaced instead of moved
                                resetAction();
                                return;
                            }
                            for (int j = i + 1; j < count; j++)
                            {
                                if (!comparer.Equals(target[j <= oldIndex ? j - 1 : j], source[j]))
                                {
                                    // Second move operation is not supported -> Reset
                                    resetAction();
                                    return;
                                }
                            }
                            moveAction(oldIndex, i);
                            return;
                        }
                    }
                }
            }

            resetAction();
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Check if resource converters are equal.
 /// </summary>
 public override bool Equals(ResourceConverter obj)
 {
     return(part == obj.part && converters.SequenceEqual(obj.converters));
 }
Ejemplo n.º 17
0
        public static void AssertListEquals <T>(this IList <T> a, IList <T> b)
        {
            Assert.AreEqual(a.Count(), b.Count(), "The size of lists do not match");

            Assert.IsTrue(a.SequenceEqual(b));
        }
Ejemplo n.º 18
0
 public bool Equals(AttributeNode other)
 {
     return(other != null &&
            string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase) &&
            _values.SequenceEqual(other.Values));
 }
Ejemplo n.º 19
0
 protected bool Equals(ValidationOptions other)
 {
     return(_fields.SequenceEqual(other._fields));
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Returns true if the objects are equal.
 /// </summary>
 public override bool Equals(ResourceConverter other)
 {
     return(!ReferenceEquals(other, null) && Part == other.Part && converters.SequenceEqual(other.converters));
 }
 public bool Equals(CouchDesignDocument other)
 {
     return(Id.Equals(other.Id) && Language.Equals(other.Language) && Definitions.SequenceEqual(other.Definitions));
 }
Ejemplo n.º 22
0
 public static IMember Resolve(ITypeResolveContext context,
                               EntityType entityType,
                               string name,
                               ITypeReference explicitInterfaceTypeReference  = null,
                               IList <string> typeParameterNames              = null,
                               IList <ITypeReference> parameterTypeReferences = null)
 {
     if (context.CurrentTypeDefinition == null)
     {
         return(null);
     }
     if (parameterTypeReferences == null)
     {
         parameterTypeReferences = EmptyList <ITypeReference> .Instance;
     }
     if (typeParameterNames == null || typeParameterNames.Count == 0)
     {
         // non-generic member
         // In this case, we can simply resolve the parameter types in the given context
         var parameterTypes = parameterTypeReferences.Resolve(context);
         if (explicitInterfaceTypeReference == null)
         {
             foreach (IMember member in context.CurrentTypeDefinition.Members)
             {
                 if (member.IsExplicitInterfaceImplementation)
                 {
                     continue;
                 }
                 if (IsNonGenericMatch(member, entityType, name, parameterTypes))
                 {
                     return(member);
                 }
             }
         }
         else
         {
             IType explicitInterfaceType = explicitInterfaceTypeReference.Resolve(context);
             foreach (IMember member in context.CurrentTypeDefinition.Members)
             {
                 if (!member.IsExplicitInterfaceImplementation)
                 {
                     continue;
                 }
                 if (member.ImplementedInterfaceMembers.Count != 1)
                 {
                     continue;
                 }
                 if (IsNonGenericMatch(member, entityType, name, parameterTypes))
                 {
                     if (explicitInterfaceType.Equals(member.ImplementedInterfaceMembers[0].DeclaringType))
                     {
                         return(member);
                     }
                 }
             }
         }
     }
     else
     {
         // generic member
         // In this case, we must specify the correct context for resolving the parameter types
         foreach (IMethod method in context.CurrentTypeDefinition.Methods)
         {
             if (method.EntityType != entityType)
             {
                 continue;
             }
             if (method.Name != name)
             {
                 continue;
             }
             if (method.Parameters.Count != parameterTypeReferences.Count)
             {
                 continue;
             }
             // Compare type parameter count and names:
             if (!typeParameterNames.SequenceEqual(method.TypeParameters.Select(tp => tp.Name)))
             {
                 continue;
             }
             // Once we know the type parameter names are fitting, we can resolve the
             // type references in the context of the method:
             var contextForMethod = context.WithCurrentMember(method);
             var parameterTypes   = parameterTypeReferences.Resolve(contextForMethod);
             if (!IsParameterTypeMatch(method, parameterTypes))
             {
                 continue;
             }
             if (explicitInterfaceTypeReference == null)
             {
                 if (!method.IsExplicitInterfaceImplementation)
                 {
                     return(method);
                 }
             }
             else if (method.IsExplicitInterfaceImplementation && method.ImplementedInterfaceMembers.Count == 1)
             {
                 IType explicitInterfaceType = explicitInterfaceTypeReference.Resolve(contextForMethod);
                 if (explicitInterfaceType.Equals(method.ImplementedInterfaceMembers[0].DeclaringType))
                 {
                     return(method);
                 }
             }
         }
     }
     return(null);
 }
Ejemplo n.º 23
0
 protected bool Equals(UserParameters other)
 {
     return(Usernames.SequenceEqual(other.Usernames));
 }
        private static void OnCollectionChanged <TSrc, TDest>(NotifyCollectionChangedEventArgs e,
                                                              IList <TSrc> source, IList <TDest> destination,
                                                              Func <TSrc, TDest> registerSync, Func <TSrc, TDest> deregisterSync,
                                                              Func <TSrc, TDest> getDestItem, Func <TDest, TSrc> getSrcItem,
                                                              Action clearSync)
        {
            List <TSrc>  newListSource;
            List <TDest> newListDestination;

            Action <Action> updateDestination = action => {
                var transactive = destination as TransactiveObservableCollection <TDest>;
                if (transactive != null)
                {
                    using (transactive.Transaction())
                        action();
                }
                else
                {
                    action();
                }
            };

            switch (e.Action)
            {
            case NotifyCollectionChangedAction.Add:
                newListSource = e.NewItems.Cast <TSrc>().ToList();

                newListDestination = new List <TDest>();
                foreach (var item in newListSource)
                {
                    newListDestination.Add(registerSync(item));
                }

                if (newListDestination.Count > 0)
                {
                    if (e.NewStartingIndex == -1)
                    {
                        if (newListDestination.Count == 1)
                        {
                            destination.Add(newListDestination[0]);
                        }

                        else
                        {
                            updateDestination(() => {
                                foreach (var item in newListDestination)
                                {
                                    destination.Add(item);
                                }
                            });
                        }
                    }
                    else
                    {
                        var index = e.NewStartingIndex;

                        if (newListDestination.Count == 1)
                        {
                            destination.Insert(index, newListDestination[0]);
                        }

                        else
                        {
                            updateDestination(() => {
                                foreach (var item in newListDestination)
                                {
                                    destination.Insert(index, item);
                                    index++;
                                }
                            });
                        }
                    }
                }
                break;

            case NotifyCollectionChangedAction.Remove:
                newListSource = e.OldItems.Cast <TSrc>().ToList();

                newListDestination = new List <TDest>();
                foreach (var item in newListSource)
                {
                    newListDestination.Add(deregisterSync(item));
                }

                if (newListDestination.Count > 0)
                {
                    if (newListDestination.Count == 1)
                    {
                        destination.Remove(newListDestination[0]);
                    }

                    else
                    {
                        updateDestination(() => {
                            foreach (var item in newListDestination)
                            {
                                destination.Remove(item);
                            }
                        });
                    }
                }
                break;

            case NotifyCollectionChangedAction.Replace:
                if (e.NewItems.Count != 1)
                {
                    throw new NotImplementedException(@"NotifyCollectionChangedAction.Replace && e.NewItems.Count != 1");
                }

                var oldSrc = e.OldItems.Cast <TSrc>().Single();
                var newSrc = e.NewItems.Cast <TSrc>().Single();

                var oldDest = deregisterSync(oldSrc);
                var newDest = registerSync(newSrc);

                var indexSrc  = source.IndexOf(newSrc);
                var indexDest = destination.IndexOf(oldDest);

                if (indexSrc != indexDest)
                {
                    throw new InvalidOperationException();
                }

                destination[indexDest] = newDest;

                break;

            case NotifyCollectionChangedAction.Reset:

                var sourceComparer = EqualityComparer <TSrc> .Default;

                // ложное срабатывание
                // здесь нельзя вызывать getDestItem, потому что в source уже новые элементы,а в _mapping еще старые.
                // в итогде mapping.Find выдает null, а за ним - NullReferenceException
                // getDestItem - можно вызывать для гарантированно неизменных элементов
                // getSrcItem - напротив, вызывать можно на всех, ибо destination пока содержит старые элементы
                // if (source.Count == destination.Count && !destination.SkipWhile((d, i) => d.Equals(getDestItem(source[i]))).Any()) {
                if (source.Count == destination.Count && source.SequenceEqual(destination.Select(getSrcItem), sourceComparer))
                {
                    // nop
                }
                else if (source.Count == 0)
                {
                    destination.Clear();
                    clearSync();

                    // addRange
                }
                else if (source.Count > destination.Count && !destination.SkipWhile((d, i) => sourceComparer.Equals(source[i], getSrcItem(d))).Any())
                {
                    var items = source.Skip(destination.Count).ToList();

                    OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, items), source, destination, registerSync, deregisterSync, getDestItem, getSrcItem, clearSync);

                    // removeRange
                }
                else if (source.Count < destination.Count && !source.Except(destination.Select(getSrcItem), sourceComparer).Any())
                {
                    var items = destination.Except(source.Select(getDestItem)).Select(getSrcItem).ToList();

                    OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, items), source, destination, registerSync, deregisterSync, getDestItem, getSrcItem, clearSync);
                }
                else
                {
                    // accurate
                    //Synchronize(source, destination);

                    // rough
                    clearSync();

                    updateDestination(() => {
                        destination.Clear();
                        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, (IList)source), source, destination, registerSync, deregisterSync, getDestItem, getSrcItem, clearSync);
                    });
                }
                break;

            default:
                throw new NotImplementedException(e.Action.ToString());
            }
        }
Ejemplo n.º 25
0
        protected void assertNonLLStar( Grammar g, IList<int> expectedBadAlts )
        {
            DecisionProbe.verbose = true; // make sure we get all error info
            ErrorQueue equeue = new ErrorQueue();
            ErrorManager.SetErrorListener( equeue );

            // mimic actions of org.antlr.Tool first time for grammar g
            if ( g.NumberOfDecisions == 0 )
            {
                g.BuildNFA();
                g.CreateLookaheadDFAs( false );
            }
            NonRegularDecisionMessage msg = getNonRegularDecisionMessage( equeue.errors );
            Assert.IsNotNull(msg, "expected fatal non-LL(*) msg");
            List<int> alts = new List<int>();
            alts.AddRange( msg.altsWithRecursion );
            alts.Sort();
            //Collections.sort( alts );
            //Assert.AreEqual( expectedBadAlts, alts );
            Assert.IsTrue( expectedBadAlts.SequenceEqual( alts ) );
        }
Ejemplo n.º 26
0
        public void TestDeleteSelectorsByGroupIds()
        {
            string groupIdToDelete = "10000";
            string groupIdToKeep   = "20000";

            int item1 = 10000;
            int item2 = 20000;
            int item3 = 30000;

            var          container   = GetConfiguredContainer();
            IRuleManager ruleManager = container.Resolve <IRuleManager>();

            // Rule created to Item 1
            SelectorDefinition selector1 = new SelectorDefinition(null, DateTime.Now, item1, groupIdToDelete);
            SelectorDefinition selector2 = new SelectorDefinition(null, DateTime.Now, item1, groupIdToDelete);
            SelectorDefinition selector3 = new SelectorDefinition(null, DateTime.Now, item2, groupIdToDelete);
            SelectorDefinition selector4 = new SelectorDefinition(null, DateTime.Now, item1, groupIdToKeep);
            SelectorDefinition selector5 = new SelectorDefinition(null, DateTime.Now, item2, groupIdToKeep);
            SelectorDefinition selector6 = new SelectorDefinition(null, DateTime.Now, item3, groupIdToKeep);

            ruleManager.AddSelector(selector1);
            ruleManager.AddSelector(selector2);
            ruleManager.AddSelector(selector3);
            ruleManager.AddSelector(selector4);
            ruleManager.AddSelector(selector5);
            ruleManager.AddSelector(selector6);

            IList <SelectorDefinition> rulesFetch_1_1 = ruleManager.GetSelectorsForItemId(item1);

            Assert.IsNotNull(rulesFetch_1_1);
            Assert.AreEqual(3, rulesFetch_1_1.Count);
            Assert.IsTrue(rulesFetch_1_1.SequenceEqual(new List <SelectorDefinition>()
            {
                selector1, selector2, selector4
            }, new SelectorEqualityComparer()));

            IList <SelectorDefinition> rulesFetch_1_2 = ruleManager.GetSelectorsForItemId(item2);

            Assert.IsNotNull(rulesFetch_1_2);
            Assert.AreEqual(2, rulesFetch_1_2.Count);
            Assert.IsTrue(rulesFetch_1_2.SequenceEqual(new List <SelectorDefinition>()
            {
                selector3, selector5
            }, new SelectorEqualityComparer()));

            IList <SelectorDefinition> rulesFetch_1_3 = ruleManager.GetSelectorsForItemId(item3);

            Assert.IsNotNull(rulesFetch_1_3);
            Assert.AreEqual(1, rulesFetch_1_3.Count);
            Assert.IsTrue(rulesFetch_1_3.SequenceEqual(new List <SelectorDefinition>()
            {
                selector6
            }, new SelectorEqualityComparer()));

            // Update rule. This is now associated with Item 2
            ruleManager.RemoveSelectorsFiltersByGroupId(groupIdToDelete);

            IList <SelectorDefinition> rulesFetch_2_1 = ruleManager.GetSelectorsForItemId(item1);

            Assert.IsNotNull(rulesFetch_2_1);
            Assert.AreEqual(1, rulesFetch_2_1.Count);
            Assert.IsTrue(rulesFetch_2_1.SequenceEqual(new List <SelectorDefinition>()
            {
                selector4
            }, new SelectorEqualityComparer()));

            IList <SelectorDefinition> rulesFetch_2_2 = ruleManager.GetSelectorsForItemId(item2);

            Assert.IsNotNull(rulesFetch_2_2);
            Assert.AreEqual(1, rulesFetch_2_2.Count);
            Assert.IsTrue(rulesFetch_2_2.SequenceEqual(new List <SelectorDefinition>()
            {
                selector5
            }, new SelectorEqualityComparer()));

            IList <SelectorDefinition> rulesFetch_2_3 = ruleManager.GetSelectorsForItemId(item3);

            Assert.IsNotNull(rulesFetch_2_3);
            Assert.AreEqual(1, rulesFetch_2_3.Count);
            Assert.IsTrue(rulesFetch_2_3.SequenceEqual(new List <SelectorDefinition>()
            {
                selector6
            }, new SelectorEqualityComparer()));
        }
Ejemplo n.º 27
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Save the new list of writing systems to the database
		/// </summary>
		/// ------------------------------------------------------------------------------------
		protected bool WsListChanged(CheckedListBox lstBox, IList<IWritingSystem> currList, ICollection<IWritingSystem> allSet)
		{
			if (allSet.Count != lstBox.Items.Count || allSet.Intersect(lstBox.Items.Cast<IWritingSystem>()).Count() != allSet.Count)
			{
				return true;
			}

			if (!currList.SequenceEqual(lstBox.CheckedItems.Cast<IWritingSystem>()))
			{
				return true;
			}
			return false;
		}
 private void Write(IList<int> trueOutput, IList<int> output, ref int correct)
 {
     if (output.SequenceEqual(trueOutput))
     {
         correct++;
         Console.Write("+\t");
     }
     else
         Console.Write("-\t");
     foreach (var element in trueOutput)
     {
         Console.Write(element);
     }
     Console.Write("\t");
     foreach (var element in output)
     {
         Console.Write(element);
     }
     Console.WriteLine();
 }
Ejemplo n.º 29
0
        public bool HaveSameSignature(
            IList<IParameterSymbol> parameters1,
            IList<IParameterSymbol> parameters2)
        {
            if (parameters1.Count != parameters2.Count)
            {
                return false;
            }

            return parameters1.SequenceEqual(parameters2, this.ParameterEquivalenceComparer);
        }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            // Problem 1
            int[] arr = new int[4] {
                10, 15, 3, 7
            };
            int k      = 17;
            var result = new Problem1().problem1(arr, k);

            System.Console.WriteLine("Problem 1: " + result);
            // Expected output 10,7 or 7, 10
            Debug.Assert(Tuple.Equals(result, Tuple.Create(10, 7)) || Tuple.Equals(result, Tuple.Create(7, 10)));

            // Problem 2
            arr = new int[3] {
                3, 2, 1
            };
            System.Console.Write("Problem 2: ");
            int[] res = new Problem2().problem2(arr);
            res.ToList().ForEach(x => System.Console.Write((x) + " "));
            Debug.Assert(res.SequenceEqual(new int[] { 2, 3, 6 }));
            System.Console.Write("\nProblem 2_1: ");
            res = new Problem2().problem2_1(arr);
            res.ToList().ForEach(x => System.Console.Write((x) + " "));
            // Expected output == [2, 3, 6]
            Debug.Assert(res.SequenceEqual(new int[] { 2, 3, 6 }));

            // Problem 3
            var root  = new Problem3().populateNode();
            var nodes = new Problem3().serialize(root);

            System.Console.Write("\nProblem 3: ");
            System.Console.WriteLine(nodes);
            // Expected output == left.left
            Debug.Assert(new Problem3().deserialize(nodes).Left.Left.Val == "left.left");

            // Problem 4
            arr = new int[] { 3, 4, -1, 1 };
            System.Console.Write("Problem 4: ");
            int res4 = new Problem4().problem4(arr);

            System.Console.WriteLine(res4);
            // Expected output == 2
            Debug.Assert(res4 == 2);

            // Problem 6
            var prob6 = new Problem6().problem6();

            System.Console.WriteLine($"Problem 6: {prob6}");
            Debug.Assert(prob6 == 2);

            // Problem 7
            var prob7 = new Problem7().problem7("111");

            System.Console.WriteLine($"Problem 7: {prob7}");

            // Problem simple ecryption
            var encr = new SimpleEncryptedString().encrypt("This is a test!", 1);

            System.Console.WriteLine($"Problem encrypted string: {encr}");
            Debug.Assert(encr == "hsi  etTi sats!");

            var decrypt = new SimpleEncryptedString().decrypt(encr, 1);

            System.Console.WriteLine($"Problem decrypted string: {decrypt}");
            Debug.Assert(decrypt == "This is a test!");

            encr = new SimpleEncryptedString().encrypt("This is a test!", 2);
            System.Console.WriteLine($"Problem encrypted string: {encr}");
            Debug.Assert(encr == "s eT ashi tist!");

            decrypt = new SimpleEncryptedString().decrypt(encr, 2);
            System.Console.WriteLine($"Problem decrypted string: {decrypt}");
            Debug.Assert(decrypt == "This is a test!");

            // Sort odd in-place
            var arrVal = new int[6] {
                5, 3, 2, 8, 1, 4
            };
            var output = new Kata().SortArray(arrVal);

            System.Console.Write("Sort Odd Values in Array: ");
            output.ToList().ForEach(x => System.Console.Write((x) + " "));
            Debug.Assert(output.SequenceEqual(new int[] { 1, 3, 2, 8, 5, 4 }));

            // Unival tree
            var prob8 = new Problem8();

            prob8.hydrateTree();
            int unival = prob8.problem8();

            System.Console.WriteLine($"\nProblem 8: {unival}");
            Debug.Assert(unival == 5, "Unival count should be 5");

            // Find all anagrams in a string
            var         anagram        = new AllAnagramsInString();
            IList <int> expectedOutput = anagram.FindAnagrams("cbaebabacd", "abc");

            System.Console.Write("Problem: All anagrams index in String: ");
            expectedOutput.ToList().ForEach(x => System.Console.Write((x) + " "));
            Debug.Assert(expectedOutput.SequenceEqual(new int[2] {
                0, 6
            }));

            expectedOutput = anagram.FindAnagrams("abab", "ab");
            System.Console.Write("\nProblem: All anagrams index in String: ");
            expectedOutput.ToList().ForEach(x => System.Console.Write((x) + " "));
            Debug.Assert(expectedOutput.SequenceEqual(new int[3] {
                0, 1, 2
            }));

            // Problem 9
            int prob9 = new Problem9().problem9(new int[5] {
                2, 4, 6, 2, 5
            });

            System.Console.WriteLine($"\nProblem 9: {prob9}");
            Debug.Assert(prob9 == 13);

            prob9 = new Problem9().problem9(new int[4] {
                5, 1, 1, 5
            });
            System.Console.WriteLine($"Problem 9: {prob9}");
            Debug.Assert(prob9 == 10);

            // Problem 11
            var problem11 = new Problem11();

            problem11.Add("dog");
            problem11.Add("deer");
            problem11.Add("deal");

            var results = problem11.Search("de");

            System.Console.Write("Problem 11: ");
            results.ToList().ForEach(x => System.Console.Write(x + " "));
            Debug.Assert(results.SequenceEqual(new string[] { "deer", "deal" }));

            System.Console.Write($"\nProblem 11 - Delete key `deal`: {problem11.deleteNode("deal")}");
            System.Console.Write("\nProblem 11- Search deleted key(`deal`): ");
            problem11.Search("deal").ToList().ForEach(_ => System.Console.Write(_));

            // Problem 12
            var problem12 = new Problem12();
            var output12  = problem12.problem12(5, new int[] { 1, 3, 5 });

            System.Console.Write($"\nProblem 12: {output12}");
            Debug.Assert(output12 == 5);

            // Problem 13
            var    prob13   = new Problem13();
            string output13 = prob13.problem13(text: "abcba", k: 2);

            System.Console.WriteLine($"\nProblem 13: {output13}");
            Debug.Assert(output13 == "bcb");
            output13 = prob13.problem13("aabbcc", 2);
            System.Console.Write($"Problem 13: {output13}");
            Debug.Assert(output13 == "aabb" || output13 == "bbcc");
            output13 = prob13.problem13Another("aabbcc", 3);
            System.Console.Write($"\nProblem 13: {output13}");
            Debug.Assert(output13 == "aabbcc");
            output13 = prob13.problem13("aabbcc", 4);
            System.Console.Write($"\nProblem 13: {output13}");
            Debug.Assert(output13 == String.Empty);

            // Problem Delete Multiple Items
            var delItem = new DeleteMultipleItems();

            int[] actual   = delItem.DeleteNth(new int[] { 1, 1, 3, 3, 7, 2, 2, 2, 2 }, 3);
            var   expected = new int[] { 1, 1, 3, 3, 7, 2, 2, 2 };

            Debug.Assert(expected.SequenceEqual(actual));

            // Problem 15
            var prob15 = new Problem15();
            IEnumerable <int> prob15Output = prob15.problem15(10);

            System.Console.Write("\nProblem 15: ");
            prob15Output.ToList().ForEach(_ => System.Console.Write(_ + " "));

            // Problem 16
            // input = 100
            var prob16         = new Problem16();
            var prob16Expected = prob16.problem16();

            System.Console.WriteLine($"\nProblem 16: {prob16Expected}");
            Debug.Assert(prob16Expected == 95);

            // Problem 17
            var prob17       = new Problem17();
            int prob17Output = prob17.problem17("dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext");

            System.Console.WriteLine($"Problem 17: {prob17Output}");
            Debug.Assert(prob17Output == 20);
            prob17Output = prob17.problem17("dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext");
            System.Console.WriteLine($"Problem 17: {prob17Output}");
            Debug.Assert(prob17Output == 32);

            // Problem 18
            var prob18 = new Problem18();
            IEnumerable <int> prob18Output = prob18.problem18(array: new int[] { 10, 5, 2, 7, 8, 7 }, k: 3);

            System.Console.Write("Problem 18: ");
            prob18Output.ToList().ForEach(_ => System.Console.Write(_ + " "));
            prob18Output = prob18.problem18Optimized(array: new int[] { 11, 12, 13, 12, 14, 11, 10, 9 }, k: 3);
            System.Console.Write("\nProblem 18: ");
            prob18Output.ToList().ForEach(_ => System.Console.Write(_ + " "));

            // Problem 22
            var prob22       = new Problem22();
            var text         = "thequickbrownfox";
            var dic          = new string[] { "quick", "brown", "the", "fox" };
            var prob22Output = prob22.problem22(text, dic);

            System.Console.Write("\nProblem 22: ");
            prob22Output.ToList().ForEach(_ => System.Console.Write(_ + " "));
            Debug.Assert(prob22Output.SequenceEqual(new string[] { "the", "quick", "brown", "fox" }));

            var prob22Other = prob22.prob22Another("bedbathandbeyond", new string[] { "bed", "bath", "bedbath", "and",
                                                                                      "beyond" });

            System.Console.Write("\nProblem 22: ");
            prob22Other.ToList().ForEach(_ => System.Console.Write(_ + " "));

            // Problem 26
            var prob26       = new Problem26();
            var prob26Output = prob26.problem26(2);

            System.Console.WriteLine($"\nProblem 26: {prob26Output}");

            // Problem min window
            var minWindow = new MinWindowProblem();
            IEnumerable <String> minOutput = minWindow.minWindowOther("this is a test string", "tist");

            System.Console.Write("Min Window: ");
            minOutput.ToList().ForEach(_ => System.Console.WriteLine(_));
            // Debug.Assert(minOutput == "t stri");
            minOutput = minWindow.minWindowOther("a", "b");
            System.Console.Write("\nMin Window: ");
            minOutput.ToList().ForEach(_ => System.Console.WriteLine(_));
            // Debug.Assert(minOutput == "");

            // Remove duplicates recursively
            var    remDups   = new RemoveDuplicates();
            string dupOutput = remDups.removeDuplicates("careermonk");

            System.Console.WriteLine($"\nRemove duplicates: {dupOutput}");
            Debug.Assert(dupOutput == "camonk");
            dupOutput = remDups.removeDuplicates("geeksforgeeg");
            System.Console.WriteLine($"Remove duplicates: {dupOutput}");
            Debug.Assert(dupOutput == "gksfor");

            // word boggle
            char[,] matrix =
            {
                { 'o', 'a', 'a', 'n' },
                { 'e', 't', 'a', 'e' },
                { 'i', 'h', 'k', 'r' },
                { 'i', 'f', 'l', 'v' }
            };
            string[] words = { "oath", "pea", "eat", "rain" };
            System.Console.Write("Word boggle: ");
            var boggle = new Boggle().boggle(matrix, words);

            System.Console.WriteLine(string.Join(", ", boggle));
            Debug.Assert(boggle.OrderBy(x => x).ToList().SequenceEqual(new string[] { "eat", "oath" }));

            // Candy problem
            var candy       = new Candy().candy(new int[] { 1, 0, 2 });
            var candyOutput = 5;

            System.Console.WriteLine($"Minimum Candies: {candy}");
            Debug.Assert(candy == candyOutput);
            candy       = new Candy().candy(new int[] { 1, 2, 2 });
            candyOutput = 4;
            System.Console.WriteLine($"Minimum Candies: {candy}");
            Debug.Assert(candy == candyOutput);

            // Lowest Common Ancestor - BST
            var lcaBst       = new LowestCommonAncestorBST();
            var lcabstOutput = lcaBst.lca();

            System.Console.WriteLine($"LCA BST: {lcabstOutput}");
            Debug.Assert(lcabstOutput == 12);

            // Lowest Common Ancestor - BT
            var lcaBt       = new LowestCommonAncestorBT();
            var lcabtOutput = lcaBt.lca();

            System.Console.WriteLine($"LCA BT: {lcabtOutput}");
            Debug.Assert(lcabtOutput == 2);

            // Topology Sort
            var topo       = new TopologySort();
            var topoOutput = topo.topologySort();

            System.Console.WriteLine($"Topology sort: {string.Join(',', topoOutput.ToList())}");
            Debug.Assert(topoOutput.SequenceEqual(new int[] { 5, 4, 2, 3, 1, 0 }));

            // LRU
            var lru = new LRU(4);

            lru.put(1, 1);
            lru.put(10, 15);
            lru.put(15, 10);
            lru.put(10, 16);
            System.Console.WriteLine($"LRU cache size: {lru.getCacheSize()}"); // 3
            System.Console.WriteLine($"Get LRU key-10: {lru.get(10)}");        // 16

            lru.put(12, 15);
            lru.put(18, 10);
            System.Console.WriteLine($"LRU cache size: {lru.getCacheSize()}"); // 4
            lru.put(13, 16);
            System.Console.WriteLine($"LRU cache size: {lru.getCacheSize()}"); // 4
            System.Console.WriteLine($"Get LRU key-1: {lru.get(1)}");          // -1
            System.Console.WriteLine($"Get LRU key-15: {lru.get(15)}");        // -1
            System.Console.WriteLine($"Get LRU key-18: {lru.get(18)}");        // 10
            System.Console.WriteLine($"Get LRU key-13: {lru.get(13)}");        // 16

            // Number Of Islands
            int[,] islands =
            {
                { 0, 1 },
                { 1, 0 },
                { 1, 1 },
                { 1, 0 }
            };
            int connected = new NumberOfIslands().numerOfIslands(islands);

            System.Console.WriteLine($"Number of Connected islands is: {connected}");
            Debug.Assert(connected == 1);
            islands = new int[, ] {
                { 0, 1, 1, 1, 0, 0, 0 },
                { 0, 0, 1, 1, 0, 1, 0 }
            };
            connected = new NumberOfIslands().numerOfIslands(islands);
            System.Console.WriteLine($"Number of Connected islands is: {connected}");
            Debug.Assert(connected == 2);

            // Minimum number of swaps
            int[] array    = { 4, 3, 2, 1 };
            int   minswaps = new MinimumSwapsToSort().minimumSwaps(array);

            System.Console.WriteLine($"Minimum swap for array -> {string.Join(",", array)} : {minswaps}");
            Debug.Assert(minswaps == 2);

            array    = new int[] { 1, 5, 4, 3, 2 };
            minswaps = new MinimumSwapsToSort().minimumSwaps(array);
            System.Console.WriteLine($"Minimum swap for array -> {string.Join(",", array)} : {minswaps}");
            Debug.Assert(minswaps == 2);

            // Snakes and Ladder
            // int[] positions = {3, 22, 5, 8, 11, 26, 20, 29,
            //     17, 4, 19, 7, 27, 1, 21, 9};
            (int rows, int cols) = (5, 6);
            int steps = rows * cols;

            int[] moves = new int[steps];
            Enumerable.Range(0, steps).ToList().ForEach(x =>
            {
                moves[x] = -1;
            });

            // Ladders
            moves[2]  = 21;
            moves[4]  = 7;
            moves[10] = 25;
            moves[19] = 28;

            // Snakes
            moves[26] = 0;
            moves[20] = 8;
            moves[16] = 3;
            moves[18] = 6;

            int minDistance = new SnakesNLadders().snakesnLadder(moves, steps);

            System.Console.WriteLine($"Snakes n Ladder: Minimum dice roll needed: {minDistance}");
            Debug.Assert(minDistance == 3);

            // Alternating array
            var altArray = new int[] { 1, 2, 3, 4, 5, 6 };

            System.Console.Write($"Alternating array output for array - {String.Join(", ", altArray)}");
            new AlternateArray().alternateArray(altArray);
            System.Console.WriteLine(" is: " + String.Join(", ", altArray));

            // Minimum platforms
            int[] arrivals   = new int[] { 0900, 0940, 0950, 1100, 1500, 1800 };
            int[] departures = new int[] { 0910, 1200, 1120, 1130, 1900, 2000 };

            int minPlatforms = new MinimumPlatforms().findPlatforms(arrivals, departures, arrivals.Length);

            System.Console.WriteLine($"Mininum platforms needed: {minPlatforms}");
            Debug.Assert(minPlatforms == 3);

            arrivals   = new int[] { 0900, 1100, 1235 };
            departures = new int[] { 1000, 1200, 1240 };

            minPlatforms = new MinimumPlatforms().findPlatforms(arrivals, departures, arrivals.Length);
            System.Console.WriteLine($"Mininum platforms needed: {minPlatforms}");
            Debug.Assert(minPlatforms == 1);

            // Reverse array in groups of size K
            int[] revArray = new int[] { 1, 2, 3, 4, 5 };
            k = 3;
            System.Console.WriteLine($"Reverse array: {String.Join(", ", revArray)} in group of \"{k}\"");
            new ReverseArrays().reverArrays(revArray, k);
            System.Console.WriteLine($"Reversed array: {String.Join(", ", revArray)}");

            // Cycle in undirected graph
            var hasCycle = new CyclesInUndirectedGraph(5).DetectCycle();

            System.Console.WriteLine($"Is the Graph cyclic: {hasCycle}");
            Debug.Assert(hasCycle == true);

            // Cycle in directed graph
            var dgCycle = new CycleInDirectedGraph(4).detectCycle();

            System.Console.WriteLine($"Is the Graph cyclic: {dgCycle}");
            Debug.Assert(dgCycle == false);

            // Typeahead
            System.Console.WriteLine("\nTypeahead:");
            System.Console.WriteLine("==========");
            var typeAhead = new Typeahead();

            words = new string[] { "table", "tablet", "mobile", "mob", "mobbed" };
            var ranks = new int[] { 9, 4, 8, 3, 1 };

            foreach (var(word, rank) in Enumerable.Zip(words, ranks))
            {
                typeAhead.AddNode(word, rank);
            }

            typeAhead.BuildMostSearchWords(wordLimit: 3);

            System.Console.Write("Most searched words by Rank:");
            typeAhead.GetMostSearchedWordsByRank().ToList().ForEach(_ => System.Console.Write(_.ToString() + ", "));
            System.Console.WriteLine("\nStrings starting with mob: " + string.Join(", ", typeAhead.SearchAllChildren("mob")));
            System.Console.WriteLine("Strings starting with tab: " + string.Join(", ", typeAhead.PrefixSearch("tab")));
            System.Console.WriteLine("Strings starting with let: " + string.Join(", ", typeAhead.SearchAllChildren("let")));

            // Problem 20
            var prob20 = new Problem20().problem20(new int[] { 3, 7, 8, 10 }, new int[] { 99, 1, 8, 101 });

            System.Console.WriteLine($"Problem 20: {prob20}");
            Debug.Assert(prob20 == 8);

            // Problem 21
            int prob21 = new Problem21(new int[] { 30, 75, 0, 50, 60, 150 }).problem21();

            System.Console.WriteLine($"Problem 21: {prob21}, for sequence - [30, 75, 0, 50, 60, 150]");
            Debug.Assert(prob21 == 2);
            prob21 = new Problem21(new int[] { 30, 75, 0, 50, 60, 150, 25, 45 }).problem21();
            System.Console.WriteLine($"Problem 21: {prob21}, for sequence - [30, 75, 0, 50, 60, 150, 25, 45]");
            Debug.Assert(prob21 == 3);

            // Problem 28
            string[]             sequence = { "the", "quick", "brown", "fox", "jumps", "over", "the",
                                              "lazy",            "dog" };
            IEnumerable <string> prob28 = new Problem28().problem28(sequence, k: 16);

            System.Console.WriteLine($"Problem 28: for sequence - [{string.Join(", ", sequence)}] - {string.Join(", ", prob28)}");

            sequence = new string[] { "This", "is", "an", "example", "of", "text", "justification" };
            prob28   = new Problem28().problem28(sequence, k: 16);
            System.Console.WriteLine($"Problem 28: for sequence - [{string.Join(", ", sequence)}] - {string.Join(", ", prob28)}");

            // Make maximum sum
            arr = new int[] { 1, 1, 3 };
            int probMaxSum = new RemoveMinSum().removeMinSum(arr);

            System.Console.WriteLine($"Remove Min Sum for sequence - [{string.Join(", ", arr)}] is: {probMaxSum}");
            Debug.Assert(probMaxSum == 3);

            arr        = new int[] { 1, 1, 3, 3, 2, 2, 1, 1, 1 };
            probMaxSum = new RemoveMinSum().removeMinSum(arr);
            System.Console.WriteLine($"Remove Min Sum for sequence - [{string.Join(", ", arr)}] is: {probMaxSum}");
            Debug.Assert(probMaxSum == 11);

            // string permutation
            text = "abca";
            IEnumerable <string> stringPerm = new StringPermutation().permute(text, "");

            System.Console.WriteLine($"String permutation - {string.Join(", ", stringPerm)}");

            // linked list grouping
            var llGroup = new GroupLinkedListsByIntersectionPoint().getLinkedListsByGroup().ToList();

            System.Console.WriteLine("Group LinkedList by intersection nodes:");
            for (int i = 0; i < llGroup.Count; i++)
            {
                System.Console.WriteLine($"Group {i + 1}: [{string.Join(", ", llGroup[i])}]");
            }

            // minimum repetitive window
            arr = new int[] { 1, 2, 1, 2, 3 };
            int minimumRepetitionWindow = new MinimumRepetitionWindow().minimumRepetitionWindow(arr);

            System.Console.WriteLine($"Minimum repetitive window for sequence - [{string.Join(", ", arr)}] is: {minimumRepetitionWindow}");
            Debug.Assert(minimumRepetitionWindow == 3);

            arr = new int[] { 1, 2, 1, 2, 3, 2, 1 };
            minimumRepetitionWindow = new MinimumRepetitionWindow().minimumRepetitionWindow(arr);
            System.Console.WriteLine($"Minimum repetitive window for sequence - [{string.Join(", ", arr)}] is: {minimumRepetitionWindow}");
            Debug.Assert(minimumRepetitionWindow == 5);

            // problem 24
            var prob24 = new Problem24();

            System.Console.WriteLine($"Problem 24: [{string.Join(", ", prob24.problem24())}]");
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Check the engines are equal.
 /// </summary>
 public override bool Equals(Engine obj)
 {
     return(part == obj.part && engines.SequenceEqual(obj.engines) && multiModeEngine == obj.multiModeEngine && gimbal == obj.gimbal);
 }
Ejemplo n.º 32
0
        public override void WriteInitializationScript(TextWriter writer)
        {
            IClientSideObjectWriter objectWriter = ClientSideObjectWriterFactory.Create(Id, "tTreeView", writer);

            objectWriter.Start();

            if (!defaultEffects.SequenceEqual(Effects.Container))
            {
                objectWriter.Serialize("effects", Effects);
            }

            if (ShowCheckBox)
            {
                objectWriter.Append("showCheckBox", ShowCheckBox);
            }

            if (DragAndDrop.Enabled)
            {
                if (DragAndDrop.DropTargets.HasValue())
                {
                    var dragAndDropOptions = new Dictionary <string, string>();

                    dragAndDropOptions["dropTargets"] = DragAndDrop.DropTargets;

                    objectWriter.AppendObject("dragAndDrop", dragAndDropOptions);
                }
                else
                {
                    objectWriter.Append("dragAndDrop", true);
                }
            }

            if (Ajax.Enabled)
            {
                Dictionary <string, string> ajax = new Dictionary <string, string>();

                ajax["selectUrl"] = UrlGenerator.Generate(ViewContext.RequestContext, Ajax.Select);

                objectWriter.AppendObject("ajax", ajax);
            }

            if (WebService.Enabled)
            {
                Dictionary <string, string> webService = new Dictionary <string, string>();

                webService["selectUrl"] = UrlGenerator.Generate(ViewContext.RequestContext, WebService.Select.Url);

                objectWriter.AppendObject("ws", webService);
            }

            objectWriter.AppendClientEvent("onExpand", ClientEvents.OnExpand);
            objectWriter.AppendClientEvent("onCollapse", ClientEvents.OnCollapse);
            objectWriter.AppendClientEvent("onSelect", ClientEvents.OnSelect);
            objectWriter.AppendClientEvent("onLoad", ClientEvents.OnLoad);
            objectWriter.AppendClientEvent("onError", ClientEvents.OnError);
            objectWriter.AppendClientEvent("onChecked", ClientEvents.OnChecked);
            objectWriter.AppendClientEvent("onNodeDragStart", ClientEvents.OnNodeDragStart);
            objectWriter.AppendClientEvent("onNodeDragging", ClientEvents.OnNodeDragging);
            objectWriter.AppendClientEvent("onNodeDragCancelled", ClientEvents.OnNodeDragCancelled);
            objectWriter.AppendClientEvent("onNodeDrop", ClientEvents.OnNodeDrop);
            objectWriter.AppendClientEvent("onNodeDropped", ClientEvents.OnNodeDropped);
            objectWriter.AppendClientEvent("onDataBinding", ClientEvents.OnDataBinding);
            objectWriter.AppendClientEvent("onDataBound", ClientEvents.OnDataBound);

            objectWriter.Complete();
            base.WriteInitializationScript(writer);
        }
Ejemplo n.º 33
0
 protected bool Equals(Polynomial other)
 {
     return(coefficients.SequenceEqual(other.coefficients));
 }
Ejemplo n.º 34
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Save the new list of writing systems to the database
		/// </summary>
		/// ------------------------------------------------------------------------------------
		protected void SaveWs(CheckedListBox lstBox, IList<IWritingSystem> currList, ICollection<IWritingSystem> allSet)
		{
			if (allSet.Count != lstBox.Items.Count || allSet.Intersect(lstBox.Items.Cast<IWritingSystem>()).Count() != allSet.Count)
			{
				var newWsIds = new List<string>();
				foreach (IWritingSystem ws in lstBox.Items)
				{
					string id = ws.IcuLocale;
					if (allSet.FirstOrDefault(existing => existing.IcuLocale == id) == null)
						newWsIds.Add(id);
				}
				allSet.Clear();
				foreach (IWritingSystem ws in lstBox.Items)
				{
					if (ws.Handle == 0)
						m_cache.ServiceLocator.WritingSystemManager.Replace(ws);
					allSet.Add(ws);
				}
				m_fWsChanged = true;
				foreach (var newWs in newWsIds)
				{
					// IcuLocale uses _ to separate, RFC5646 uses -.  We need the latter (see FWNX-1165).
					ProgressDialogWithTask.ImportTranslatedListsForWs(this, m_cache, newWs.Replace("_","-"));
				}
			}

			if (!currList.SequenceEqual(lstBox.CheckedItems.Cast<IWritingSystem>()))
			{
				currList.Clear();
				foreach (IWritingSystem ws in lstBox.CheckedItems)
					currList.Add(ws);
				m_fWsChanged = true;
			}
		}
Ejemplo n.º 35
0
 /// <inheritdoc/>
 public bool Equals(IEventSequence other)
 {
     return(other != null && _events.SequenceEqual(other.Events));
 }
        /// <summary>
        /// Comapres linked Objects details of recommendation action entity
        /// </summary>
        private static void CompareRecommendedActionLinkedObjects(IList<string> expected, IEnumerable<string> response)
        {
            Assert.False(expected != null ^ response != null);

            if (response != null)
            {
                Assert.True(expected.SequenceEqual(response));
            }
        }
Ejemplo n.º 37
0
 protected bool Equals(Activity other)
 {
     return(base.Equals(other) && _nested.SequenceEqual(other._nested));
 }
Ejemplo n.º 38
0
        public IEnumerable<ISonesIndex> GetIndices(IVertexType myVertexType, IList<IPropertyDefinition> myPropertyDefinition, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            myVertexType.CheckNull("myVertexType");
            myPropertyDefinition.CheckNull("myPropertyDefinition");

            if (myPropertyDefinition.Count == 0)
                throw new ArgumentOutOfRangeException("myPropertyDefinition", "At least one property must be given.");

            var propertyTypes = myPropertyDefinition.GroupBy(_ => _.RelatedType);
            foreach (var group in propertyTypes)
            {
                if (!myVertexType.IsDescendantOrSelf(group.Key))
                {
                    throw new ArgumentException(string.Format("The properties ({0}) defined on type {1} is not part of inheritance hierarchy of {2}.",
                        string.Join(",", group.Select(_ => _.Name)),
                        group.Key.Name,
                        myVertexType.Name));
                }
            }

            var result = myVertexType.GetIndexDefinitions(false).Where(_ => myPropertyDefinition.SequenceEqual(_.IndexedProperties)).Select(_=>_indices[_.ID]).ToArray();

            return result;
        }
Ejemplo n.º 39
0
 public bool Equals(IList <T> x, IList <T> y)
 {
     return((x == null && y == null) ||
            ((x != null && y != null) &&
             x.SequenceEqual(y)));
 }