Beispiel #1
0
        public virtual void LinkedHashSetTest()
        {
            LinkedHashSet <int> set1 = new LinkedHashSet <int>();

            set1.Add(5);
            set1.Add(2);
            set1.Add(3);
            set1.Add(5);

            Assert.AreEqual(5, set1.First());
            Assert.AreEqual(3, set1.Last());
            Assert.AreEqual(3, set1.Count);

            LinkedHashSet <int> set2 = new LinkedHashSet <int>();

            set2.Add(2);
            set2.Add(5);

            Assert.True(set1.IsSupersetOf(set2));
            Assert.True(set1.IsProperSupersetOf(set2));
            Assert.True(set2.IsSubsetOf(set1));
            Assert.True(set2.IsProperSubsetOf(set1));

            Assert.False(set2.IsSupersetOf(set1));

            LinkedHashSet <int> set3 = new LinkedHashSet <int>();

            set3.Add(5);
            set3.Add(2);

            Assert.True(set3.SetEquals(set2));
        }
            public HashSet <Action> actions(Object state)
            {
                EightPuzzleBoard board = (EightPuzzleBoard)state;

                HashSet <Action> actions = new LinkedHashSet <Action>();

                if (board.canMoveGap(EightPuzzleBoard.UP))
                {
                    actions.Add(EightPuzzleBoard.UP);
                }
                if (board.canMoveGap(EightPuzzleBoard.DOWN))
                {
                    actions.Add(EightPuzzleBoard.DOWN);
                }
                if (board.canMoveGap(EightPuzzleBoard.LEFT))
                {
                    actions.Add(EightPuzzleBoard.LEFT);
                }
                if (board.canMoveGap(EightPuzzleBoard.RIGHT))
                {
                    actions.Add(EightPuzzleBoard.RIGHT);
                }

                return(actions);
            }
            public HashSet<Action> actions(Object state)
            {
                EightPuzzleBoard board = (EightPuzzleBoard)state;

                HashSet<Action> actions = new LinkedHashSet<Action>();

                if (board.canMoveGap(EightPuzzleBoard.UP))
                {
                    actions.Add(EightPuzzleBoard.UP);
                }
                if (board.canMoveGap(EightPuzzleBoard.DOWN))
                {
                    actions.Add(EightPuzzleBoard.DOWN);
                }
                if (board.canMoveGap(EightPuzzleBoard.LEFT))
                {
                    actions.Add(EightPuzzleBoard.LEFT);
                }
                if (board.canMoveGap(EightPuzzleBoard.RIGHT))
                {
                    actions.Add(EightPuzzleBoard.RIGHT);
                }

                return actions;
            }
Beispiel #4
0
        public void TestTryGetNextValue()
        {
            var set = new LinkedHashSet <string>(EqualityComparer <string> .Default);

            set.Add("1");

            Assert.That(set.TryGetNextValue("1", out var nextValue), Is.False);
            Assert.That(nextValue, Is.Null);

            set.Add("3");

            Assert.That(set.TryGetNextValue("1", out nextValue), Is.True);
            Assert.That(nextValue, Is.EqualTo("3"));

            Assert.That(set.TryGetNextValue("3", out nextValue), Is.False);
            Assert.That(nextValue, Is.Null);

            set.Add("2");

            Assert.That(set.TryGetNextValue("1", out nextValue), Is.True);
            Assert.That(nextValue, Is.EqualTo("3"));

            Assert.That(set.TryGetNextValue("3", out nextValue), Is.True);
            Assert.That(nextValue, Is.EqualTo("2"));

            Assert.That(set.TryGetNextValue("2", out nextValue), Is.False);
            Assert.That(nextValue, Is.Null);
        }
Beispiel #5
0
        public void TestFirstAndLast()
        {
            var set = new LinkedHashSet <string>(EqualityComparer <string> .Default);

            set.Add("10");

            Assert.That(set.First, Is.EqualTo("10"));
            Assert.That(set.Last, Is.EqualTo("10"));

            set.Add("20");
            set.Add("30");

            Assert.That(set.First, Is.EqualTo("10"));
            Assert.That(set.Last, Is.EqualTo("30"));

            set.Remove("10");
            set.Remove("30");

            Assert.That(set.First, Is.EqualTo("20"));
            Assert.That(set.Last, Is.EqualTo("20"));

            set.Add("10");

            Assert.That(set.First, Is.EqualTo("20"));
            Assert.That(set.Last, Is.EqualTo("10"));

            set.Add("30");

            Assert.That(set.First, Is.EqualTo("20"));
            Assert.That(set.Last, Is.EqualTo("30"));
        }
 static CellWorldAction()
 {
     _actions.Add(ActionEnum.Up);
     _actions.Add(ActionEnum.Down);
     _actions.Add(ActionEnum.Left);
     _actions.Add(ActionEnum.Right);
     _actions.Add(ActionEnum.None);
 }
Beispiel #7
0
        private ContainerEvent MakeContainerEvent(String value)
        {
            ISet <Level1Event> level1s = new LinkedHashSet <Level1Event>();

            level1s.Add(new Level1Event(new Level2Event("X1".AsSet(), "X1").AsSet()));
            level1s.Add(new Level1Event(new Level2Event(value.AsSet(), value).AsSet()));
            level1s.Add(new Level1Event(new Level2Event("X2".AsSet(), "X2").AsSet()));
            return(new ContainerEvent(level1s));
        }
