public void Except()
        {
            var dict = new Dictionary<int, string>();
            dict.Add(1, "one");
            dict.Add(2, "two");
            dict.Add(3, "three");

            Assert.AreEqual("([1,one],[2,two])", dict.Except(3).Print());
            Assert.AreEqual("([2,two])", dict.Except(1, 3).Print());
            Assert.AreEqual("([1,one],[2,two],[3,three])", dict.Except(57).Print());
        }
        static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPaths)
        {
            string[] created = importedAssets.Except (Watcher.allAssets).ToArray ();
            string[] modified = importedAssets.Except (created).ToArray ();

            Dictionary<string, string> allMoved = new Dictionary<string, string> ();
            for (int i = 0; i < movedAssets.Length; i++) {
                allMoved.Add (movedAssets [i], movedFromPaths [i]);
            }

            // Renamed to, renamed from
            Dictionary<string, string> renamed =
                (from m in allMoved
                 where (Path.GetDirectoryName (m.Key)) == (Path.GetDirectoryName (m.Value))
                 select m).ToDictionary (p => p.Key, p => p.Value);

            Dictionary<string, string> moved = allMoved.Except (renamed).ToDictionary (p => p.Key, p => p.Value);

            // Dispatch asset events to available watchers
            foreach (Watcher w in Watcher.allWatchers) {
                w.InvokeEventForPaths (created, w.onAssetCreated);
                w.InvokeEventForPaths (deletedAssets, w.onAssetDeleted);
                w.InvokeEventForPaths (modified, w.onAssetModified);
                w.InvokeMovedEventForPaths (renamed, w.onAssetRenamed);
                w.InvokeMovedEventForPaths (moved, w.onAssetMoved);
            }

            // Update asset paths cache
            Watcher.allAssets = AssetDatabase.GetAllAssetPaths ();
        }
Example #3
0
        public void TestMethod2()
        {
            var dictionary = new Dictionary<string, int>();

            WordCounter text = new WordCounter(string.Empty);
            text.Count();
            Assert.IsTrue(!dictionary.Except(text.GetDictionary()).Any(), "Error");
        }
Example #4
0
        public void ExceptNoEqualityComparer_SameKeyInSecondDict_RemovesDuplicateKeyValuePair()
        {
            var first = new Dictionary<int, int> { { 2, 3 }, { 3, 5 } };
            var second = new SortedList<int, int> { { 3, 2 }, { 4, 7 } };

            var expected = 1;
            var actual = first.Except(second).Count;
            Assert.AreEqual(expected, actual);
        }
Example #5
0
        public void ExceptDefaultEqualityComparer_SameKeyDifferentValues_KeepsKeyValuePairWithMatchingKey()
        {
            var first = new Dictionary<int, int> { { 2, 3 }, { 3, 5 } };
            var second = new SortedList<int, int> { { 3, 2 }, { 4, 7 } };

            var expected = 2;
            var actual = first.Except(second, EqualityComparer<KeyValuePair<int, int>>.Default).Count;
            Assert.AreEqual(expected, actual);
        }
Example #6
0
        public Dictionary<string, SqlColumnType> GetFieldTypes(string tablename, Dictionary<string, object> example)
        {
            if (!TableExists(tablename))
                return null;

            var types = _items.First(i => i.Name == tablename).Types;
            var extras = example.Except(types.Keys).SelectVals(v => SqlTypeConversion.GetSqlType(v));
            var res = extras.Union(types);
            return res;
        }
Example #7
0
        public void TestMethod3()
        {
            var dictionary = new Dictionary<string, int>
                              {
                                  { "123", 2 },
                                  { "21312", 1 },
                                  { "2452", 1 }
                              };

            WordCounter text = new WordCounter("21312 2452 123 123!!$$%#$^&$%");
            text.Count();
            Assert.IsTrue(!dictionary.Except(text.GetDictionary()).Any(), "Error");
        }
Example #8
0
        public static void CreateTable(this IDBModifier meta, string tablename, Dictionary<string, object> instance)
        {
            var taxonomyTypes = meta.Taxonomy == null ?
                new Dictionary<string, SqlColumnType>() :
                meta.Taxonomy.GetFieldTypes(tablename, instance);

            taxonomyTypes = taxonomyTypes ?? new Dictionary<string, SqlColumnType>();

            var missingTypes = instance.Except(taxonomyTypes.Keys)
                .SelectVals(v => SqlTypeConversion.GetSqlType(v));

            var fieldTypes = missingTypes.Union(taxonomyTypes);

            meta.CreateTable(tablename, fieldTypes);
        }
Example #9
0
        public override string _getCreateTableSql(string schema, string table, Dictionary<string, SqlColumnType> fieldTypes)
        {
            // Strip off the primary key if it was supplied in fields - we'll make it ourselves
            var datafields = fieldTypes.Except(table + "Id");
            var fieldList = _fieldDefinitions(datafields);

            var sql = String.Format(@"CREATE TABLE `{1}`
            (
                {1}Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
                {2}
            )",
               schema, table, fieldList);

            return sql;
        }
Example #10
0
        public void TestMethod1()
        {
            var dictionary = new Dictionary<string, int>
                              {
                                  { "is", 2 },
                                  { "this", 2 },
                                  { "a", 1 },
                                  { "and", 1 },
                                  { "so", 1 },
                                  { "statement", 1 }
                              };

            WordCounter text = new WordCounter("This is a statement, and so is this.");
            text.Count();
            Assert.IsTrue(!dictionary.Except(text.GetDictionary()).Any(), "Error");
        }
Example #11
0
 private void SplitByRack(Dictionary<int, int> smpPlasmaSlices)
 {
     int totalSliceCnt = smpPlasmaSlices.Count;
     while (smpPlasmaSlices.Any())
     {
         int remaining = smpPlasmaSlices.Count;
         int splitted = totalSliceCnt - remaining;
         var tmpPlasmaSlices = smpPlasmaSlices.Take(Math.Min(remaining, 16)).ToDictionary(x => x.Key, x => x.Value);
         allRackSmpPlasmaSlices.Add(tmpPlasmaSlices);
         var tmpPackageInfos = CreatePackInfo(tmpPlasmaSlices);
         allPackageExpectedInfos.Add(new Dictionary<Point, string>(tmpPackageInfos));
         allPackageScannedInfos.Add(new Dictionary<Point, string>());
         smpPlasmaSlices = smpPlasmaSlices.Except(tmpPlasmaSlices).ToDictionary(x => x.Key, x => x.Value);
     }
     ChangeRackIndex(0);
 }
