Example #1
0
 static void Main(string[] args)
 {
     var letters = new HashSet<char>("the quick brown fox");
     Console.WriteLine(letters.Contains('t')); // true
     Console.WriteLine(letters.Contains('j')); // false
     foreach (char c in letters)
     {
         Console.Write(c); // the quickbrownfx
     }
     letters.IntersectWith("aeiou");
     foreach (char c in letters)
     {
         Console.Write(c); // euio
     }
     var letters2 = new HashSet<char>("the quick brown fox");
     letters2.ExceptWith("aeiou");
     foreach (char c in letters2)
     {
         Console.Write(c); // th qckbrwnfx
     }
     var letters3 = new HashSet<char>("the quick brown fox");
     letters3.SymmetricExceptWith("the lazy brown fox");
     foreach (char c in letters3)
     {
         Console.Write(c); // quicklazy
     }
 }
Example #2
0
        internal override void OnCycle()
        {
            ad++;
            if (ad == 10)
            {
                if (_currentCustomer == null)
                    _unit.MoveTo(_unit.GetRoom().GetGameMap().getRandomWalkableSquare());
                ad = 0;
            }
            if (_currentCustomer != null && _unit.Coordinate == _currentCustomer.SquareInFront)
            {
                _unit.Chat("Don't drink it all in one go, savour the flavor!", true);
                _currentCustomer = null;
            }

            RoomUnitManager unitManager = _unit.GetRoom().GetRoomUserManager();
            List<Point> area = GetCustomerArea();
            List<int> currentCustomers = new List<int>();

            foreach (Point p in area)
            {
                RoomUser customer = unitManager.GetUnitForSquare(p.X, p.Y) as RoomUser;
                if (customer == null)
                    continue;
                currentCustomers.Add(customer.VirtualID);

                if (!_customers.Contains(customer.VirtualID)) // New customer
                {
                    _customers.Add(customer.VirtualID);
                    _unit.Chat(string.Format("Hello, {0}", customer.Name), true);
                }
            }

            var test = new HashSet<int>(_customers);
            test.SymmetricExceptWith(currentCustomers);
            List<int> toRemove = new List<int>();
            foreach (int customerID in test)
            {
                if (!currentCustomers.Contains(customerID)) // A customer left
                {
                    _customers.Remove(customerID);
                    //toRemove.Add(customerID);
                    _unit.Chat(string.Format("Bye, {0}", unitManager.GetRoomUnitByVirtualId(customerID).Name), true);
                }
            }

            // Remove old customers
            //foreach (int customerID in toRemove)
            //    _customers.Remove(customerID);
        }
Example #3
0
 public void SymmetricExceptWithTest()
 {
     var set=new HashSet<int>();
     var arr = new int[100];
     for (int i = 0; i < 100; i++)
     {
         set.Add(i);
         arr[i] = i + 50;
     }
     set.SymmetricExceptWith(arr);
     Assert.AreEqual(set.Count, 100);
     for (int i = 0,j=100; i < 50 && j<150; i++,j++)
     {
         Assert.IsTrue(set.Contains(i) && set.Contains(j));
     }
 }
Example #4
0
        private void btnHashSet_Click(object sender, EventArgs e)
        {
            clearList();

            var letters = new HashSet<char>("teerapong");
            string result = "";

            foreach (char c in letters) result += c;
            lsvResult.Items.Add(result); result = "";

            lsvResult.Items.Add(letters.Contains('t'));
            lsvResult.Items.Add(letters.Contains('z'));

            letters = new HashSet<char>("teerapong");
            letters.IntersectWith("aeiou");
            foreach (char c in letters) result += c;
            lsvResult.Items.Add(result); result = "";

            letters = new HashSet<char>("teerapong");
            letters.ExceptWith("aeiou");
            foreach (char c in letters) result += c;
            lsvResult.Items.Add(result); result = "";

            letters = new HashSet<char>("teerapong");
            letters.SymmetricExceptWith("teerapongs" );
            foreach (char c in letters) result += c;
            lsvResult.Items.Add(result); result = "";

            HashSet<int> first = new HashSet<int>();
            HashSet<int> second = new HashSet<int>();
            for (var i = 1; i <= 5; i++)
            {
                first.Add(5 * i);
            }
            for (var j = 1; j <= 5; j++)
            {
                second.Add(10 * j);
            }
            lsvResult.Items.Add("The table of 5 is:");
            foreach (var n in first)
            {
                lsvResult.Items.Add(n);
            }
            lsvResult.Items.Add("The table of 10 is:");
            foreach (var n in second)
            {
                lsvResult.Items.Add(n);
            }
        }