Beispiel #8
0
        private ContainerEvent MakeContainerEvent(string value)
        {
            var level1s = new LinkedHashSet <Level1Event>();

            level1s.Add(new Level1Event(Collections.SingletonSet(new Level2Event(Collections.SingletonSet("X1"), "X1"))));
            level1s.Add(new Level1Event(Collections.SingletonSet(new Level2Event(Collections.SingletonSet(value), value))));
            level1s.Add(new Level1Event(Collections.SingletonSet(new Level2Event(Collections.SingletonSet("X2"), "X2"))));
            return(new ContainerEvent(level1s));
        }
        /// <summary>
        /// Returns descriptors for all writable properties.
        /// </summary>
        /// <param name="eventType">to reflect on</param>
        /// <param name="allowAnyType">whether any type property can be populated</param>
        /// <returns>list of writable properties</returns>
        public static ICollection <WriteablePropertyDescriptor> GetWriteableProperties(EventType eventType, bool allowAnyType)
        {
            if (!(eventType is EventTypeSPI))
            {
                return(null);
            }
            if (eventType is BeanEventType)
            {
                var beanEventType = (BeanEventType)eventType;
                return(PropertyHelper.GetWritableProperties(beanEventType.UnderlyingType));
            }
            var typeSPI = (EventTypeSPI)eventType;

            if (!allowAnyType && !AllowPropulate(typeSPI))
            {
                return(null);
            }
            if (eventType is BaseNestableEventType)
            {
                IDictionary <string, Object>       mapdef    = ((BaseNestableEventType)eventType).Types;
                ISet <WriteablePropertyDescriptor> writables = new LinkedHashSet <WriteablePropertyDescriptor>();
                foreach (var types in mapdef)
                {
                    if (types.Value is Type)
                    {
                        writables.Add(new WriteablePropertyDescriptor(types.Key, (Type)types.Value, null));
                    }
                    if (types.Value is string)
                    {
                        var  typeName = types.Value.ToString();
                        Type clazz    = TypeHelper.GetPrimitiveTypeForName(typeName);
                        if (clazz != null)
                        {
                            writables.Add(new WriteablePropertyDescriptor(types.Key, clazz, null));
                        }
                    }
                }
                return(writables);
            }
            else if (eventType is AvroSchemaEventType)
            {
                var writables = new LinkedHashSet <WriteablePropertyDescriptor>();
                var desc      = typeSPI.WriteableProperties;
                foreach (var prop in desc)
                {
                    writables.Add(new WriteablePropertyDescriptor(prop.PropertyName, prop.PropertyType, null));
                }
                return(writables);
            }
            else
            {
                return(null);
            }
        }
Beispiel #10
0
 private bool AddDisconnectedAbbreviation(IAtomContainer mol, string label)
 {
     try
     {
         var cansmi = SmilesGenerator.Unique.Create(mol);
         disconnectedAbbreviations[cansmi] = label;
         labels.Add(label);
         return(true);
     }
     catch (CDKException)
     {
         return(false);
     }
 }
Beispiel #11
0
 private static SupportContainerLevelEvent MakeContainerEvent(string value)
 {
     ISet<SupportContainerLevel1Event> level1s = new LinkedHashSet<SupportContainerLevel1Event>();
     level1s.Add(
         new SupportContainerLevel1Event(
             Collections.SingletonSet(new SupportContainerLevel2Event(Collections.SingletonSet("X1"), "X1"))));
     level1s.Add(
         new SupportContainerLevel1Event(
             Collections.SingletonSet(new SupportContainerLevel2Event(Collections.SingletonSet(value), value))));
     level1s.Add(
         new SupportContainerLevel1Event(
             Collections.SingletonSet(new SupportContainerLevel2Event(Collections.SingletonSet("X2"), "X2"))));
     return new SupportContainerLevelEvent(level1s);
 }
        private void RegisterAllMcrs()
        {
            pageToPageMcrs = new Dictionary <PdfIndirectReference, ParentTreeHandler.PageMcrsContainer>();
            // we create new number tree and not using parentTree, because we want parentTree to be empty
            IDictionary <int?, PdfObject> parentTreeEntries = new PdfNumTree(structTreeRoot.GetDocument().GetCatalog(),
                                                                             PdfName.ParentTree).GetNumbers();
            ICollection <PdfDictionary> mcrParents = new LinkedHashSet <PdfDictionary>();
            int maxStructParentIndex = -1;

            foreach (KeyValuePair <int?, PdfObject> entry in parentTreeEntries)
            {
                if (entry.Key > maxStructParentIndex)
                {
                    maxStructParentIndex = (int)entry.Key;
                }
                PdfObject entryValue = entry.Value;
                if (entryValue.IsDictionary())
                {
                    mcrParents.Add((PdfDictionary)entryValue);
                }
                else
                {
                    if (entryValue.IsArray())
                    {
                        PdfArray parentsArray = (PdfArray)entryValue;
                        for (int i = 0; i < parentsArray.Size(); ++i)
                        {
                            PdfDictionary parent = parentsArray.GetAsDictionary(i);
                            if (parent != null)
                            {
                                mcrParents.Add(parent);
                            }
                        }
                    }
                }
            }
            structTreeRoot.GetPdfObject().Put(PdfName.ParentTreeNextKey, new PdfNumber(maxStructParentIndex + 1));
            foreach (PdfObject mcrParent in mcrParents)
            {
                PdfStructElem mcrParentStructElem = new PdfStructElem((PdfDictionary)mcrParent);
                foreach (IStructureNode kid in mcrParentStructElem.GetKids())
                {
                    if (kid is PdfMcr)
                    {
                        RegisterMcr((PdfMcr)kid, true);
                    }
                }
            }
        }