Example #12
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="schema"></param>
        /// <param name="table"></param>
        /// <param name="fieldTypes">A mapping of the fieldname to .NET type of the fields</param>
        /// <returns></returns>
        public virtual string _getCreateTableSql(string schema, string table, Dictionary<string, SqlColumnType> fieldTypes)
        {
            // Strip off the primary key if it was supplied in fields - we'll make it ourselves
            var datafields = fieldTypes.Except(table + "Id");
            var fieldList = _fieldDefinitions(datafields);

            var sql = String.Format(@"CREATE TABLE [{0}].[{1}]
            (
                {1}Id int NOT NULL IDENTITY (1,1) PRIMARY KEY,
                {2}
            ) ON [PRIMARY]",
               schema, table, fieldList);

            return sql;
        }
        public void GetInternalKeys()
        {
            downloader.Pages["http://myhost:222/api/rules/search?f=internalKey&ps=" + int.MaxValue + "&repositories=fxcop"] = "{\"total\":2,\"p\":1,\"ps\":10,\"rules\":[{\"key\":\"fxcop:My_Own_FxCop_Rule\"},{\"key\":\"fxcop:UriParametersShouldNotBeStrings\",\"internalKey\":\"CA1054\"}]}";
            var expected = new Dictionary<string, string>();
            expected["fxcop:UriParametersShouldNotBeStrings"] = "CA1054";
            var actual = ws.GetInternalKeys("fxcop");

            Assert.AreEqual(true, expected.Count == actual.Count && !expected.Except(actual).Any());
        }
        public void GetProperties()
        {
            // This test includes a regression scenario for SONARMSBRU-187:
            // Requesting properties for project:branch should return branch-specific data

            // Check that properties are correctly defaulted as well as branch-specific
            downloader.Pages["http://myhost:222/api/properties?resource=foo+bar"] = "[{\"key\": \"sonar.property1\",\"value\": \"value1\"},{\"key\": \"sonar.property2\",\"value\": \"value2\"}]";
            downloader.Pages["http://myhost:222/api/properties?resource=foo+bar%3AaBranch"] = "[{\"key\": \"sonar.property1\",\"value\": \"anotherValue1\"},{\"key\": \"sonar.property2\",\"value\": \"anotherValue2\"}]";

            // default
            var expected1 = new Dictionary<string, string>();
            expected1["sonar.property1"] = "value1";
            expected1["sonar.property2"] = "value2";
            expected1["sonar.cs.msbuild.testProjectPattern"] = SonarProperties.DefaultTestProjectPattern;
            var actual1 = ws.GetProperties("foo bar");

            Assert.AreEqual(true, expected1.Count == actual1.Count && !expected1.Except(actual1).Any());

            // branch specific
            var expected2 = new Dictionary<string, string>();
            expected2["sonar.property1"] = "anotherValue1";
            expected2["sonar.property2"] = "anotherValue2";
            expected2["sonar.cs.msbuild.testProjectPattern"] = SonarProperties.DefaultTestProjectPattern;
            var actual2 = ws.GetProperties("foo bar", "aBranch");

            Assert.AreEqual(true, expected2.Count == actual2.Count && !expected2.Except(actual2).Any());
        }