Example #5
0
        internal IEnumerable<MemberResult> GetMemberResults(IEnumerable<Namespace> vars, bool intersectMultipleResults = true)
        {
            IList<Namespace> namespaces = new List<Namespace>();
            foreach (var ns in vars) {
                if (ns != null) {
                    namespaces.Add(ns);
                }
            }

            if (namespaces.Count == 1) {
                // optimize for the common case of only a single namespace
                var newMembers = namespaces[0].GetAllMembers(GlobalScope.ShowClr);
                if (newMembers == null || newMembers.Count == 0) {
                    return new MemberResult[0];
                }

                return SingleMemberResult(newMembers);
            }

            Dictionary<string, List<Namespace>> memberDict = null;
            HashSet<string> memberSet = null;
            foreach (Namespace ns in namespaces) {
                if (ProjectState._noneInst   == ns) {
                    continue;
                }

                var newMembers = ns.GetAllMembers(GlobalScope.ShowClr);
                // IntersectMembers(members, memberSet, memberDict);
                if (newMembers == null || newMembers.Count == 0) {
                    continue;
                }

                if (memberSet == null) {
                    // first namespace, add everything
                    memberSet = new HashSet<string>(newMembers.Keys);
                    memberDict = new Dictionary<string, List<Namespace>>();
                    foreach (var kvp in newMembers) {
                        var tmp = new List<Namespace>(kvp.Value);
                        memberDict[kvp.Key] = tmp;
                    }
                } else {
                    // 2nd or nth namespace, union or intersect
                    HashSet<string> toRemove;
                    IEnumerable<string> adding;

                    if (intersectMultipleResults) {
                        adding = new HashSet<string>(newMembers.Keys);
                        // Find the things only in memberSet that we need to remove from memberDict
                        // toRemove = (memberSet ^ adding) & memberSet

                        toRemove = new HashSet<string>(memberSet);
                        toRemove.SymmetricExceptWith(adding);
                        toRemove.IntersectWith(memberSet);

                        // intersect memberSet with what we're adding
                        memberSet.IntersectWith(adding);

                        // we're only adding things they both had
                        adding = memberSet;
                    } else {
                        // we're adding all of newMembers keys
                        adding = newMembers.Keys;
                        toRemove = null;
                    }

                    // update memberDict
                    foreach (var name in adding) {
                        List<Namespace> values;
                        if (!memberDict.TryGetValue(name, out values)) {
                            memberDict[name] = values = new List<Namespace>();
                        }
                        values.AddRange(newMembers[name]);
                    }

                    if (toRemove != null) {
                        foreach (var name in toRemove) {
                            memberDict.Remove(name);
                        }
                    }
                }
            }

            if (memberDict == null) {
                return new MemberResult[0];
            }
            return MemberDictToResultList(memberDict);
        }
        public void CanCreateAndRunFromView(ViewDefinition vd)
        {
            var snapshotManager = Context.MarketDataSnapshotManager;
            using (var proc = snapshotManager.CreateFromViewDefinition(vd.Name))
            {
                proc.Snapshot.Name = TestUtils.GetUniqueName();
                var uid = Context.MarketDataSnapshotMaster.Add(new MarketDataSnapshotDocument(null, proc.Snapshot)).UniqueId;

                try
                {
                    var snapOptions = ExecutionOptions.Snapshot(proc.Snapshot.UniqueId);
                    var withSnapshot = GetFirstResult(snapOptions, vd.Name);

                    var options = ExecutionOptions.SingleCycle;
                    IViewComputationResultModel withoutSnapshot = GetFirstResult(options, vd.Name);

                    var withoutCount = CountResults(withoutSnapshot);
                    var withCount = CountResults(withSnapshot);
                    if (withoutCount != withCount)
                    {
                        var withSpecs = new HashSet<ValueSpecification>(withSnapshot.AllResults.Select(r => r.ComputedValue.Specification));
                        var withoutSpecs = new HashSet<ValueSpecification>(withoutSnapshot.AllResults.Select(r => r.ComputedValue.Specification));
                        withoutSpecs.SymmetricExceptWith(withSpecs);
                        Assert.True(false, string.Format("Running snapshot of {0} only had {1}, live had {2}", vd.Name, withCount, withoutCount));
                    }

                    Assert.Equal(withoutCount, withCount);
                }
                finally
                {
                    Context.MarketDataSnapshotMaster.Remove(uid);
                }
            }
        }