Beispiel #13
0
 /// <summary>
 /// Checks recursively that the node has a circular dependency.
 /// </summary>
 /// <param name="node">
 /// The node of the DAG.
 /// </param>
 /// <exception cref="CircularDependencyException">
 /// if the circular dependency has occurred.
 /// </exception>
 public void Check(T node)
 {
     if (!set.Add(node))
     {
         var list = new List <T>(set)
         {
             node,
         };
         var index = list.IndexOf(node);
         var loop  = list.GetRange(index, list.Count - index);
         throw CircularDependencyException.Of(loop);
     }
     try
     {
         var dependencies = getDependencies(node)
                            .Where(d => !checkedSet.Contains(d));
         foreach (var d in dependencies)
         {
             Check(d);
         }
         checkedSet.Add(node);
     }
     finally
     {
         set.Remove(node);
     }
 }
        public static ISet<string> AssignEventAsTagNumber(
            ISet<string> priorAllTags,
            EvalForgeNode evalForgeNode)
        {
            var allTagNamesOrdered = new LinkedHashSet<string>();
            var filterFactoryNodes = EvalNodeUtil.RecursiveGetChildNodes(
                evalForgeNode,
                StreamSpecCompiler.FilterForFilterFactoryNodes.INSTANCE);
            if (priorAllTags != null) {
                allTagNamesOrdered.AddAll(priorAllTags);
            }

            foreach (var filterNode in filterFactoryNodes) {
                var forge = (EvalFilterForgeNode) filterNode;
                int tagNumber;
                if (forge.EventAsName != null) {
                    if (!allTagNamesOrdered.Contains(forge.EventAsName)) {
                        allTagNamesOrdered.Add(forge.EventAsName);
                        tagNumber = allTagNamesOrdered.Count - 1;
                    }
                    else {
                        tagNumber = FindTagNumber(forge.EventAsName, allTagNamesOrdered);
                    }

                    forge.EventAsTagNumber = tagNumber;
                }
            }

            return allTagNamesOrdered;
        }
Beispiel #15
0
        /// <summary>
        /// Add a filter callback. The filter callback set allows adding the same callback twice with no effect.
        /// If a client to the class needs to check that the callback already existed, the contains method does that.
        /// NOTE: the client to this method must use the read-write lock of this object to lock, if required
        /// by the client code.
        /// </summary>
        /// <param name="filterCallback">is the callback to add</param>
        public void Add(FilterHandle filterCallback)
        {
            _callbackSet.Add(filterCallback);
#if DEBUG && DIAGNOSTICS
            System.Diagnostics.Debug.WriteLine("{0}: Add: {1} / {2} / {3}", System.Threading.Thread.CurrentThread.ManagedThreadId, _id, _callbackSet.Count, System.Threading.Thread.CurrentThread.ManagedThreadId);
#endif
        }
Beispiel #16
0
        private ISet <string> MakeWithPrefix(string prefix, int n)
        {
            ISet <string> set = new LinkedHashSet <string>();

            IntStream.range(0, n).forEach(i => set.Add(prefix + i));
            return(set);
        }
Beispiel #17
0
        protected void ReadConfig(IOrmConfigGroup ormConfigGroup)
        {
            LinkedHashSet <IEntityConfig> entities = new LinkedHashSet <IEntityConfig>();

            entities.AddAll(ormConfigGroup.GetLocalEntityConfigs());
            entities.AddAll(ormConfigGroup.GetExternalEntityConfigs());

            foreach (IEntityConfig entityConfig in entities)
            {
                Type entityType = entityConfig.EntityType;
                if (EntityMetaDataProvider.GetMetaData(entityType, true) != null)
                {
                    continue;
                }
                Type realType = entityConfig.RealType;

                EntityMetaData metaData = new EntityMetaData();
                metaData.EntityType  = entityType;
                metaData.RealType    = realType;
                metaData.LocalEntity = entityConfig.Local;

                EntityMetaDataReader.AddMembers(metaData, entityConfig);

                managedEntityMetaData.Add(metaData);
                lock (EntityMetaDataExtendable)
                {
                    EntityMetaDataExtendable.RegisterEntityMetaData(metaData);
                }
            }
        }
Beispiel #18
0
        /// <summary>
        ///     Factory for a bean type.
        /// </summary>
        /// <param name="name">type name</param>
        /// <param name="clazz">java class</param>
        /// <param name="isConfigured">whether the class was made known or is discovered</param>
        /// <param name="typeClass">type of type</param>
        /// <param name="isPreConfigured">preconfigured</param>
        /// <param name="isPreConfiguredStatic">preconfigured via static config</param>
        /// <returns>instance</returns>
        public static EventTypeMetadata CreateBeanType(
            string name,
            Type clazz,
            bool isPreConfiguredStatic,
            bool isPreConfigured,
            bool isConfigured,
            TypeClass typeClass)
        {
            ISet<string> secondaryNames = null;
            if (name == null)
            {
                name = clazz.Name;
            }
            else
            {
                if (!name.Equals(clazz.Name))
                {
                    secondaryNames = new LinkedHashSet<string>();
                    secondaryNames.Add(clazz.Name);
                }
            }

            return new EventTypeMetadata(
                name, secondaryNames, typeClass, isPreConfiguredStatic, isPreConfigured, isConfigured,
                ApplicationType.CLASS, false);
        }