Example #15
0
 public void TC13_VerifyDrainWashStepFunctionality()
 {
     Thread.Sleep(2000);
     if (Page.WasherGroupPage.WasherGroupTableGrid.Rows.Count > 1)
     {
         Thread.Sleep(1000);
         Page.WasherGroupPage.WasherGroupTableGrid.SelectedRows(setWasherType)[0].GetButtonControls()[4].DeskTopMouseClick();
         Page.WasherGroupPage.TabFormula.DeskTopMouseClick();
         Thread.Sleep(1000);
         Page.WasherGroupPage.WasherGroupFormulaTabelGrid.Rows[1].GetButtonControls()[4].DeskTopMouseClick();
         Thread.Sleep(1000);
         if (Page.WasherGroupPage.WashStepsTableGrid.Rows.Count > 1)
         {
             //Verifying the conditions.
             Thread.Sleep(1000);
             for (int k = 1; k <= Page.WasherGroupPage.WashStepsTableGrid.Rows.Count; k++)
             {
                 Thread.Sleep(1000);
                 if (Page.WasherGroupPage.WashStepsTableGrid.Rows[k].GetColumnValues()[2].ToString() == "Drain")
                 {
                     Dictionary<string, string> ActualDrainWashStep = new Dictionary<string, string>();
                     Dictionary<string, string> ExpectedDrainWashStep = new Dictionary<string, string>();
                     ExpectedDrainWashStep.Add("Operations", "Drain");
                     ExpectedDrainWashStep.Add("Run Time (mm:ss)", "02:00");
                     ExpectedDrainWashStep.Add("Temperature (oF)", "1");
                     ExpectedDrainWashStep.Add("Water Level (inches)", "0");
                     //Need to find the list of row values to compare and fail or pass the test case....with this finish...
                     ReadOnlyCollection<string> getValues = Page.WasherGroupPage.WashStepsTableGrid.Rows[k].GetColumnValues();
                     ActualDrainWashStep.Add("Operations", getValues[2]);
                     ActualDrainWashStep.Add("Run Time (mm:ss)", getValues[3]);
                     ActualDrainWashStep.Add("Temperature (oF)", getValues[4]);
                     ActualDrainWashStep.Add("Water Level (inches)", getValues[5]);
                     List<KeyValuePair<string,string>> diffCount = ExpectedDrainWashStep.Except(ActualDrainWashStep).ToList();
                     if(diffCount.Count > 0)
                     {
                         Assert.Fail("Drain Wash Steps are not matching with Expected.Actual - " + diffCount[0]);
                     }
                     break;
                 }
             }
         }
         else
         {
             Assert.Fail("Drain WashStep not found in the gridview: Expected- Drain WashStep to be display while adding new WashStep");
         }
     }
     else
     {
         Assert.Fail("Washer Group data not found in grid page");
     }
 }
		private void LinkRooms(ICollection<ConnectionPoint> _connectionPoints)
		{
			var connectors = new Dictionary<Point, Connector>();

			var rooms = m_mazeBlocks.Values.SelectMany(_mapBlock => _mapBlock.Rooms).ToArray();

			if (rooms.Length == 0) return;

			var forbid = new Dictionary<Point, EDirections>();

			{
				foreach (var room in rooms)
				{
					foreach (var pair in room.WorldRoomRectangle.ForbidBorders)
					{
						EDirections dir;
						if (!forbid.TryGetValue(pair.Key, out dir))
						{
							dir = EDirections.DOWN | EDirections.UP | EDirections.LEFT | EDirections.RIGHT;
						}
						dir &= pair.Value;
						forbid[pair.Key] = dir;
					}
				}
			}

			Action<IEnumerable<ConnectionPoint>> actRemove = delegate(IEnumerable<ConnectionPoint> _points)
			                                                 	{
			                                                 		foreach (var connectionPoint in _points)
			                                                 		{
			                                                 			_connectionPoints.Remove(connectionPoint);
			                                                 		}
			                                                 	};

			if (true)
			{
				#region конечные точки совпадают

				var sameEndPoints = _connectionPoints.GroupBy(_point => _point.End).Where(_points => _points.Count() > 1).ToArray();
				foreach (var grouping in sameEndPoints)
				{
					var points = grouping.ToArray();
					if (points.Length > 2)
					{
						throw new NotImplementedException("Как может сойтись в одной точке более двух комнат????");
					}
					ConnectTwoRooms(points[0].Room, points[1].Room, forbid, connectors, points[0].Begin, points[0].End, points[1].Begin);
					foreach (var point in grouping)
					{
						_connectionPoints.Remove(point);
					}
				}

				#endregion
			}

			if (true)
			{
				#region концевая точка касается другой комнаты

				{
					var toRemove = new List<ConnectionPoint>();

					foreach (var cp in _connectionPoints)
					{
						if (toRemove.Contains(cp)) continue;

						var oppositeDelta = cp.Dir.Opposite().GetDelta();
						foreach (var room in rooms)
						{
							if (room == cp.Room) continue;
							var rrect = room.WorldRoomRectangle;
							var frect = rrect.Inflate(1, 1);
							var end = cp.End;
							if (frect.Contains(end))
							{
								while (rrect.Contains(end))
								{
									end += oppositeDelta;
								}

								if (!frect.AllPointsExceptCorners().Contains(end))
								{
									end += cp.Dir.GetDelta();
								}
								{
									ConnectTwoRooms(room, cp.Room, forbid, connectors, end, cp.Begin);

									toRemove.Add(cp);
									var revert = _connectionPoints.Where(_point => _point.Dir == cp.Dir.Opposite() && _point.Room == room).ToArray();
									toRemove.AddRange(revert);
								}
								//else
								{
									//концевая точка примыкает к углу комнаты
									//toRemove.Add(connectionPoint);
								}
							}
						}
					}
					actRemove(toRemove);
				}

				#endregion
			}

			if (true)
			{
				#region Конечные точки в одном столбце

				{
					var toRemove = new List<ConnectionPoint>();
					var sameCol = _connectionPoints.GroupBy(_point => _point.End.X).Where(_points => _points.Count() > 1).ToArray();
					foreach (var grouping in sameCol)
					{
						var points = grouping.OrderBy(_point => _point.End.Y).ToArray();

						for (var i = 0; i < points.Length - 1; ++i)
						{
							if ((points[i].End - points[i + 1].End).QLenght > MAX_PATH_LEN) continue;
							if (!points[i].End.GetLineToPoints(points[i + 1].End).Any(forbid.ContainsKey))
							{
								ConnectTwoRooms(points[i].Room,
								                points[i + 1].Room,
								                forbid,
								                connectors,
								                points[i].Begin,
								                points[i].End,
								                points[i + 1].End,
								                points[i + 1].Begin);
								toRemove.Add(points[i]);
								toRemove.Add(points[i + 1]);
							}
						}
					}
					actRemove(toRemove.Distinct());
				}

				#endregion
			}

			if (true)
			{
				#region Конечные точки на одной строке

				{
					var toRemove = new List<ConnectionPoint>();
					var sameRow = _connectionPoints.GroupBy(_point => _point.End.Y).Where(_points => _points.Count() > 1).ToArray();
					foreach (var grouping in sameRow)
					{
						var points = grouping.OrderBy(_point => _point.End.X).ToArray();

						for (var i = 0; i < points.Length - 1; ++i)
						{
							if ((points[i].End - points[i + 1].End).QLenght > MAX_PATH_LEN) continue;
							if (!points[i].End.GetLineToPoints(points[i + 1].End).Any(forbid.ContainsKey))
							{
								ConnectTwoRooms(points[i].Room, points[i + 1].Room, forbid, connectors, points[i].Begin, points[i].End, points[i + 1].End, points[i + 1].Begin);
								toRemove.Add(points[i]);
								toRemove.Add(points[i + 1]);
							}
						}
					}
					actRemove(toRemove.Distinct());
				}

				#endregion
			}

			if (true)
			{
				#region можно проложить путь между двумя концами не затрагивая forbid

				var toRemove = new List<ConnectionPoint>();

				foreach (var cp in _connectionPoints)
				{
					if (toRemove.Contains(cp) || forbid.ContainsKey(cp.End)) continue;

					var candidates = _connectionPoints.Where(_point => _point.Room != cp.Room && cp.Dir <= _point.Dir && !_point.Room.ConnectedTo.Contains(cp.Room) && !forbid.ContainsKey(_point.End) && (_point.End - cp.End).QLenght < MAX_PATH_LEN).ToArray();

					foreach (var candidate in candidates)
					{
						if (toRemove.Contains(cp) || toRemove.Contains(candidate)) continue;

						var points = new[] {cp, candidate}; //.OrderBy(_point => _point.Dir).ToArray();

						var minx = cp.End.X < candidate.End.X ? cp : candidate;
						var miny = cp.End.Y < candidate.End.Y ? cp : candidate;
						var maxx = cp.End.X > candidate.End.X ? cp : candidate;
						var maxy = cp.End.Y > candidate.End.Y ? cp : candidate;

						var dx = maxx.End.X - minx.End.X;
						var dy = maxy.End.Y - miny.End.Y;

						var way1 = new List<Point>();
						var way2 = new List<Point>();

						for (var i = 0; i < 20; ++i)
						{
							way1.Clear();
							way2.Clear();
							switch (points[0].Dir)
							{
								case EDirections.UP:
									switch (points[1].Dir)
									{
										case EDirections.UP:
											if (dx >= dy)
											{
												way1.AddRange(new[]
												              	{
												              		minx.Begin, minx.End,
												              		new Point(minx.End.X, miny.End.Y - i),
												              		new Point(maxx.End.X, miny.End.Y - i),
												              		maxx.End, maxx.Begin
												              	});
											}
											else
											{
												way1.AddRange(new[]
												              	{
												              		miny.Begin, miny.End,
												              		new Point(miny.End.X - i, miny.End.Y),
												              		new Point(miny.End.X - i, maxy.End.Y),
												              		maxx.End, maxx.Begin
												              	});
												way2.AddRange(new[]
												              	{
												              		minx.Begin, minx.End,
												              		new Point(miny.End.X + i, miny.End.Y),
												              		new Point(miny.End.X + i, maxy.End.Y),
												              		maxx.End, maxx.Begin
												              	});
											}
											break;
										case EDirections.DOWN:
											if (maxx.End.X - minx.End.X < 2) continue;
											way1.AddRange(new[]
											              	{
											              		miny.Begin, miny.End,
											              		new Point(miny.End.X + i, miny.End.Y),
											              		new Point(miny.End.X + i, maxy.End.Y),
											              		maxy.End, maxy.Begin
											              	});
											way2.AddRange(new[]
											              	{
											              		miny.Begin, miny.End,
											              		new Point(miny.End.X - i, miny.End.Y),
											              		new Point(miny.End.X - i, maxy.End.Y),
											              		maxy.End, maxy.Begin
											              	});
											break;
										case EDirections.LEFT:
											way1.AddRange(new[]
											              	{
											              		minx.Begin, minx.End,
											              		new Point(minx.End.X - i, minx.End.Y),
											              		new Point(minx.End.X - i, maxx.End.Y),
											              		maxx.End, maxx.Begin
											              	});
											way2.AddRange(new[]
											              	{
											              		minx.Begin, minx.End,
											              		new Point(minx.End.X, minx.End.Y - i),
											              		new Point(minx.End.X, maxx.End.Y - i),
											              		maxx.End, maxx.Begin
											              	});
											break;
										case EDirections.RIGHT:
											way1.AddRange(new[]
											              	{
											              		minx.Begin, minx.End,
											              		new Point(minx.End.X + i, minx.End.Y),
											              		new Point(minx.End.X + i, maxx.End.Y),
											              		maxx.End, maxx.Begin
											              	});
											way2.AddRange(new[]
											              	{
											              		minx.Begin, minx.End,
											              		new Point(minx.End.X, minx.End.Y + i),
											              		new Point(minx.End.X, maxx.End.Y + i),
											              		maxx.End, maxx.Begin
											              	});
											break;
										default:
											throw new ArgumentOutOfRangeException();
									}
									break;
								case EDirections.DOWN:
									switch (points[1].Dir)
									{
										case EDirections.DOWN:
											if (dx >= dy)
											{
												way1.AddRange(new[]
												              	{
												              		minx.Begin, minx.End,
												              		new Point(minx.End.X, miny.End.Y + i),
												              		new Point(maxx.End.X, miny.End.Y + i),
												              		maxx.End, maxx.Begin
												              	});
											}
											else
											{
												way1.AddRange(new[]
												              	{
												              		miny.Begin, miny.End,
												              		new Point(miny.End.X - i, miny.End.Y),
												              		new Point(miny.End.X - i, maxy.End.Y),
												              		maxx.End, maxx.Begin
												              	});
												way2.AddRange(new[]
												              	{
												              		minx.Begin, minx.End,
												              		new Point(miny.End.X + i, miny.End.Y),
												              		new Point(miny.End.X + i, maxy.End.Y),
												              		maxx.End, maxx.Begin
												              	});
											}
											break;
										case EDirections.LEFT:
											way1.AddRange(new[]
											              	{
											              		minx.Begin, minx.End,
											              		new Point(minx.End.X, minx.End.Y + i),
											              		new Point(maxx.End.X, minx.End.Y + i),
											              		maxx.End, maxx.Begin
											              	});
											way2.AddRange(new[]
											              	{
											              		minx.Begin, minx.End,
											              		new Point(maxx.End.X - i, minx.End.Y),
											              		new Point(maxx.End.X - i, maxx.End.Y),
											              		maxx.End, maxx.Begin
											              	});
											break;
										case EDirections.RIGHT:
											way1.AddRange(new[]
											              	{
											              		minx.Begin, minx.End,
											              		new Point(minx.End.X + i, minx.End.Y),
											              		new Point(minx.End.X + i, maxx.End.Y),
											              		maxx.End, maxx.Begin
											              	});
											way2.AddRange(new[]
											              	{
											              		minx.Begin, minx.End,
											              		new Point(minx.End.X, minx.End.Y + i),
											              		new Point(minx.End.X, maxx.End.Y + i),
											              		maxx.End, maxx.Begin
											              	});
											break;
										default:
											throw new ArgumentOutOfRangeException();
									}
									break;
								case EDirections.LEFT:
									switch (points[1].Dir)
									{
										case EDirections.LEFT:
											if (maxy.End.Y - miny.End.Y < 2) continue;
											way1.AddRange(new[]
											              	{
											              		miny.Begin, miny.End,
											              		new Point(miny.End.X - i, miny.End.Y),
											              		new Point(miny.End.X - i, maxy.End.Y),
											              		maxy.End, maxy.Begin
											              	});
											break;
										case EDirections.RIGHT:
											if (i > 0) continue;
											way1.AddRange(new[]
											              	{
											              		miny.Begin, miny.End,
											              		new Point(maxy.End.X, miny.End.Y),
											              		maxy.End, maxy.Begin
											              	});
											way2.AddRange(new[]
											              	{
											              		miny.Begin, miny.End,
											              		new Point(miny.End.X, maxy.End.Y),
											              		maxy.End, maxy.Begin
											              	});
											break;
										default:
											throw new ArgumentOutOfRangeException();
									}
									break;
								case EDirections.RIGHT:
									switch (points[1].Dir)
									{
										case EDirections.RIGHT:
											if (maxy.End.Y - miny.End.Y < 2) continue;
											way1.AddRange(new[]
											              	{
											              		miny.Begin, miny.End,
											              		new Point(maxx.End.X + i, miny.End.Y),
											              		new Point(maxx.End.X + i, maxy.End.Y),
											              		maxy.End, maxy.Begin
											              	});
											break;
										default:
											throw new ArgumentOutOfRangeException();
									}
									break;
								default:
									throw new ArgumentOutOfRangeException();
							}
							var flag = false;
							foreach (var way in new[] {way1, way2})
							{
								flag = true;
								if (way.Count == 0) continue;
								var pnt = way[1];

								for (var index = 2; index < way.Count - 1 && flag; ++index)
								{
									flag = !pnt.GetLineToPoints(way[index]).Any(forbid.ContainsKey);
									pnt = way[index];
								}
								if (!flag) continue;
								if (way[0] != cp.Begin) way.Reverse();

								ConnectTwoRooms(cp.Room, candidate.Room, forbid, connectors, way1.ToArray());
								toRemove.Add(candidate);
								break;
							}
							if (flag)
							{
								break;
							}
						}
					}
					if (cp.Room.IsConnected)
					{
						toRemove.Add(cp);
					}
				}

				actRemove(toRemove.Distinct());

				#endregion
			}

			if (true)
			{
				#region остатки ConnectionPoints

				var notConnectedToAny = rooms.Where(_room => !_room.IsConnected).ToList();
				foreach (var room in notConnectedToAny)
				{
					var cps = _connectionPoints.Where(_point => _point.Room == room).ToList();
					if (cps.Count == 0)
					{
						continue;
					}
					foreach (var cp in cps)
					{
						var delta = cp.Dir.GetDelta();
						var point = cp.End;
						var i = 0;
						var flag = false;
						for (; i < 10; ++i)
						{
							point += delta;
							EDirections dir;
							if (forbid.TryGetValue(point, out dir))
							{
								if (!dir.HasFlag(cp.Dir)) break;
							}

							Connector connector;
							if (connectors.TryGetValue(point, out connector))
							{
								ConnectTwoRooms(room, null, forbid, connectors, cp.Begin, cp.End, point);
								flag = true;
								break;
							}
							else
							{
								var rm = rooms.FirstOrDefault(_room => _room.WorldRoomRectangle.Contains(point));
								if (rm != null)
								{
									ConnectTwoRooms(room, rm, forbid, connectors, cp.Begin, cp.End, point - delta);
									flag = true;
									break;
								}
							}
						}
						_connectionPoints.Remove(cp);
						if (flag) break;
					}
				}

				#endregion
			}

			if (true)
			{
				#region финальный этап

				while (true)
				{
					var nConnectors = connectors.Where(_pair => _pair.Value.Rooms.Any(_room => !_room.IsConnected)).ToArray();
					var nKeys = nConnectors.Select(_pair => _pair.Key).ToArray();
					var pConnectors = connectors.Except(nConnectors).ToArray();
					if (nConnectors.Length == 0)
					{
						break;
					}

					var flag = false;
					foreach (var nPair in nConnectors)
					{
						var nPnt = nPair.Key;

						var possible =
							pConnectors.Where(_pair => (_pair.Key.X == nPnt.X || _pair.Key.Y == nPnt.Y)).OrderBy(
								_pair => (_pair.Key - nPnt).QLenght).ToList();
						foreach (var pPair in possible)
						{
							var pPnt = pPair.Key;

							var npDir = Util.GetDirection(nPnt, pPnt);

							flag = true;

							foreach (var point in nPnt.GetLineToPoints(pPnt))
							{
								if (point != nPnt && nKeys.Contains(point))
								{
									flag = false;
									break;
								}

								EDirections dir;
								if (forbid.TryGetValue(point, out dir))
								{
									if (!dir.HasFlag(npDir))
									{
										flag = false;
										break;
									}
								}
							}
							if (flag)
							{
								var nRooms = nPair.Value.Rooms.ToArray();
								foreach (var room in nRooms)
								{
									ConnectTwoRooms(room, null, forbid, connectors, nPnt + npDir.GetDelta(), pPnt);
								}
								break;
							}
						}
						if (flag)
						{
							break;
						}
					}
					if (!flag)
					{
						break;
					}
				}

				#endregion
			}
		}
        public void ServerUrlWithTrailingSlash()
        {
            ws = new SonarWebService(downloader, "http://myhost:222/", new TestLogger());

            downloader.Pages["http://myhost:222/api/profiles/list?language=cs&project=foo+bar"] = "[{\"name\":\"profile1\",\"language\":\"cs\",\"default\":true}]";
            string qualityProfile;
            bool result = ws.TryGetQualityProfile("foo bar", "cs", out qualityProfile);
            Assert.IsTrue(result);
            Assert.AreEqual("profile1", qualityProfile);

            downloader.Pages["http://myhost:222/api/profiles/index?language=cs&name=Sonar+way"] = "[{\"name\":\"Sonar way\",\"language\":\"cs\",\"default\":true}]";
            var expected1 = new List<string>();
            var actual1 = new List<string>(ws.GetActiveRuleKeys("Sonar way", "cs", "foo"));
            Assert.AreEqual(true, expected1.SequenceEqual(actual1));

            downloader.Pages["http://myhost:222/api/rules/search?f=internalKey&ps=" + int.MaxValue + "&repositories=fxcop"] = "{\"total\":2,\"p\":1,\"ps\":10,\"rules\":[{\"key\":\"fxcop:My_Own_FxCop_Rule\"},{\"key\":\"fxcop:UriParametersShouldNotBeStrings\",\"internalKey\":\"CA1054\"}]}";
            var expected2 = new Dictionary<string, string>();
            expected2["fxcop:UriParametersShouldNotBeStrings"] = "CA1054";
            var actual2 = ws.GetInternalKeys("fxcop");

            Assert.AreEqual(true, expected2.Count == actual2.Count && !expected2.Except(actual2).Any());

            downloader.Pages["http://myhost:222/api/properties?resource=foo+bar"] = "[{\"key\": \"sonar.property1\",\"value\": \"value1\"},{\"key\": \"sonar.property2\",\"value\": \"value2\"}]";
            var expected3 = new Dictionary<string, string>();
            expected3["sonar.property1"] = "value1";
            expected3["sonar.property2"] = "value2";
            expected3["sonar.cs.msbuild.testProjectPattern"] = SonarProperties.DefaultTestProjectPattern;
            var actual3 = ws.GetProperties("foo bar");

            Assert.AreEqual(true, expected3.Count == actual3.Count && !expected3.Except(actual3).Any());

            downloader.Pages["http://myhost:222/api/updatecenter/installed_plugins"] = "[{\"key\":\"visualstudio\",\"name\":\"...\",\"version\":\"1.2\"},{\"key\":\"csharp\",\"name\":\"C#\",\"version\":\"4.0\"}]";
            var expected4 = new List<string>();
            expected4.Add("visualstudio");
            expected4.Add("csharp");
            var actual4 = new List<string>(ws.GetInstalledPlugins());

            Assert.AreEqual(true, expected4.SequenceEqual(actual4));
        }