Example #7
0
        internal IEnumerable<MemberResult> GetMemberResults(
            IEnumerable<AnalysisValue> vars,
            InterpreterScope scope,
            GetMemberOptions options
            )
        {
            IList<AnalysisValue> namespaces = new List<AnalysisValue>();
            foreach (var ns in vars) {
                if (ns != null) {
                    namespaces.Add(ns);
                }
            }

            if (namespaces.Count == 1) {
                // optimize for the common case of only a single namespace
                var newMembers = namespaces[0].GetAllMembers(GlobalScope.InterpreterContext, options);
                if (newMembers == null || newMembers.Count == 0) {
                    return new MemberResult[0];
                }

                return SingleMemberResult(GetPrivatePrefix(scope), options, newMembers);
            }

            Dictionary<string, IEnumerable<AnalysisValue>> memberDict = null;
            Dictionary<string, IEnumerable<AnalysisValue>> ownerDict = null;
            HashSet<string> memberSet = null;
            int namespacesCount = namespaces.Count;
            foreach (AnalysisValue ns in namespaces) {
                if (ProjectState._noneInst == ns) {
                    namespacesCount -= 1;
                    continue;
                }

                var newMembers = ns.GetAllMembers(GlobalScope.InterpreterContext, options);
                // IntersectMembers(members, memberSet, memberDict);
                if (newMembers == null || newMembers.Count == 0) {
                    continue;
                }

                if (memberSet == null) {
                    // first namespace, add everything
                    memberSet = new HashSet<string>(newMembers.Keys);
                    memberDict = new Dictionary<string, IEnumerable<AnalysisValue>>();
                    ownerDict = new Dictionary<string, IEnumerable<AnalysisValue>>();
                    foreach (var kvp in newMembers) {
                        var tmp = new List<AnalysisValue>(kvp.Value);
                        memberDict[kvp.Key] = tmp;
                        ownerDict[kvp.Key] = new List<AnalysisValue> { ns };
                    }
                } else {
                    // 2nd or nth namespace, union or intersect
                    HashSet<string> toRemove;
                    IEnumerable<string> adding;

                    if (options.Intersect()) {
                        adding = new HashSet<string>(newMembers.Keys);
                        // Find the things only in memberSet that we need to remove from memberDict
                        // toRemove = (memberSet ^ adding) & memberSet

                        toRemove = new HashSet<string>(memberSet);
                        toRemove.SymmetricExceptWith(adding);
                        toRemove.IntersectWith(memberSet);

                        // intersect memberSet with what we're adding
                        memberSet.IntersectWith(adding);

                        // we're only adding things they both had
                        adding = memberSet;
                    } else {
                        // we're adding all of newMembers keys
                        adding = newMembers.Keys;
                        toRemove = null;
                    }

                    // update memberDict
                    foreach (var name in adding) {
                        IEnumerable<AnalysisValue> values;
                        List<AnalysisValue> valueList;
                        if (!memberDict.TryGetValue(name, out values)) {
                            memberDict[name] = values = new List<AnalysisValue>();
                        }
                        if ((valueList = values as List<AnalysisValue>) == null) {
                            memberDict[name] = valueList = new List<AnalysisValue>(values);
                        }
                        valueList.AddRange(newMembers[name]);

                        if (!ownerDict.TryGetValue(name, out values)) {
                            ownerDict[name] = values = new List<AnalysisValue>();
                        }
                        if ((valueList = values as List<AnalysisValue>) == null) {
                            ownerDict[name] = valueList = new List<AnalysisValue>(values);
                        }
                        valueList.Add(ns);
                    }

                    if (toRemove != null) {
                        foreach (var name in toRemove) {
                            memberDict.Remove(name);
                            ownerDict.Remove(name);
                        }
                    }
                }
            }

            if (memberDict == null) {
                return new MemberResult[0];
            }
            if (options.Intersect()) {
                // No need for this information if we're only showing the
                // intersection. Setting it to null saves lookups later.
                ownerDict = null;
            }
            return MemberDictToResultList(GetPrivatePrefix(scope), options, memberDict, ownerDict, namespacesCount);
        }
    public override System.Collections.IEnumerator Execute(UTContext context)
    {
        var theFirstListProperty = firstListProperty.EvaluateIn (context);
        if (string.IsNullOrEmpty (theFirstListProperty)) {
            throw new UTFailBuildException ("You must specify the property holding the first list.", this);
        }

        var theSecondListProperty = secondListProperty.EvaluateIn (context);
        if (string.IsNullOrEmpty (theFirstListProperty)) {
            throw new UTFailBuildException ("You must specify the property holding the second list.", this);
        }

        var theOutputProperty = outputProperty.EvaluateIn (context);
        if (string.IsNullOrEmpty (theFirstListProperty)) {
            throw new UTFailBuildException ("You must specify the output property.", this);
        }

        var firstEnumerable = context [theFirstListProperty];
        if (!(firstEnumerable is IEnumerable)) {
            if (firstEnumerable == null) {
                throw new UTFailBuildException ("Property '" + theFirstListProperty + "' has a null value. Cannot combine this.", this);
            }
            throw new UTFailBuildException ("Property '" + theFirstListProperty + "' is of type '" + firstEnumerable.GetType () + "'. Cannot combine this.", this);
        }

        var secondEnumerable = context [theSecondListProperty];
        if (!(secondEnumerable is IEnumerable)) {
            if (secondEnumerable == null) {
                throw new UTFailBuildException ("Property '" + theSecondListProperty + "' has a null value. Cannot combine this.", this);
            }
            throw new UTFailBuildException ("Property '" + theSecondListProperty + "' is of type '" + secondEnumerable.GetType () + "'. Cannot combine this.", this);
        }

        var firstListAsSet = new HashSet<object> ();
        foreach (var obj in (IEnumerable)firstEnumerable) {
            firstListAsSet.Add (obj);
        }

        var secondListAsSet = new HashSet<object> ();
        foreach (var obj in (IEnumerable)secondEnumerable) {
            secondListAsSet.Add (obj);
        }

        var theListOperationType = listOperationType.EvaluateIn (context);
        switch (theListOperationType) {
        case UTCombineListOperation.Union:
            firstListAsSet.UnionWith (secondListAsSet);
            break;
        case UTCombineListOperation.Intersect:
            firstListAsSet.IntersectWith (secondListAsSet);
            break;
        case UTCombineListOperation.Subtract:
            firstListAsSet.ExceptWith (secondListAsSet);
            break;
        case UTCombineListOperation.ExclusiveOr:
            firstListAsSet.SymmetricExceptWith (secondListAsSet);
            break;
        }

        context [theOutputProperty] = firstListAsSet;

        yield return "";
    }
Example #9
0
    static void Main(string[] args)
    {
      Console.WriteLine("Combining two collections with no duplicates:");
      List<string> colors = new List<string> { "red", "orange", "yellow" };
      string[] moreColors = { "orange", "yellow", "green", "blue", "violet" };
      // Want to combine but without any duplicates.
      // Following is just the first stage ...
      HashSet<string> combined = new HashSet<string>(colors);
      // ... now for the second stage.
      // UnionWith() collects items in both lists that aren't duplicated,
      // resulting in a combined collection whose members are all unique.
      combined.UnionWith(moreColors);
      foreach (string color in combined)
      {
        Console.WriteLine(color);
      }
      Console.WriteLine("\nConverting the combined set to a list:");
      // Initialize a new List from combined.
      List<string> spectrum = new List<string>(combined);
      foreach(string color in spectrum)
      {
        Console.WriteLine("{0}", color);
      }

      Console.WriteLine("\nFinding the overlap in two lists:");
      List<string> presidentialCandidates = 
        new List<string> { "Clinton", "Edwards", "Giuliani", 
          "McCain", "Obama", "Romney" };
      List<string> senators = new List<string> { "Alexander", "Boxer", 
        "Clinton", "McCain", "Obama", "Snowe" };
      // Following set hasn't yet weeded out non-Senators ...
      HashSet<string> senatorsRunning = 
        new HashSet<string>(presidentialCandidates);
      // ... but IntersectWith() collects items that appear only in both lists,
      // effectively eliminating the non-Senators.
      senatorsRunning.IntersectWith(senators);
      foreach (string senator in senatorsRunning)
      {
        Console.WriteLine(senator);
      }

      Console.WriteLine("\nExcluding items from a list:");
      // Initialize a Queue from an array.
      Queue<int> queue = 
        new Queue<int>(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 17 });
      // Create a set containing small prime numbers. This is stage 1 of 2.
      HashSet<int> unique = 
        new HashSet<int> { 1, 3, 5, 7, 9, 11, 13, 15 };
      // ExceptWith() removes any items in remainder that are 
      // also in queue: 1, 3, 5, 7,
      // leaving remainder with 9, 11, 13, 15. Stage 2 of 2.
      unique.ExceptWith(queue);
      foreach (int n in unique)
      {
        Console.WriteLine(n.ToString());
      }

      Console.WriteLine("\nFinding just the non-overlapping items in two lists:");
      Stack<int> stackOne = new Stack<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8 });
      Stack<int> stackTwo = new Stack<int>(new int[] { 2, 4, 6, 7, 8, 10, 12 });
      HashSet<int> nonoverlapping = new HashSet<int>(stackOne);
      // SymmetricExceptWith() collects items that are in one collection but not
      // the other: the items that don't overlap.
      nonoverlapping.SymmetricExceptWith(stackTwo);
      foreach(int n in nonoverlapping)
      {
        Console.WriteLine(n.ToString());
      }

      Console.WriteLine("Press Enter to terminate...");
      Console.Read();
    }