Beispiel #19
0
        public override void ValidateGetContextProps(
            LinkedHashMap<string, object> props,
            string contextName,
            StatementRawInfo statementRawInfo,
            StatementCompileTimeServices services)
        {
            var propertyTypes = ContextControllerKeyedUtil.ValidateContextDesc(contextName, detail);

            for (var i = 0; i < detail.Items[0].PropertyNames.Count; i++) {
                var propertyName = ContextPropertyEventType.PROP_CTX_KEY_PREFIX + (i + 1);
                props.Put(propertyName, propertyTypes[i]);
            }

            var allTags = new LinkedHashSet<string>();
            foreach (var item in detail.Items) {
                if (item.AliasName != null) {
                    allTags.Add(item.AliasName);
                }
            }

            if (detail.OptionalInit != null) {
                foreach (var filter in detail.OptionalInit) {
                    ContextPropertyEventType.AddEndpointTypes(filter, props, allTags);
                }
            }
        }
        /// <summary>
        /// Registers all pending labels.
        /// Called once per frame during LateUpdate by the <see cref="PerceptionUpdater"/>.
        /// </summary>
        public void RegisterPendingLabels()
        {
            if (m_RegisteredLabels.Count == 0)
            {
                m_NextObjectIndex = k_StartingIndex;
            }

            foreach (var unregisteredLabel in m_LabelsPendingRegistration)
            {
                if (m_RegisteredLabels.Contains(unregisteredLabel))
                {
                    continue;
                }

                var instanceId = m_NextObjectIndex++;

                RecursivelyInitializeGameObjects(
                    unregisteredLabel.gameObject,
                    new MaterialPropertyBlock(),
                    unregisteredLabel,
                    instanceId);

                unregisteredLabel.SetInstanceId(instanceId);
                m_RegisteredLabels.Add(unregisteredLabel);
            }

            m_LabelsPendingRegistration.Clear();
        }
Beispiel #21
0
        /** Return the set of all methods either inherited or not */
        public IEnumerable <MethodSymbol> GetMethods()
        {
            LinkedHashSet <MethodSymbol> methods = new LinkedHashSet <MethodSymbol>();
            ClassSymbol superClassScope          = GetBaseClassScope();
            IEnumerable <MethodSymbol> temp;

            if (superClassScope != null)
            {
                temp = superClassScope.GetMethods();
                foreach (var item in temp)
                {
                    methods.Add(item);
                }
            }
            temp = GetDefinedMethods();
            if (temp != null)
            {
                foreach (var item in temp)
                {
                    methods.Remove(item); // override method from superclass
                }
                temp = GetDefinedMethods();
                foreach (var item in temp)
                {
                    methods.Remove(item); // override method from superclass
                }
            }
            return(methods);
        }
Beispiel #22
0
        /// <summary>Returns a reversed map of the current map.</summary>
        /// <returns>A reversed map of the current map.</returns>
        public virtual IDictionary <string, ICollection <string> > GetReverseMap()
        {
            ICollection <KeyValuePair <string, ICollection <string> > > entries = map;
            IDictionary <string, ICollection <string> > rMap = Generics.NewHashMap(entries.Count);

            foreach (KeyValuePair <string, ICollection <string> > me in entries)
            {
                string k = me.Key;
                ICollection <string> transList = me.Value;
                foreach (string trans in transList)
                {
                    ICollection <string> entry = rMap[trans];
                    if (entry == null)
                    {
                        // reduce default size as most will be small
                        ICollection <string> toAdd = new LinkedHashSet <string>(6);
                        toAdd.Add(k);
                        rMap[trans] = toAdd;
                    }
                    else
                    {
                        entry.Add(k);
                    }
                }
            }
            return(rMap);
        }
Beispiel #23
0
        /// <summary>
        ///     Validate the variant stream definition.
        /// </summary>
        /// <param name="variantStreamname">the stream name</param>
        /// <param name="variantStreamConfig">the configuration information</param>
        /// <param name="repo">the event types</param>
        /// <returns>specification for variant streams</returns>
        private static VariantSpec ValidateVariantStream(
            string variantStreamname,
            ConfigurationCommonVariantStream variantStreamConfig,
            EventTypeRepositoryImpl repo)
        {
            if (variantStreamConfig.TypeVariance == TypeVariance.PREDEFINED) {
                if (variantStreamConfig.VariantTypeNames.IsEmpty()) {
                    throw new ConfigurationException(
                        "Invalid variant stream configuration, no event type name has been added and default type variance requires at least one type, for name '" +
                        variantStreamname +
                        "'");
                }
            }

            ISet<EventType> types = new LinkedHashSet<EventType>();
            foreach (var typeName in variantStreamConfig.VariantTypeNames) {
                var type = repo.GetTypeByName(typeName);
                if (type == null) {
                    throw new ConfigurationException(
                        "Event type by name '" +
                        typeName +
                        "' could not be found for use in variant stream configuration by name '" +
                        variantStreamname +
                        "'");
                }

                types.Add(type);
            }

            var eventTypes = types.ToArray();
            return new VariantSpec(eventTypes, variantStreamConfig.TypeVariance);
        }
        private ISet <MultiKey <EventBean> > MakeEventSet(EventBean theEvent)
        {
            ISet <MultiKey <EventBean> > result = new LinkedHashSet <MultiKey <EventBean> >();

            result.Add(new MultiKey <EventBean>(new EventBean[] { theEvent }));
            return(result);
        }
        private BlockProcessor.TxAction ProcessAccountAbstractionTransaction(
            Block block,
            Transaction currentTx,
            int index,
            BlockReceiptsTracer receiptsTracer,
            ProcessingOptions processingOptions,
            LinkedHashSet <Transaction> transactionsInBlock)
        {
            int snapshot = receiptsTracer.TakeSnapshot();

            BlockProcessor.TxAction action = ProcessTransaction(block, currentTx, index, receiptsTracer, processingOptions, transactionsInBlock, false);
            if (action != BlockProcessor.TxAction.Add)
            {
                return(action);
            }

            string?error = receiptsTracer.LastReceipt.Error;
            bool   transactionSucceeded = string.IsNullOrEmpty(error);

            if (!transactionSucceeded)
            {
                receiptsTracer.Restore(snapshot);
                return(BlockProcessor.TxAction.Skip);
            }

            transactionsInBlock.Add(currentTx);
            _transactionProcessed?.Invoke(this, new TxProcessedEventArgs(index, currentTx, receiptsTracer.TxReceipts[index]));
            return(BlockProcessor.TxAction.Add);
        }