Example #18
0
        public Result BuildModel(Grevit.Types.ComponentCollection components)
        {
            bool delete = false;

            if (components == null)
            {
                // Create new Grevit Client sending existing Families 
                Grevit.Client.ClientWindow grevitClientDialog = new Grevit.Client.ClientWindow(document.GetFamilies());
                //Grevit.Serialization.Client grevitClientDialog = new Grevit.Serialization.Client(document.GetFamilies());

                // Show Client Dialog
                grevitClientDialog.ShowWindow();
                //if (grevitClientDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) return Result.Cancelled;

                // Set the received component collection
                components = grevitClientDialog.componentCollection;

                delete = grevitClientDialog.componentCollection.delete;

                Scale = grevitClientDialog.componentCollection.scale;
            }



            // Set up a List for stalled components (with References)
            List<Component> componentsWithReferences = new List<Component>();

            // Get all existing Grevit Elements from the Document
            // If Update is false this will just be an empty List
            existing_Elements = document.GetExistingGrevitElements(components.update);

            // Set up an empty List for created Elements
            created_Elements = new Dictionary<string, ElementId>();


            #region createComponents

            Transaction trans = new Transaction(GrevitBuildModel.document, "GrevitCreate");
            trans.Start();

            // Walk thru all received components
            foreach (Component component in components.Items)
            {
                // If they are not reference dependent, create them directly
                // Otherwise add the component to a List of stalled elements
                if (!component.stalledForReference)
                    component.Build(false);       
                else
                    componentsWithReferences.Add(component);
            }

            // Walk thru all elements which are stalled because they are depending on
            // an Element which needed to be created first


            foreach (Component component in componentsWithReferences) component.Build(true);

            trans.Commit();
            trans.Dispose();

            #endregion


            // If Delete Setting is activated
            if (delete)
            {
                // Create a new transaction
                Transaction transaction = new Transaction(document, "GrevitDelete");
                transaction.Start();

                // get the Difference between existing and new elements to erase them
                IEnumerable<KeyValuePair<string, ElementId>> unused = 
                    existing_Elements.Except(created_Elements).Concat(created_Elements.Except(existing_Elements));

                // Delete those elements from the document
                foreach (KeyValuePair<string, ElementId> element in unused) document.Delete(element.Value);

                // commit and dispose the transaction
                transaction.Commit();
                transaction.Dispose();
            }



            return Result.Succeeded;
        }
        public void ServerUrlWithTrailingSlash()
        {
            ws = new SonarWebService(downloader, "http://myhost:222/", new TestLogger());

            // Check that profiles are correctly defaulted as well as branch-specific
            // This test includes a regression scenario for SONARMSBRU-187:
            // Requesting properties for project:branch should return branch-specific data
            downloader.Pages["http://myhost:222/api/profiles/list?language=cs&project=foo+bar"] = "[{\"name\":\"profile1\",\"language\":\"cs\",\"default\":true}]";
            downloader.Pages["http://myhost:222/api/profiles/list?language=cs&project=foo+bar%3AaBranch"] = "[{\"name\":\"profile2\",\"language\":\"cs\",\"default\":false}]";
            downloader.Pages["http://myhost:222/api/profiles/list?language=cs&project=foo+bar%3AanotherBranch"] = "[{\"name\":\"profile3\",\"language\":\"cs\",\"default\":false}]";
            string qualityProfile1;
            string qualityProfile2;
            string qualityProfile3;
            bool result1 = ws.TryGetQualityProfile("foo bar", null, "cs", out qualityProfile1);
            bool result2 = ws.TryGetQualityProfile("foo bar", "aBranch", "cs", out qualityProfile2);
            bool result3 = ws.TryGetQualityProfile("foo bar", "anotherBranch", "cs", out qualityProfile3);

            Assert.IsTrue(result1);
            Assert.IsTrue(result2);
            Assert.IsTrue(result3);
            Assert.AreEqual("profile1", qualityProfile1);
            Assert.AreEqual("profile2", qualityProfile2);
            Assert.AreEqual("profile3", qualityProfile3);

            Assert.IsTrue(result1);
            Assert.IsTrue(result2);
            Assert.IsTrue(result3);
            Assert.AreEqual("profile1", qualityProfile1);
            Assert.AreEqual("profile2", qualityProfile2);
            Assert.AreEqual("profile3", qualityProfile3);

            downloader.Pages["http://myhost:222/api/profiles/index?language=cs&name=Sonar+way"] = "[{\"name\":\"Sonar way\",\"language\":\"cs\",\"default\":true}]";
            var expected1 = new List<string>();
            var actual1 = new List<string>(ws.GetActiveRuleKeys("Sonar way", "cs", "foo"));
            Assert.AreEqual(true, expected1.SequenceEqual(actual1));

            downloader.Pages["http://myhost:222/api/rules/search?f=internalKey&ps=" + int.MaxValue + "&repositories=fxcop"] = "{\"total\":2,\"p\":1,\"ps\":10,\"rules\":[{\"key\":\"fxcop:My_Own_FxCop_Rule\"},{\"key\":\"fxcop:UriParametersShouldNotBeStrings\",\"internalKey\":\"CA1054\"}]}";
            var expected2 = new Dictionary<string, string>();
            expected2["fxcop:UriParametersShouldNotBeStrings"] = "CA1054";
            var actual2 = ws.GetInternalKeys("fxcop");

            Assert.AreEqual(true, expected2.Count == actual2.Count && !expected2.Except(actual2).Any());

            downloader.Pages["http://myhost:222/api/properties?resource=foo+bar"] = "[{\"key\": \"sonar.property1\",\"value\": \"value1\"},{\"key\": \"sonar.property2\",\"value\": \"value2\"}]";
            downloader.Pages["http://myhost:222/api/properties?resource=foo+bar%3AaBranch"] = "[{\"key\": \"sonar.property1\",\"value\": \"anotherValue1\"},{\"key\": \"sonar.property2\",\"value\": \"anotherValue2\"}]";

            var expected3_1 = new Dictionary<string, string>();
            expected3_1["sonar.property1"] = "value1";
            expected3_1["sonar.property2"] = "value2";
            expected3_1["sonar.cs.msbuild.testProjectPattern"] = SonarProperties.DefaultTestProjectPattern;
            var actual3_1 = ws.GetProperties("foo bar");

            var expected3_2 = new Dictionary<string, string>();
            expected3_2["sonar.property1"] = "anotherValue1";
            expected3_2["sonar.property2"] = "anotherValue2";
            expected3_2["sonar.cs.msbuild.testProjectPattern"] = SonarProperties.DefaultTestProjectPattern;
            var actual3_2 = ws.GetProperties("foo bar", "aBranch");

            Assert.AreEqual(true, expected3_1.Count == actual3_1.Count && !expected3_1.Except(actual3_1).Any());
            Assert.AreEqual(true, expected3_2.Count == actual3_2.Count && !expected3_2.Except(actual3_2).Any());

            downloader.Pages["http://myhost:222/api/updatecenter/installed_plugins"] = "[{\"key\":\"visualstudio\",\"name\":\"...\",\"version\":\"1.2\"},{\"key\":\"csharp\",\"name\":\"C#\",\"version\":\"4.0\"}]";
            var expected4 = new List<string>();
            expected4.Add("visualstudio");
            expected4.Add("csharp");
            var actual4 = new List<string>(ws.GetInstalledPlugins());

            Assert.AreEqual(true, expected4.SequenceEqual(actual4));
        }
        public void FindFrontContractFindsCorrectContractNMonthsBack()
        {
            List<Instrument> contracts = ContinuousFuturesBrokerTestData.GetVIXFutures().Where(x => x.ID < 6).ToList();

            //return the contracts requested
            _instrumentMgrMock.Setup(x => x
                .FindInstruments(It.IsAny<Expression<Func<Instrument, bool>>>(), It.IsAny<MyDBContext>()))
                .Returns(
                    (Expression<Func<Instrument, bool>> y, MyDBContext a) => contracts.AsQueryable().Where(y).ToList()
                );

            _cfInst.ContinuousFuture.RolloverDays = 1;

            var expectedExpirationMonths = new Dictionary<DateTime, int?>
            {
                { new DateTime(2012, 11,20), 1 },
                { new DateTime(2012, 11,21), 1 },
                { new DateTime(2012, 11,23), 1 },
                { new DateTime(2012, 11,26), 1 },
                { new DateTime(2012, 11,27), 1 },
                { new DateTime(2012, 11,28), 1 },
                { new DateTime(2012, 11,29), 1 },
                { new DateTime(2012, 11,30), 1 },
                { new DateTime(2012, 12,3), 1 },
                { new DateTime(2012, 12,4), 1 },
                { new DateTime(2012, 12,5), 1 },
                { new DateTime(2012, 12,6), 1 },
                { new DateTime(2012, 12,7), 1 },
                { new DateTime(2012, 12,10), 1 },
                { new DateTime(2012, 12,11), 1 },
                { new DateTime(2012, 12,12), 1 },
                { new DateTime(2012, 12,13), 1 },
                { new DateTime(2012, 12,14), 1 },
                { new DateTime(2012, 12,17), 1 },
                { new DateTime(2012, 12,18), 2 },
                { new DateTime(2012, 12,19), 2 },
                { new DateTime(2012, 12,20), 2 },
                { new DateTime(2012, 12,21), 2 },
                { new DateTime(2012, 12,24), 2 },
                { new DateTime(2012, 12,26), 2 },
                { new DateTime(2012, 12,27), 2 },
                { new DateTime(2012, 12,28), 2 },
                { new DateTime(2012, 12,31), 2 },
                { new DateTime(2013, 1,2), 2 },
                { new DateTime(2013, 1,3), 2 },
                { new DateTime(2013, 1,4), 2 },
                { new DateTime(2013, 1,7), 2 },
                { new DateTime(2013, 1,8), 2 },
                { new DateTime(2013, 1,9), 2 },
                { new DateTime(2013, 1,10), 2 },
                { new DateTime(2013, 1,11), 2 },
                { new DateTime(2013, 1,14), 2 },
                { new DateTime(2013, 1,15), 3 },
                { new DateTime(2013, 1,16), 3 },
                { new DateTime(2013, 1,17), 3 },
                { new DateTime(2013, 1,18), 3 },
                { new DateTime(2013, 1,22), 3 },
                { new DateTime(2013, 1,23), 3 },
                { new DateTime(2013, 1,24), 3 },
                { new DateTime(2013, 1,25), 3 },
                { new DateTime(2013, 1,28), 3 },
                { new DateTime(2013, 1,29), 3 },
                { new DateTime(2013, 1,30), 3 },
                { new DateTime(2013, 1,31), 3 },
                { new DateTime(2013, 2,1), 3 },
                { new DateTime(2013, 2,4), 3 },
                { new DateTime(2013, 2,5), 3 },
                { new DateTime(2013, 2,6), 3 },
                { new DateTime(2013, 2,7), 3 },
                { new DateTime(2013, 2,8), 3 },
                { new DateTime(2013, 2,11), 3 },
                { new DateTime(2013, 2,12), null },
                { new DateTime(2013, 2,13), null },
                { new DateTime(2013, 2,14), null },
                { new DateTime(2013, 2,15), null },
                { new DateTime(2013, 2,19), null },
                { new DateTime(2013, 2,20), null },
                { new DateTime(2013, 2,21), null },
                { new DateTime(2013, 2,22), null },
                { new DateTime(2013, 2,25), null },
                { new DateTime(2013, 2,26), null },
                { new DateTime(2013, 2,27), null },
                { new DateTime(2013, 2,28), null },
                { new DateTime(2013, 3,1), null },
                { new DateTime(2013, 3,4), null },
                { new DateTime(2013, 3,5), null },
                { new DateTime(2013, 3,6), null },
                { new DateTime(2013, 3,7), null },
                { new DateTime(2013, 3,8), null },
                { new DateTime(2013, 3,11), null },
                { new DateTime(2013, 3,12), null },
                { new DateTime(2013, 3,13), null }
            };

            Dictionary<DateTime, int?> returnedExpirationMonths = new Dictionary<DateTime, int?>();

            //hook up the event to add the expiration month
            _broker.FoundFrontContract += (sender, e) =>
                {
                    returnedExpirationMonths.Add(e.Date, e.Instrument == null ? null : (int?)e.Instrument.Expiration.Value.Month);
                };

            _cfInst.ContinuousFuture.Month = 2;

            //make the request
            foreach (DateTime dt in expectedExpirationMonths.Keys)
            {
                _broker.RequestFrontContract(_cfInst, dt);
            }


            int i = 0;
            while (expectedExpirationMonths.Count != returnedExpirationMonths.Count)
            {
                i++;
                if (i >= 50)
                {
                    string missing = string.Join(", ", expectedExpirationMonths.Except(returnedExpirationMonths).Select(x => x.Key));
                    Assert.IsTrue(false, "Took too long. Missing: " + missing);
                }
                Thread.Sleep(50);
            }

            string missing2 = string.Join(", ", expectedExpirationMonths.Except(returnedExpirationMonths).Select(x => x.Key));
            Assert.AreEqual(0, expectedExpirationMonths.Except(returnedExpirationMonths).Count(), missing2);

            foreach (var kvp in expectedExpirationMonths)
            {
                var month = kvp.Value;
                Assert.IsTrue(returnedExpirationMonths.ContainsKey(kvp.Key), "Contains: " + kvp.Key.ToString());
                Assert.AreEqual(month, returnedExpirationMonths[kvp.Key], "Are equal: " + kvp.Key.ToString());
            }
        }
        /// <summary>
        /// Given a vector, it will attempt to trim any superfluous
        /// axes e.g. conjunctives, times (but not dates).
        /// </summary>
        /// <param name="vec"></param>
        /// <returns></returns>
        public static Dictionary<string, int> TrimVector(Dictionary<string, int> vec)
        {
            var removalList = new Dictionary<string, int>();
            foreach (var kvp in vec)
            {
                var timePattern = @"^\d{2}:\d{2}:\d{2}$";
                var timeRgx = new Regex(timePattern);

                if (kvp.Key.Length <= 3)
                {
                    removalList.Add(kvp.Key, kvp.Value);
                }
                else if ((timeRgx.Match(kvp.Key)).Success)
                {
                    removalList.Add(kvp.Key, kvp.Value);
                }
            }
            return vec.Except(removalList).ToDictionary(x => x.Key, x => x.Value);
        }