Example #10
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Selections the changed.
		/// </summary>
		/// <param name="prootb">The prootb.</param>
		/// <param name="sel">The sel.</param>
		/// ------------------------------------------------------------------------------------
		protected override void HandleSelectionChange(IVwRootBox prootb, IVwSelection sel)
		{
			CheckDisposed();

			if (m_fInChangeSelectedObjects)
				return;
			m_fInChangeSelectedObjects = true;
			try
			{
				int cvsli = 0;

				// Out variables for AllTextSelInfo.
				int ihvoRoot = 0;
				int tagTextProp = 0;
				int cpropPrevious = 0;
				int ichAnchor = 0;
				int ichEnd = 0;
				int ws = 0;
				bool fAssocPrev = false;
				int ihvoEnd = 0;
				ITsTextProps ttpBogus = null;
				SelLevInfo[] rgvsli = new SelLevInfo[0];

				List<int> newSelectedObjects = new List<int>(4);
				newSelectedObjects.Add(XmlVc.FocusHvo);
				if (sel != null)
				{
					cvsli = sel.CLevels(false) - 1;
					// Main array of information retrived from sel that made combo.
					rgvsli = SelLevInfo.AllTextSelInfo(sel, cvsli,
						out ihvoRoot, out tagTextProp, out cpropPrevious, out ichAnchor, out ichEnd,
						out ws, out fAssocPrev, out ihvoEnd, out ttpBogus);
					for (int i = 0; i < cvsli; i++)
					{
						newSelectedObjects.Add(rgvsli[i].hvo);
					}
				}
				var changed = new HashSet<int>(m_xmlVc.SelectedObjects);
				changed.SymmetricExceptWith(newSelectedObjects);
				if (changed.Count != 0)
				{
					m_xmlVc.SelectedObjects = newSelectedObjects;
					// Generate propChanged calls that force the relevant parts of the view to redraw
					// to indicate which command icons should be visible.
					foreach (int hvo in changed)
						m_rootb.PropChanged(hvo, XmlVc.IsObjectSelectedTag, 0, 1, 1);
					if (sel != null && !sel.IsValid)
					{
						// we wiped it out by regenerating parts of the display in our PropChanged calls! Restore it if we can.
						sel = m_rootb.MakeTextSelection(ihvoRoot, cvsli, rgvsli, tagTextProp,
							cpropPrevious, ichAnchor, ichEnd, ws, fAssocPrev, ihvoEnd, ttpBogus, true);
					}
				}
			}

			finally
			{
				m_fInChangeSelectedObjects = false;
			}
			base.HandleSelectionChange(prootb, sel);
		}
Example #11
0
 public void AppendDifferential(Differential differential, DocumentState originatingState)
 {
     var contextChangeIndices = new HashSet<int>(_activeDifferentialIndices);
     contextChangeIndices.SymmetricExceptWith(originatingState.ActiveDifferentialIndices);
 }
        public void BuildersAreSymmetric(TypeDefinition type)
        {
            if (type.Name == "ValuePropertiesBuilder")
            {
                //This builder is too clever for its own good
                return;
            }
            if (type.BaseType != null && type.BaseType.Name.StartsWith("BuilderBase"))
            {
                var methods = type.Methods.Cast<MethodDefinition>();
                Assert.NotEmpty(methods);

                var serialize = methods.SingleOrDefault(m => m.Name == "SerializeImpl");
                var deserialize = methods.SingleOrDefault(m => m.Name == "DeserializeImpl");
                Assert.NotNull(deserialize);
                if (IsUseful(deserialize) && IsUseful(serialize))
                {
                    var deserializeStrings = new HashSet<string>(GetStaticStrings(deserialize));
                    var serializeStrings = new HashSet<string>(GetStaticStrings(serialize));
                    if (! deserializeStrings.SetEquals(serializeStrings))
                    {
                        deserializeStrings.SymmetricExceptWith(serializeStrings);
                        throw new Exception(string.Format("Mismatched strings: {0}", string.Join(",", deserializeStrings)));
                    }
                }
            }
        }
Example #13
0
        static void Main(string[] args)
        {
            var set=new MySet.HashSet<int>();
            var micrset=new HashSet<int>();

            var watch = new Stopwatch();
            var rnd = new Random();

            watch.Start();
            for (int i = 0; i < 100000; i++)
            {
                set.Add(rnd.Next(0, 100000));
            }

            watch.Stop();
            Console.WriteLine(watch.Elapsed);
            watch.Reset();

            watch.Start();
            for (int i = 0; i < 100000; i++)
            {
                micrset.Add(rnd.Next(50000, 150000));
            }
            watch.Stop();
            Console.WriteLine(watch.Elapsed);

            watch.Reset();
            watch.Start();
               micrset.SymmetricExceptWith(set);
            watch.Stop();
            Console.WriteLine("\n\n"+watch.Elapsed+"\n\n");
            watch.Reset();
            var words = GetWords();

            watch.Restart();
            var my = GetTable(words);
            watch.Stop();
            Console.WriteLine(watch.Elapsed);

            watch.Restart();

            var notmy = GetDictionary(words);
            watch.Stop();
            Console.WriteLine(watch.Elapsed);

            Console.WriteLine();
            var notnot=new HashSet<int>();
            Console.ReadKey();
        }