Beispiel #26
0
        public override void Update(
            EventBean[] newData,
            EventBean[] oldData)
        {
            _agentInstanceContext.AuditProvider.View(newData, oldData, _agentInstanceContext, _keepAllViewFactory);
            _agentInstanceContext.InstrumentationProvider.QViewProcessIRStream(_keepAllViewFactory, newData, oldData);

            if (newData != null) {
                foreach (var newEvent in newData) {
                    _indexedEvents.Add(newEvent);
                    InternalHandleAdded(newEvent);
                }
            }

            if (oldData != null) {
                foreach (var anOldData in oldData) {
                    _indexedEvents.Remove(anOldData);
                    InternalHandleRemoved(anOldData);
                }
            }

            // update event buffer for access by expressions, if any
            _viewUpdatedCollection?.Update(newData, oldData);

            _agentInstanceContext.InstrumentationProvider.QViewIndicate(_keepAllViewFactory, newData, oldData);
            child.Update(newData, oldData);
            _agentInstanceContext.InstrumentationProvider.AViewIndicate();

            _agentInstanceContext.InstrumentationProvider.AViewProcessIRStream();
        }
Beispiel #27
0
        /// <summary>Validate the variant stream definition. </summary>
        /// <param name="variantStreamname">the stream name</param>
        /// <param name="variantStreamConfig">the configuration information</param>
        /// <param name="eventAdapterService">the event adapters</param>
        /// <returns>specification for variant streams</returns>
        public static VariantSpec ValidateVariantStream(String variantStreamname, ConfigurationVariantStream variantStreamConfig, EventAdapterService eventAdapterService)
        {
            if (variantStreamConfig.TypeVariance == TypeVarianceEnum.PREDEFINED)
            {
                if (variantStreamConfig.VariantTypeNames.IsEmpty())
                {
                    throw new ConfigurationException("Invalid variant stream configuration, no event type name has been added and default type variance requires at least one type, for name '" + variantStreamname + "'");
                }
            }

            ICollection <EventType> types = new LinkedHashSet <EventType>();

            foreach (String typeName in variantStreamConfig.VariantTypeNames)
            {
                EventType type = eventAdapterService.GetEventTypeByName(typeName);
                if (type == null)
                {
                    throw new ConfigurationException("Event type by name '" + typeName + "' could not be found for use in variant stream configuration by name '" + variantStreamname + "'");
                }
                types.Add(type);
            }

            EventType[] eventTypes = types.ToArray();
            return(new VariantSpec(variantStreamname, eventTypes, variantStreamConfig.TypeVariance));
        }
Beispiel #28
0
        public void TestEqualityComparer()
        {
            var set = new LinkedHashSet <int>(AlwaysEqualEqualityComparer <int> .Instance);

            Assert.That(set.Add(10), Is.True);
            Assert.That(set.Add(20), Is.False);
            Assert.That(set.Add(30), Is.False);

            Assert.That(set.Count, Is.EqualTo(1));

            Assert.That(set.Remove(40), Is.True);
            Assert.That(set.Remove(50), Is.False);
            Assert.That(set.Remove(10), Is.False);

            Assert.That(set.Count, Is.EqualTo(0));
        }
Beispiel #29
0
        public override void Update(EventBean[] newData, EventBean[] oldData)
        {
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().QViewProcessIRStream(this, _timeBatchViewFactory.ViewName, newData, oldData);
            }

            if (oldData != null)
            {
                for (int i = 0; i < oldData.Length; i++)
                {
                    _currentBatch.Remove(oldData[i]);
                    InternalHandleRemoved(oldData[i]);
                }
            }

            // we don't care about removed data from a prior view
            if ((newData == null) || (newData.Length == 0))
            {
                if (InstrumentationHelper.ENABLED)
                {
                    InstrumentationHelper.Get().AViewProcessIRStream();
                }
                return;
            }

            // If we have an empty window about to be filled for the first time, schedule a callback
            if (_currentBatch.IsEmpty())
            {
                if (_currentReferencePoint == null)
                {
                    _currentReferencePoint = _initialReferencePoint;
                    if (_currentReferencePoint == null)
                    {
                        _currentReferencePoint = _agentInstanceContext.StatementContext.SchedulingService.Time;
                    }
                }

                // Schedule the next callback if there is none currently scheduled
                if (!_isCallbackScheduled)
                {
                    ScheduleCallback();
                    _isCallbackScheduled = true;
                }
            }

            // add data points to the timeWindow
            foreach (EventBean newEvent in newData)
            {
                _currentBatch.Add(newEvent);
            }

            // We do not update child views, since we batch the events.
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().AViewProcessIRStream();
            }
        }