Example #22
0
        public virtual string MakeWhereClause(Dictionary<string, object> keyFields, string paramPrefix = "", bool useParameters = true)
        {
            keyFields = keyFields ?? new Dictionary<string, object>();

            // TODO: Figure out how to pass null values as parameters
            // instead of hardcoding them in here
            var nullFields = keyFields.WhereValues(v => v == DBNull.Value || v == null).Keys;
            var nullFieldParts = nullFields.Select(x => x + " is null");

            var nonNullFields = keyFields.Except(nullFields).Keys;
            var nonNullFieldParts =
                useParameters ?
                    nonNullFields.Select(x => x + " = @" + paramPrefix + x) :
                    nonNullFields.Select(x => x + " = " + SqlLiteral(keyFields[x]));

            var whereClause = "";
            if (keyFields.Any())
                whereClause = " WHERE " + nullFieldParts.And(nonNullFieldParts).Join(" AND ");

            return whereClause;
        }
        public void GetProperties()
        {
            downloader.Pages["http://myhost:222/api/properties?resource=foo+bar"] = "[{\"key\": \"sonar.property1\",\"value\": \"value1\"},{\"key\": \"sonar.property2\",\"value\": \"value2\"}]";
            var expected = new Dictionary<string, string>();
            expected["sonar.property1"] = "value1";
            expected["sonar.property2"] = "value2";
            expected["sonar.cs.msbuild.testProjectPattern"] = SonarProperties.DefaultTestProjectPattern;
            var actual = ws.GetProperties("foo bar");

            Assert.AreEqual(true, expected.Count == actual.Count && !expected.Except(actual).Any());
        }