Example #14
0
        public void SymmetricExceptWith()
        {
            var set = new HashSet<int>();

              Assert.That(() => set.SymmetricExceptWith(null), Throws.TypeOf(typeof(ArgumentNullException)));

              set.SymmetricExceptWith(new[] { 3, 9, 11 });
              Assert.IsTrue(set.SetEquals(new[] { 3, 9, 11 }));

              set.SymmetricExceptWith(Enumerable.Range(0, 10));
              Assert.IsTrue(set.SetEquals(new[] { 0, 1, 2, 4, 5, 6, 7, 8, 11 }));

              set.SymmetricExceptWith(set);
              Assert.IsTrue(set.SetEquals(new int[0]));
        }
        public void CanCombineSnapshots()
        {
            ViewDefinition vd = Context.ViewProcessor.ViewDefinitionRepository.GetViewDefinition(@"Demo Equity Option Test View");
            var snapshotManager = Context.MarketDataSnapshotManager;
            Tuple<ManageableMarketDataSnapshot, ManageableMarketDataSnapshot> snaps;
            using (var proc = snapshotManager.CreateFromViewDefinition(vd.Name))
            {
                var snapshot = proc.Snapshot;
                snaps = Halve(snapshot);

                snaps.Item1.Name = TestUtils.GetUniqueName();
                snaps.Item2.Name = TestUtils.GetUniqueName();

                Context.MarketDataSnapshotMaster.Add(new MarketDataSnapshotDocument(null, snaps.Item1));
                Context.MarketDataSnapshotMaster.Add(new MarketDataSnapshotDocument(null, snaps.Item2));
            }

            try
            {
                var snapOptions = ExecutionOptions.GetSingleCycle(new CombinedMarketDataSpecification(new UserMarketDataSpecification(snaps.Item2.UniqueId), new UserMarketDataSpecification(snaps.Item1.UniqueId)));
                var withSnapshot = GetFirstResult(snapOptions, vd.Name);

                var options = ExecutionOptions.SingleCycle;
                IViewComputationResultModel withoutSnapshot = GetFirstResult(options, vd.Name);

                var withoutCount = CountResults(withoutSnapshot);
                var withCount = CountResults(withSnapshot);
                if (withoutCount != withCount)
                {
                    var withSpecs = new HashSet<ValueSpecification>(withSnapshot.AllResults.Select(r => r.ComputedValue.Specification));
                    var withoutSpecs = new HashSet<ValueSpecification>(withoutSnapshot.AllResults.Select(r => r.ComputedValue.Specification));
                    withoutSpecs.SymmetricExceptWith(withSpecs);
                    Assert.True(false, string.Format("Running snapshot of {0} only had {1}, live had {2}", vd.Name, withCount, withoutCount));
                }

                Assert.Equal(withoutCount, withCount);
            }
            finally
            {
                Context.MarketDataSnapshotMaster.Remove(snaps.Item1.UniqueId);
                Context.MarketDataSnapshotMaster.Remove(snaps.Item2.UniqueId);
            }
        }
Example #16
0
        internal override void CheckSyntax()
        {
            if (GroupByClause != null)
            {
                if (!Columns.Aggregates.Any())
                    throw new SqlException("At least one aggregate function must be present along with a GROUP BY clause.\n");

                var groupByKeys = GroupByClause.GroupByItems.Select(g => g.Id.LookupId);
                var nonAggregateSelectKeys = Columns.ColumnSources.Where(c => !(c is AggregateNode)).Select(c => c.Id.LookupId);

                var difference = new HashSet<string>(groupByKeys, StringComparer.OrdinalIgnoreCase);
                difference.SymmetricExceptWith(nonAggregateSelectKeys);
                if (difference.Count > 0)
                    throw new SqlException(string.Format("The query contains the field '{0}' that is not matched between the select list and group by clause.", difference.First()));
            }
            else if (Columns.Aggregates.Any() && !Columns.IsAggregateOnlyQuery)
                throw new SqlException("Your query contains fields and aggregates but no GROUP BY clause.\n");

            if ((Columns.Distinct || GroupByClause != null) && OrderByClause != null)
            {
                var selectFields = Columns.FieldList;
                foreach (OrderByItem item in OrderByClause.OrderByItems)
                {
                    if (!selectFields.Contains(item.Id.LookupId, StringComparer.OrdinalIgnoreCase))
                        throw new SqlException(string.Format("The query specifies DISTINCT or GROUP BY but contains an ORDER BY field '{0}' that is not included in the result list.", item.Id.LookupId));
                }
            }

            base.CheckSyntax();
        }
Example #17
0
 private void RemoveCachedRoutesForChangedSubscriptions(IEnumerable<Subscription> subscriptions)
 {
     _routes.Keys.ToList().Each(type =>
     {
         // This list of subscriptions is generally pretty small (less than 100),
         // so multiple enumerations over the collection shouldn't be a big deal.
         var existingSubscriptions = _subscriptions.Where(x => x.Matches(type));
         var newSubscriptions = subscriptions.Where(x => x.Matches(type));
         var differences = new HashSet<Subscription>(existingSubscriptions);
         differences.SymmetricExceptWith(newSubscriptions);
         if (differences.Any())
         {
             _routes.Remove(type);
         }
     });
 }