Beispiel #30
0
        public override void Update(
            EventBean[] newData,
            EventBean[] oldData)
        {
            _agentInstanceContext.AuditProvider.View(newData, oldData, _agentInstanceContext, _lengthWindowViewFactory);
            _agentInstanceContext.InstrumentationProvider.QViewProcessIRStream(
                _lengthWindowViewFactory,
                newData,
                oldData);

            EventBean[] expiredArr = null;
            if (oldData != null) {
                foreach (var anOldData in oldData) {
                    _indexedEvents.Remove(anOldData);
                    InternalHandleRemoved(anOldData);
                }

                expiredArr = oldData;
            }

            // add data points to the window
            // we don't care about removed data from a prior view
            if (newData != null) {
                foreach (var newEvent in newData) {
                    _indexedEvents.Add(newEvent);
                    InternalHandleAdded(newEvent);
                }
            }

            // Check for any events that get pushed out of the window
            var expiredCount = _indexedEvents.Count - Size;
            if (expiredCount > 0) {
                expiredArr = new EventBean[expiredCount];
                using (var enumerator = _indexedEvents.GetEnumerator()) {
                    for (var ii = 0; enumerator.MoveNext() && ii < expiredCount; ii++) {
                        expiredArr[ii] = enumerator.Current;
                    }
                }

                foreach (var anExpired in expiredArr) {
                    _indexedEvents.Remove(anExpired);
                    InternalHandleExpired(anExpired);
                }
            }

            // If there are child views, call update method
            if (child != null) {
                _agentInstanceContext.InstrumentationProvider.QViewIndicate(
                    _lengthWindowViewFactory,
                    newData,
                    expiredArr);
                child.Update(newData, expiredArr);
                _agentInstanceContext.InstrumentationProvider.AViewIndicate();
            }

            _agentInstanceContext.InstrumentationProvider.AViewProcessIRStream();
        }
        private IList <int[]> HandleCube(int[][] childIndexes)
        {
            var enumerationSorted = new List <int[]>();
            var size = ChildNodes.Count;
            var e    = new NumberAscCombinationEnumeration(size);

            while (e.MoveNext())
            {
                enumerationSorted.Add(e.Current);
            }


            enumerationSorted.SortInPlace(
                (o1, o2) =>
            {
                int shared = Math.Min(o1.Length, o2.Length);
                for (int i = 0; i < shared; i++)
                {
                    if (o1[i] < o2[i])
                    {
                        return(-1);
                    }
                    if (o1[i] > o2[i])
                    {
                        return(1);
                    }
                }
                if (o1.Length > o2.Length)
                {
                    return(-1);
                }
                if (o1.Length < o2.Length)
                {
                    return(1);
                }
                return(0);
            });

            var rollup = new List <int[]>(enumerationSorted.Count + 1);
            var keys   = new LinkedHashSet <int>();

            foreach (var item in enumerationSorted)
            {
                keys.Clear();
                foreach (int index in item)
                {
                    int[] childIndex = childIndexes[index];
                    foreach (int childIndexItem in childIndex)
                    {
                        keys.Add(childIndexItem);
                    }
                }
                rollup.Add(CollectionUtil.IntArray(keys));
            }
            return(rollup);
        }
		public void ReinsertShouldNotAffectOrdering()
		{
			// Deliberatly add in an order different from the natural ordering.
			var set = new LinkedHashSet<int> { 1, 10, 5 };
			var added = set.Add(1);  // This element should still be first in the list.

			Assert.That(added, Is.False);
			Assert.That(set, Has.Count.EqualTo(3));
			Assert.That(set.ToArray(), Is.EqualTo(new[] { 1, 10, 5 }));
		}
            public HashSet<Action> actions(System.Object state)
            {
                HashSet<Action> actions = new LinkedHashSet<Action>();
                System.String location = state.ToString();

                List<System.String> linkedLocations = map.getLocationsLinkedTo(location);
                foreach (System.String linkLoc in linkedLocations)
                {
                    actions.Add(new MoveToAction(linkLoc));
                }

                return actions;
            }
        /* TODO: looks like the following are function delegates, replace
        public ModelBasedReflexVacuumAgent() {
            super(new ModelBasedReflexAgentProgram() {
                protected override void init() {
                    setState(new DynamicState());
                    setRules(getRuleSet());
                }

                protected DynamicState updateState(DynamicState state,
                        Action anAction, Percept percept, Model model) {

                    VacuumEnvPercept vep = (VacuumEnvPercept) percept;

                    state.setAttribute(ATTRIBUTE_CURRENT_LOCATION, vep
                            .getAgentLocation());
                    state.setAttribute(ATTRIBUTE_CURRENT_STATE, vep
                            .getLocationState());
                    // Keep track of the state of the different locations
                    if (VacuumEnvironment.LOCATION_A == vep.getAgentLocation()) {
                        state.setAttribute(ATTRIBUTE_STATE_LOCATION_A, vep
                                .getLocationState());
                    } else {
                        state.setAttribute(ATTRIBUTE_STATE_LOCATION_B, vep
                                .getLocationState());
                    }
                    return state;
                }
            });
         * */


        //
        // PRIVATE METHODS
        //
        private static HashSet<Rule> getRuleSet()
        {
            // Note: Using a LinkedHashSet so that the iteration order (i.e. implied
            // precedence) of rules can be guaranteed.
            HashSet<Rule> rules = new LinkedHashSet<Rule>();

            rules.Add(new Rule(new ANDCondition(new EQUALCondition(
                    ATTRIBUTE_STATE_LOCATION_A,
                    VacuumEnvironment.LocationState.Clean), new EQUALCondition(
                    ATTRIBUTE_STATE_LOCATION_B,
                    VacuumEnvironment.LocationState.Clean)), NoOpAction.NO_OP));
            rules.Add(new Rule(new EQUALCondition(ATTRIBUTE_CURRENT_STATE,
                    VacuumEnvironment.LocationState.Dirty),
                    VacuumEnvironment.ACTION_SUCK));
            rules.Add(new Rule(new EQUALCondition(ATTRIBUTE_CURRENT_LOCATION,
                    VacuumEnvironment.LOCATION_A),
                    VacuumEnvironment.ACTION_MOVE_RIGHT));
            rules.Add(new Rule(new EQUALCondition(ATTRIBUTE_CURRENT_LOCATION,
                    VacuumEnvironment.LOCATION_B),
                    VacuumEnvironment.ACTION_MOVE_LEFT));

            return rules;
        }
        //
        // PRIVATE METHODS
        //
        private static HashSet<Rule> getRuleSet()
        {
            // Note: Using a LinkedHashSet so that the iteration order (i.e. implied
            // precedence) of rules can be guaranteed.
            HashSet<Rule> rules = new LinkedHashSet<Rule>();

            // Rules based on REFLEX-VACUUM-AGENT:
            // Artificial Intelligence A Modern Approach (3rd Edition): Figure 2.8,
            // page 48.

            rules.Add(new Rule(new EQUALCondition(VacuumEnvPercept.ATTRIBUTE_STATE,
                    VacuumEnvironment.LocationState.Dirty),
                    VacuumEnvironment.ACTION_SUCK));
            rules.Add(new Rule(new EQUALCondition(
                    VacuumEnvPercept.ATTRIBUTE_AGENT_LOCATION,
                    VacuumEnvironment.LOCATION_A),
                    VacuumEnvironment.ACTION_MOVE_RIGHT));
            rules.Add(new Rule(new EQUALCondition(
                    VacuumEnvPercept.ATTRIBUTE_AGENT_LOCATION,
                    VacuumEnvironment.LOCATION_B),
                    VacuumEnvironment.ACTION_MOVE_LEFT));

            return rules;
        }
            public HashSet<Action> actions(Object state)
            {
                NQueensBoard board = (NQueensBoard)state;

                HashSet<Action> actions = new LinkedHashSet<Action>();

                int numQueens = board.getNumberOfQueensOnBoard();
                int boardSize = board.getSize();
                for (int i = 0; i < boardSize; i++)
                {
                    XYLocation newLocation = new XYLocation(numQueens, i);
                    if (!(board.isSquareUnderAttack(newLocation)))
                    {
                        actions.Add(new QueenAction(QueenAction.PLACE_QUEEN,
                                newLocation));
                    }
                }

                return actions;
            }
Beispiel #37
0
		/// <summary>
		/// create a VCF header from a set of header record lines
		/// </summary>
		/// <param name="headerStrings"> a list of strings that represent all the ## and # entries </param>
		/// <returns> a VCFHeader object </returns>
		protected internal virtual VCFHeader parseHeaderFromLines (IList<string> headerStrings, VCFHeaderVersion version)
		{
			this.version = version;
			ISet<VCFHeaderLine> metaData = new LinkedHashSet<VCFHeaderLine> ();
			ISet<string> sampleNames = new LinkedHashSet<string> ();
			int contigCounter = 0;
			// iterate over all the passed in strings
			foreach (string str in headerStrings) {
				if (!str.StartsWith (VCFHeader.METADATA_INDICATOR)) {//presumably the #CHROM POS ID REF ALT QUAL FILTER INFO   etc. line
					string[] strings = str.Substring (1).Split (VCFConstants.FIELD_SEPARATOR_CHAR);
					//check for null last string, grrr...
					if (String.IsNullOrEmpty (strings.Last ())) {
						strings = strings.Take (strings.Length - 1).ToArray ();
					}
					if (strings.Length < VCFHeader.HEADER_FIELDS.Length) {
						throw new VCFParsingError ("There are not enough columns present in the header line: " + str);
					}
					//Verify Arrays
					var misMatchedColumns = Enumerable.Range (0, VCFHeader.HEADER_FIELDS.Length).Where (x => VCFHeader.HEADER_FIELDS [x] != strings [x]).Select (x => strings [x]).ToArray ();
					if (misMatchedColumns.Length > 0) {
						throw new VCFParsingError ("We were not expecting column name '" + misMatchedColumns [0] + " in that position");
					}
					int arrayIndex = VCFHeader.HEADER_FIELDS.Length;//start after verified columns
					bool sawFormatTag = false;
					if (arrayIndex < strings.Length) {
						if (!strings [arrayIndex].Equals ("FORMAT")) {
							throw new VCFParsingError ("we were expecting column name 'FORMAT' but we saw '" + strings [arrayIndex] + "'");
						}
						sawFormatTag = true;
						arrayIndex++;
					}
					while (arrayIndex < strings.Length) {
						sampleNames.Add (strings [arrayIndex++]);
					}
					if (sawFormatTag && sampleNames.Count == 0) {
						throw new VCFParsingError ("The FORMAT field was provided but there is no genotype/sample data");
					}

				} else {
					if (str.StartsWith (VCFConstants.INFO_HEADER_START)) {
						VCFInfoHeaderLine info = new VCFInfoHeaderLine (str.Substring (7), version);
						metaData.Add (info);
					} else if (str.StartsWith (VCFConstants.FILTER_HEADER_START)) {
						VCFFilterHeaderLine filter = new VCFFilterHeaderLine (str.Substring (9), version);
						metaData.Add (filter);
					} else if (str.StartsWith (VCFConstants.FORMAT_HEADER_START)) {
						VCFFormatHeaderLine format = new VCFFormatHeaderLine (str.Substring (9), version);
						metaData.Add (format);
					} else if (str.StartsWith (VCFConstants.CONTIG_HEADER_START)) {
						VCFContigHeaderLine contig = new VCFContigHeaderLine (str.Substring (9), version, VCFConstants.CONTIG_HEADER_START.Substring (2), contigCounter++);
						metaData.Add (contig);
					} else if (str.StartsWith (VCFConstants.ALT_HEADER_START)) {
						//TODO: Consider giving Alt header lines their own class
						VCFSimpleHeaderLine alt = new VCFSimpleHeaderLine (str.Substring (6), version, VCFConstants.ALT_HEADER_START.Substring (2), "ID", "Description");
						metaData.Add (alt);
					} else {
						int equals = str.IndexOf ("=");
						if (equals != -1) {
							metaData.Add (new VCFHeaderLine (str.Substring (2, equals - 2), str.Substring (equals + 1)));
						}
					}
				}
			}
			this.header = new VCFHeader (metaData, sampleNames);
			if (doOnTheFlyModifications) {
				this.header = VCFStandardHeaderLines.repairStandardHeaderLines (this.header);
			}
			return this.header;
		}