Example #18
0
        public void simulate(int n, int T)
        {
            HashSet<string> first = new HashSet<string>();
            HashSet<string> second = new HashSet<string>();
            for (int multiply = 1; multiply <= 10; multiply *= 10)
            {
                HashSet<string> found = new HashSet<string>();
                for (int t = 0; t < T * multiply; t++)
                {
                    List<List<int>> towers = new List<List<int>>();
                    int numTowers = 0;
                    int howManyTowers = rand.Next(1, ((n + 1) * n) / 2 + 1);
                    for (int i = 0; i < n; i++)
                    {
                        if (howManyTowers >= n - i)
                        {
                            howManyTowers -= (n - i);
                            towers.Add(new List<int>() { 1 });
                            numTowers++;
                        }
                    }

                    double[] prob = new double[numTowers];
                    double sum = 0;
                    for (int i = 0; i < numTowers; i++)
                    {
                        prob[i] = rand.NextDouble();
                        if (i == 0) prob[i] = 1 - prob[i] * prob[i];
                        sum += prob[i];
                    }
                    for (int i = 0; i < numTowers; i++)
                    {
                        prob[i] /= sum;
                    }

                    for (int i = 0; i < n - numTowers; i++)
                    {
                        double towerToChangeRandom = rand.NextDouble();
                        List<int> towerToChange = towers[0];
                        for (int j = 0; j < numTowers; j++)
                        {
                            if (towerToChangeRandom < prob[j])
                            {
                                towerToChange = towers[j];
                                break;
                            }
                            towerToChangeRandom -= prob[j];
                        }
                        if (towerToChange[towerToChange.Count - 1] == 2 || rand.Next(0, 5) <= 2)
                        {
                            towerToChange.Add(1);
                        }
                        else
                        {
                            towerToChange[towerToChange.Count - 1] = 2;
                        }
                    }
                    found.Add(canonical(towers));
                }
                int total = found.Count;
                printHashSet(found, total);
                if (multiply == 1)
                {
                    first.UnionWith(found);
                }
                else
                {
                    second.UnionWith(found);
                }
            }
            second.SymmetricExceptWith(first);
            printHashSet(second, second.Count);
        }
        static void Main(string[] args)
        {
            var BigCities = new HashSet<string>
            {
                "New York",
                "Manchester",
                "Sheffield",
                "Paris"
            };

            string[] citiesInUK =
            {
                "Sheffield",
                "Ripon",
                "Truro",
                "Manchester"
            };

            //// Generic code to find intersecting values.
            //BigCities.IntersectWith(citiesInUK);

            //foreach (string city in BigCities)
            //{
            //    Console.WriteLine(city);
            //}

            // Linq method
            // The linq method does create a new array.
            var IntersectCities = BigCities.Intersect(citiesInUK);
            foreach (string city in IntersectCities)
            {
                Console.WriteLine(city);
            }

            Console.WriteLine();

            // Union takes elements that are in either set and puts every element out once.
            var UnionCities = BigCities.Union(citiesInUK);
            foreach (string city in UnionCities)
            {
                Console.WriteLine(city);
            }

            Console.WriteLine();

            // Every element that is in the first set, but not in the second set.
            var ExceptCities = BigCities.Except(citiesInUK);
            foreach (string city in ExceptCities)
            {
                Console.WriteLine(city);
            }

            Console.WriteLine();

            // Which elements appear in either one but not in both collections.
            BigCities.SymmetricExceptWith(citiesInUK);
            foreach (string city in BigCities)
            {
                Console.WriteLine(city);
            }
        }
Example #20
0
        /// <summary>
        /// Searches the given directory for plugins.
        /// </summary>
        /// <param name="directory">The directory to search.</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="directory"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="DirectoryNotFoundException">
        ///     Thrown if <paramref name="directory"/> does not exist.
        /// </exception>
        public void SearchDirectory(string directory)
        {
            {
                Lokad.Enforce.Argument(() => directory);
            }

            m_Diagnostics.Log(
                LevelToLog.Info,
                HostConstants.LogPrefix,
                string.Format(
                    CultureInfo.InvariantCulture,
                    Resources.Plugins_LogMessage_Detector_FileScanStarted_WithDirectory,
                    directory));

            IEnumerable<string> files = Enumerable.Empty<string>();
            try
            {
                files = m_FileSystem.Directory.GetFiles(directory, "*.dll", SearchOption.AllDirectories);
            }
            catch (UnauthorizedAccessException e)
            {
                // Something went wrong with the file IO. That probably means we don't have a complete list
                // so we just exit to prevent any issues from occuring.
                m_Diagnostics.Log(
                    LevelToLog.Error,
                    HostConstants.LogPrefix,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        Resources.Plugins_LogMessage_Detector_FileScanFailed_WithDirectoryAndException,
                        directory,
                        e));

                return;
            }
            catch (IOException e)
            {
                // Something went wrong with the file IO. That probably means we don't have a complete list
                // so we just exit to prevent any issues from occuring.
                m_Diagnostics.Log(
                    LevelToLog.Error,
                    HostConstants.LogPrefix,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        Resources.Plugins_LogMessage_Detector_FileScanFailed_WithDirectoryAndException,
                        directory,
                        e));

                return;
            }

            var knownFiles = m_Repository.KnownPluginFiles();

            var changedKnownFiles = knownFiles
                .Where(p => files.Exists(f => string.Equals(p.Path, f, StringComparison.OrdinalIgnoreCase)))
                .Where(p => m_FileSystem.File.GetLastWriteTimeUtc(p.Path) > p.LastWriteTimeUtc)
                .Select(p => p.Path);

            var changedFilePaths = new HashSet<string>(files);
            changedFilePaths.SymmetricExceptWith(knownFiles.Select(p => p.Path));

            var newFiles = changedFilePaths.Where(file => m_FileSystem.File.Exists(file));

            RemoveDeletedPlugins(changedFilePaths);
            StorePlugins(changedKnownFiles.Concat(newFiles));

            m_Diagnostics.Log(
                LevelToLog.Info,
                HostConstants.LogPrefix,
                string.Format(
                    CultureInfo.InvariantCulture,
                    Resources.Plugins_LogMessage_Detector_FileScanCompleted,
                    directory));
        }
        void OnItemSelected(Selection newSelection)
        {
            Fx.Assert(newSelection != null, "newSelection is null");
            IList<ModelItem> newSelectionObjects = newSelection.SelectedObjects as IList<ModelItem>;
            IList<ModelItem> oldSelectionObjects = oldSelection.SelectedObjects as IList<ModelItem>;

            //Call notifyPropertyChanged for IsPrimarySelection attached property.
            if (newSelection.PrimarySelection != null && !newSelection.PrimarySelection.Equals(oldSelection.PrimarySelection))
            {
                isPrimarySelectionProperty.NotifyPropertyChanged(oldSelection.PrimarySelection);
                isPrimarySelectionProperty.NotifyPropertyChanged(newSelection.PrimarySelection);
            }
            else if (newSelection.PrimarySelection == null)
            {
                isPrimarySelectionProperty.NotifyPropertyChanged(oldSelection.PrimarySelection);
            }


            //call NotifyPropertyChanged for IsSelection property on ModelItems that were added or removed from selection.
            HashSet<ModelItem> selectionChangeSet = new HashSet<ModelItem>(oldSelectionObjects);
            selectionChangeSet.SymmetricExceptWith(newSelectionObjects);
            foreach (ModelItem selectionChangeMI in selectionChangeSet)
            {
                isSelectionProperty.NotifyPropertyChanged(selectionChangeMI);
            }
                        
            if (helpService != null)
            {
                if (oldSelection.PrimarySelection != null)
                {         
                    helpService.RemoveContextAttribute(string.Empty, GetF1HelpTypeKeyword(oldSelection.PrimarySelection.ItemType));
                }

                if (newSelection.PrimarySelection != null)
                {
                    helpService.AddContextAttribute(string.Empty, GetF1HelpTypeKeyword(newSelection.PrimarySelection.ItemType), HelpKeywordType.F1Keyword);
                }
            }
            oldSelection = newSelection;
        }
        public void NumberOfResultsIsConsistent(ViewDefinition defn)
        {
            const int cyclesCount = 5;

            using (var remoteViewClient = Context.ViewProcessor.CreateClient())
            using (var mre = new ManualResetEvent(false))
            {
                var cycles = new BlockingCollection<IEngineResourceReference<IViewCycle>>();

                var listener = new EventViewResultListener();
                listener.ProcessCompleted += delegate { mre.Set(); };
                listener.ViewDefinitionCompilationFailed += delegate { mre.Set(); };
                listener.CycleExecutionFailed += delegate { mre.Set(); };

                listener.CycleCompleted += (sender, e) =>
                                               {
                                                   cycles.Add(remoteViewClient.CreateCycleReference(e.FullResult.ViewCycleId));
                                                   remoteViewClient.TriggerCycle();
                                               };

                remoteViewClient.SetResultListener(listener);
                remoteViewClient.SetViewCycleAccessSupported(true);

                var sequence = ArbitraryViewCycleExecutionSequence.Create(Enumerable.Range(0, cyclesCount).Select(i => DateTimeOffset.Now + TimeSpan.FromHours(i)));
                var options = new ExecutionOptions(sequence, ViewExecutionFlags.TriggersEnabled | ViewExecutionFlags.AwaitMarketData, null, new ViewCycleExecutionOptions(default(DateTimeOffset), ExecutionOptions.GetDefaultMarketDataSpec()));

                remoteViewClient.AttachToViewProcess(defn.UniqueID, options);

                TimeSpan timeout = TimeSpan.FromMinutes(5);
                if (! mre.WaitOne(timeout))
                {
                    throw new TimeoutException(string.Format("Failed to get result in {0}", timeout));
                }
                Assert.Equal(cyclesCount, cycles.Count);

                var specs = cycles.Select(GetAllSpecs).ToList();

                var inconsistent = specs.Zip(specs.Skip(1), Tuple.Create).SelectMany(
                    t =>
                        {
                            var diff = new HashSet<Tuple<string, ValueSpecification>>(t.Item1);
                            diff.SymmetricExceptWith(t.Item2);
                            return diff;
                        }).Distinct();
                if (inconsistent.Any())
                {
                    var counts = string.Join(",", specs.Select(c => c.Count.ToString()));
                    var inconsistentStrings = specs.Select(s => string.Join(",", s.Where(x => inconsistent.Contains(x)).Select(x => x.ToString())));
                    string inconsistentString = string.Join(Environment.NewLine, inconsistentStrings);
                    throw new Exception(string.Format("Inconsistent number of results for {0} {1}: {2}", defn.Name, counts, inconsistentString));
                }
            }
        }