Beispiel #38
0
		public void SetDefaults()
		{
			DateTime today = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

			StringSet = new HashSet<string> {"foo", "bar", "baz"};

			StringDateMap = new SortedList();
			StringDateMap.Add("now", DateTime.Now);
			StringDateMap.Add("never", null); // value is persisted since NH-2199
			// according to SQL Server the big bag happened in 1753 ;)
			StringDateMap.Add("big bang", new DateTime(1753, 01, 01));
			//StringDateMap.Add( "millenium", new DateTime( 2000, 01, 01 ) );
			StringArray = StringSet.ToArray();
			StringList = new ArrayList(StringArray);
			IntArray = new int[] {1, 3, 3, 7};
			FooArray = new Foo[0];
			
			Customs = new ArrayList();
			Customs.Add(new String[] {"foo", "bar"});
			Customs.Add(new String[] {"A", "B"});
			Customs.Add(new String[] {"1", "2"});

			FooSet = new HashSet<FooProxy>();
			Components = new FooComponent[]
				{
					new FooComponent("foo", 42, null, null),
					new FooComponent("bar", 88, null, new FooComponent("sub", 69, null, null))
				};
			TimeArray = new DateTime[]
				{
					new DateTime(),
					new DateTime(),
					new DateTime(), // H2.1 has null here, but it's illegal on .NET
					new DateTime(0)
				};

			Count = 667;
			Name = "Bazza";
			TopComponents = new ArrayList();
			TopComponents.Add(new FooComponent("foo", 11, new DateTime[] {today, new DateTime(2123, 1, 1)}, null));
			TopComponents.Add(
				new FooComponent("bar", 22, new DateTime[] {new DateTime(2007, 2, 3), new DateTime(1945, 6, 1)}, null));
			TopComponents.Add(null);
			Bag = new ArrayList();
			Bag.Add("duplicate");
			Bag.Add("duplicate");
			Bag.Add("duplicate");
			Bag.Add("unique");

			Cached = new LinkedHashSet<CompositeElement>();

			CompositeElement ce = new CompositeElement();
			ce.Foo = "foo";
			ce.Bar = "bar";
			CompositeElement ce2 = new CompositeElement();
			ce2.Foo = "fooxxx";
			ce2.Bar = "barxxx";
			Cached.Add(ce);
			Cached.Add(ce2);
			CachedMap = new SortedList();
			CachedMap.Add(this, ce);
		}
        protected void SetUp()
        {
            hs = new LinkedHashSet<Object>();

            for (int i = 0; i < objArray.Length; i++)
            {
                hs.Add(objArray[i]);
            }

            hs.Add(null);
        }
 public HashSet<Action> actions(Object state)
 {
     HashSet<Action> actions = new LinkedHashSet<Action>();
     NQueensBoard board = (NQueensBoard)state;
     for (int i = 0; i < board.getSize(); i++)
         for (int j = 0; j < board.getSize(); j++)
         {
             XYLocation loc = new XYLocation(i, j);
             if (!board.queenExistsAt(loc))
                 actions
                         .Add(new QueenAction(QueenAction.MOVE_QUEEN,
                                 loc));
         }
     return actions;
 }
     public void test_RemoveLjava_lang_Object()
     {
         int size = hs.Size();
         hs.Remove((Object) 98);
         Assert.IsTrue(!hs.Contains(98), "Failed to Remove element");
         Assert.IsTrue(hs.Size() == size - 1, "Failed to decrement set size");
 
         LinkedHashSet<Object> s = new LinkedHashSet<Object>();
         s.Add(null);
         Assert.IsTrue(s.Remove(null), "Cannot handle null");
     }
     public void TestIterator()
     {
         Iterator<Object> i = hs.Iterator();
         int x = 0;
         int j;
         for (j = 0; i.HasNext; j++)
         {
             Object oo = i.Next();
             if (oo != null)
             {
                 int ii = (int) oo;
                 Assert.IsTrue(ii == j, "Incorrect element found");
             }
             else
             {
                 Assert.IsTrue(hs.Contains(oo), "Cannot find null");
             }
             ++x;
         }
         Assert.IsTrue(hs.Size() == x, "Returned iteration of incorrect size");
 
         LinkedHashSet<Object> s = new LinkedHashSet<Object>();
         s.Add(null);
         Assert.IsNull(s.Iterator().Next(), "Cannot handle null");
     }
     public void TestContainsObject()
     {
         Assert.IsTrue(hs.Contains(objArray[90]), "Returned false for valid object");
         Assert.IsTrue(!hs.Contains(new Object()), "Returned true for invalid Object");
 
         LinkedHashSet<Object> s = new LinkedHashSet<Object>();
         s.Add(null);
         Assert.IsTrue(s.Contains(null), "Cannot handle null");
     }