Example #23
0
    static void Main()
    {
#if DEBUG
        Console.SetIn(new System.IO.StreamReader("../../input.txt"));
#endif

        var date = DateTime.Now;

        double maxRange = double.Parse(Console.ReadLine());

        decoded = Enumerable.Range(0, int.Parse(Console.ReadLine()))
            .Select(i => Console.ReadLine().Split())
            .ToDictionary(parts => parts[0], parts => int.Parse(parts[1]));

        var coords = Enumerable.Range(0, int.Parse(Console.ReadLine()))
            .Select(i => Console.ReadLine().Split())
            .Select(parts =>
                new Tuple<int, int>(
                    ParseCoordinate(parts[0]),
                    ParseCoordinate(parts[1])
                )
            ).ToArray();

#if DEBUG
        Console.WriteLine(DateTime.Now - date);
#endif

        graph = Enumerable.Range(0, coords.Length)
            .Select(i => new HashSet<int>()).ToArray();

        for (int i = 0; i < graph.Length; i++)
        {
            for (int j = 0; j < graph.Length; j++)
            {
                if (i == j) continue;

                if (Distance(coords[i], coords[j]) <= maxRange)
                {
                    graph[i].Add(j);
                    graph[j].Add(i);
                }
            }
        }

        var remaining = new HashSet<int>(Enumerable.Range(0, graph.Length));

        int groups = 0;
        while (remaining.Count != 0)
        {
            int next = remaining.First();

            Dfs(next);

            remaining.SymmetricExceptWith(visited);
            visited.Clear();

            groups++;
        }

        Console.WriteLine(groups);

#if DEBUG
        Console.WriteLine(DateTime.Now - date);
#endif
    }
Example #24
0
	private void DragCheck()
	{
		Camera cam = SceneView.lastActiveSceneView.camera;
		limitFaceDragCheckToSelection = pb_Preferences_Internal.GetBool(pb_Constant.pbDragCheckLimit);

		pbUndo.RecordSelection(selection, "Drag Select");

		switch(selectionMode)
		{
			case SelectMode.Vertex:
			{
				if(!shiftKey && !ctrlKey) ClearFaceSelection();

				// profiler.BeginSample("Drag Select Vertices");
				for(int i = 0; i < selection.Length; i++)
				{
					pb_Object pb = selection[i];
					if(!pb.isSelectable) continue;

					// profiler.BeginSample("Create HashSet");
					HashSet<int> selectedTriangles = new HashSet<int>(pb.SelectedTriangles);
					// profiler.EndSample();

					// selection[i].ToMesh();
					// selection[i].Refresh();
					// Vector3[] normals = selection[i].msh.normals;
					// selection[i].Optimize();
					// Vector3 camDirLocal = -selection[i].transform.InverseTransformDirection(cam.transform.forward);

					for(int n = 0; n < m_uniqueIndices[i].Length; n++)
					{
						Vector3 v = m_verticesInWorldSpace[i][m_uniqueIndices[i][n]];

						// profiler.BeginSample("Contains");
						bool contains = selectionRect.Contains(HandleUtility.WorldToGUIPoint(v));
						// profiler.EndSample();
						
						if(contains)
						{
							// if point is behind the camera, ignore it.
							// profiler.BeginSample("WorldToScreenPoint");
							if(cam.WorldToScreenPoint(v).z < 0)
							{
								// profiler.EndSample();
								continue;
							}
							// profiler.EndSample();


							// profiler.BeginSample("backface culling");
							// Vector3 nrm = normals[m_uniqueIndices[i][n]];
							// float dot = Vector3.Dot(camDirLocal, nrm);
							// if(!pref_backfaceSelect && (dot < 0 || pb_HandleUtility.PointIsOccluded(cam, selection[i], v)))
							if( !pref_backfaceSelect && pb_HandleUtility.PointIsOccluded(cam, selection[i], v) )	
							{
								// profiler.EndSample();
								continue;
							}
							// profiler.EndSample();

							// Check if index is already selected, and if not add it to the pot
							// profiler.BeginSample("selected triangles contains");
							contains = selectedTriangles.Contains(m_uniqueIndices[i][n]);
							// profiler.EndSample();

							// profiler.BeginSample("add / remove");
							if( contains )
								selectedTriangles.Remove(m_uniqueIndices[i][n]);
							else
								selectedTriangles.Add(m_uniqueIndices[i][n]);
							// profiler.EndSample();
						}
					}
					
					// profiler.BeginSample("SetSelectedTriangles");
					pb.SetSelectedTriangles(selectedTriangles.ToArray());
					// profiler.EndSample();
				}
				// profiler.EndSample();

				if(!vertexSelectionMask)
					DragObjectCheck(true);
                
                UpdateSelection(false);
			}
			break;

			case SelectMode.Face:
			{
				if(!shiftKey && !ctrlKey) ClearFaceSelection();

				pb_Object[] pool = limitFaceDragCheckToSelection ? selection : (pb_Object[])FindObjectsOfType(typeof(pb_Object));

				List<pb_Face> selectedFaces;
				
				for(int i = 0; i < pool.Length; i++)
				{
					pb_Object pb = pool[i];
					selectedFaces = new List<pb_Face>(pb.SelectedFaces);

					if(!pb.isSelectable)
						continue;

					Vector3[] verticesInWorldSpace = m_verticesInWorldSpace[i];
					bool addToSelection = false;

					for(int n = 0; n < pb.faces.Length; n++)
					{
						pb_Face face = pb.faces[n];

						/// face is behind the camera
						if( cam.WorldToScreenPoint(verticesInWorldSpace[face.indices[0]]).z < 0 )//|| (!pref_backfaceSelect && Vector3.Dot(dir, nrm) > 0f))
							continue;

						// only check the first index per quad, and if it checks out, then check every other point
						if(selectionRect.Contains(HandleUtility.WorldToGUIPoint(verticesInWorldSpace[face.indices[0]])))
						{
							bool nope = false;
							for(int q = 1; q < face.distinctIndices.Length; q++)
							{
								if(!selectionRect.Contains(HandleUtility.WorldToGUIPoint(verticesInWorldSpace[face.distinctIndices[q]])))
								{
									nope = true;
									break;
								}
							}

							if(!nope)
							{
								if( pref_backfaceSelect || !pb_HandleUtility.PointIsOccluded(cam, pool[i], pb_Math.Average(pbUtil.ValuesWithIndices(verticesInWorldSpace, face.distinctIndices))) )
								{
									int indx =  selectedFaces.IndexOf(face);
									
									if( indx > -1 ) {
										selectedFaces.RemoveAt(indx);
									} else {
										addToSelection = true;
										selectedFaces.Add(face);
									}
								}
							}
						}
					}

					pb.SetSelectedFaces(selectedFaces.ToArray());
					if(addToSelection)
						AddToSelection(pb.gameObject);
				}

				DragObjectCheck(true);

				UpdateSelection(false);
			}
			break;

			case SelectMode.Edge:
			{
				if(!shiftKey && !ctrlKey) ClearFaceSelection();

				for(int i = 0; i < selection.Length; i++)
				{
					Vector3 v0 = Vector3.zero, v1 = Vector3.zero, cen = Vector3.zero;
					pb_Object pb = selection[i];
					Vector3[] vertices = m_verticesInWorldSpace[i];
					pb_IntArray[] sharedIndices = pb.sharedIndices;
					HashSet<pb_Edge> inSelection = new HashSet<pb_Edge>();

					for(int n = 0; n < m_universalEdges[i].Length; n++)
					{
						v0 = vertices[sharedIndices[m_universalEdges[i][n].x][0]];
						v1 = vertices[sharedIndices[m_universalEdges[i][n].y][0]];

						cen = (v0+v1)*.5f;

						bool behindCam = cam.WorldToScreenPoint(cen).z < 0;

						if( behindCam )
							continue;

						bool rectContains = selectionRect.Contains( HandleUtility.WorldToGUIPoint(cen) );

						if( rectContains )
						{
							bool occluded = !pref_backfaceSelect && pb_HandleUtility.PointIsOccluded(cam, pb, cen);

							if(!occluded)
							{
								inSelection.Add( new pb_Edge(m_universalEdges[i][n]) );
							}
						}
					}

					pb_Edge[] curSelection = pb_Edge.GetUniversalEdges(pb.SelectedEdges, m_sharedIndicesLookup[i]);
					inSelection.SymmetricExceptWith(curSelection);
					pb_Edge[] selected = inSelection.ToArray();

					for(int n = 0; n < selected.Length; n++)
					{
						selected[n].x = sharedIndices[selected[n].x][0];
						selected[n].y = sharedIndices[selected[n].y][0];
					}

					pb.SetSelectedEdges( selected );
				}

				if(!vertexSelectionMask)
				{
					DragObjectCheck(true);
				}
				
				UpdateSelection(false);
			}
			break;

		default:
			DragObjectCheck(false);
			break;
		}

		SceneView.RepaintAll();
	}