Example #1
1
        public static void ApplySetPieces(World world)
        {
            var map = world.Map;
            int w = map.Width, h = map.Height;

            Random rand = new Random();
            HashSet<Rect> rects = new HashSet<Rect>();
            foreach (var dat in setPieces)
            {
                int size = dat.Item1.Size;
                int count = rand.Next(dat.Item2, dat.Item3);
                for (int i = 0; i < count; i++)
                {
                    IntPoint pt = new IntPoint();
                    Rect rect;

                    int max = 50;
                    do
                    {
                        pt.X = rand.Next(0, w);
                        pt.Y = rand.Next(0, h);
                        rect = new Rect() { x = pt.X, y = pt.Y, w = size, h = size };
                        max--;
                    } while ((Array.IndexOf(dat.Item4, map[pt.X, pt.Y].Terrain) == -1 ||
                             rects.Any(_ => Rect.Intersects(rect, _))) &&
                             max > 0);
                    if (max <= 0) continue;
                    dat.Item1.RenderSetPiece(world, pt);
                    rects.Add(rect);
                }
            }
        }
Example #2
0
        public PathData pathTo(Pos target, Pos currentLocation, Tile[][] board, int spikeCost = 5)
        {
            Dictionary<string, InternalTile> Navigated = new Dictionary<string, InternalTile>();
            HashSet<InternalTile> Closed = new HashSet<InternalTile>();

            InternalTile beginning = new InternalTile() { TilePos = currentLocation, Weight = 0 };
            HashSet<InternalTile> Opened = new HashSet<InternalTile> {
                beginning
            };

            Dictionary<string, int> Scores = new Dictionary<string, int> {
                {GetKey(beginning.TilePos.x, beginning.TilePos.y), beginning.Weight}
            };


            Dictionary<string, float> FullScores = new Dictionary<string, float> {
                {GetKey(beginning.TilePos.x, beginning.TilePos.y), GetDistance(currentLocation, target)}
            };

            while (Opened.Any()) {
                InternalTile lowest = Opened.First(tile => GetKey(tile.TilePos.x, tile.TilePos.y) == GetLowestCostTile(FullScores, Opened));

                if (lowest.TilePos.x == target.x && lowest.TilePos.y == target.y) {
                    return ReconstructPath(Navigated, target);
                }

                Opened.Remove(lowest);
                Closed.Add(lowest);

                foreach (Pos neighbor in GetNeighbors(lowest.TilePos, board.Length, board[0].Length)) {
                    if (Closed.Any(tile => tile.TilePos.x == neighbor.x && tile.TilePos.y == neighbor.y)) {
                        continue;
                    }

                    string neighborKey = GetKey(neighbor.x, neighbor.y);
                    int curScore = Scores[GetKey(lowest.TilePos.x, lowest.TilePos.y)] + 1;
                    if (!Opened.Any(tile => tile.TilePos.x == neighbor.x && tile.TilePos.y == neighbor.y)) {
                        Opened.Add(new InternalTile { TilePos = new Pos { x = neighbor.x, y = neighbor.y } });
                    } else if (curScore >= (Scores.ContainsKey(neighborKey) ? Scores[neighborKey] : int.MaxValue)) {
                        continue;
                    }

                    Navigated.Add(neighborKey, lowest);
                    Scores.Add(neighborKey, curScore);
                    FullScores.Add(neighborKey, curScore + GetDistance(neighbor, target));
                }
            }

            return null;
        }
        public async Task<IEnumerable<UserData>> Post(IEnumerable<ScoreData> scores, string p)
        {
            if (p != ConfigurationManager.AppSettings["SyncPass"])
                return null;

            var users = (await _userDataRepo.Get()).ToDictionary(x => x.UserId, x => x);
            var usersToUpdate = new HashSet<UserData>();

            foreach (var score in scores)
            {
                UserData user;

                if (users.ContainsKey(score.UserId))
                {
                    user = users[score.UserId];
                }
                else
                {
                    user = new UserData { UserId = score.UserId };
                    users.Add(score.UserId, user);
                    usersToUpdate.Add(user);
                }

                if (user.Score != score.Score)
                {
                    user.Score = score.Score;
                    usersToUpdate.Add(user);
                }
            }

            if (usersToUpdate.Any())
                await _userDataRepo.SaveBatch(usersToUpdate);

            return users.Values;
        }
        /// <summary>
        /// Business or validation rule implementation.
        /// </summary>
        /// <param name="context">Rule context object.</param>
        protected override void Execute(RuleContext context)
        {
            var commands = (ProcessCommandEditList)context.InputPropertyValues[PrimaryProperty];

            if (commands == null) return;

            foreach (var command in commands)
            {
                var foundConfigurations = new HashSet<ProcessCommandSecurityConfigurationEdit>();

                var command1 = command;
                foreach (var configuration in command.SecurityConfigurationList.Where(configuration => !foundConfigurations.Any(f => f.RoleId == configuration.RoleId &&
                                                                                                                                     f.StateGuid == configuration.StateGuid &&
                                                                                                                                     f.BusinessUnitId == configuration.BusinessUnitId &&
                                                                                                                                     f.PersonFieldSystemName == configuration.PersonFieldSystemName)
                                                                                                       && command1.SecurityConfigurationList.Any(x => !x.Equals(configuration) &&
                                                                                                                                                      x.RoleId == configuration.RoleId &&
                                                                                                                                                      x.StateGuid == configuration.StateGuid &&
                                                                                                                                                      x.BusinessUnitId == configuration.BusinessUnitId &&
                                                                                                                                                      x.PersonFieldSystemName == configuration.PersonFieldSystemName))
                    )
                {
                    foundConfigurations.Add(configuration);

                    context.AddErrorResult(PrimaryProperty, string.Format(LanguageService.Translate("Rule_UniqueSecurityConfiguration"), command.CommandName));
                }
            }
        }
        public override void Generate()
        {
            Console.WriteLine("Generating Age ranges");

            var uniqueAgeRanges = new HashSet<AgeRanx>();
            while (uniqueAgeRanges.Count != this.Count)
            {
                var minAge = this.Random.GetInt(0, 20);
                var maxAge = minAge + this.Random.GetInt(1, 5);

                var newAgeRange = new AgeRanx
                {
                    MaxAge = maxAge,
                    MinAge = minAge
                };
                if (!uniqueAgeRanges.Any(a => a.MinAge == minAge && a.MaxAge == maxAge))
                {
                    uniqueAgeRanges.Add(newAgeRange);
                }
            }
            var index = 0;

            foreach (var uniqueAgeRange in uniqueAgeRanges)
            {
                Db.AgeRanges.Add(uniqueAgeRange);
                index++;
                if (index % 100 == 0)
                {
                    Console.Write(".");
                    Db.SaveChanges();
                }
            }
            Console.WriteLine("\nGenerating Age Ranges Done!");
        }
        public void Render(IGraphNode<LibraryDependency> root)
        {
            // tuples of <Library Name, Requested Version, Actual Version>
            var results = new HashSet<Tuple<string, string, string>>();

            root.DepthFirstPreOrderWalk(
                (node, ancestors) =>
                {
                    var dependency = node.Item;
                    if (IsLibraryMismatch(dependency))
                    {
                        results.Add(Tuple.Create(
                            dependency.Library.Identity.Name,
                            dependency.LibraryRange.VersionRange?.MinVersion.ToString(),
                            dependency.Library.Identity.Version?.ToString()));
                    }

                    return true;
                });

            if (results.Any())
            {
                var format = GetFormat(results, padding: 2);

                RenderTitle(format);
                RenderMismatches(format, results);
            }
        }
        public IEnumerable<int> Parse(string message)
        {
            var lexer = new StringCalculatorLexer(message);
            var delimiters = new HashSet<string>();
            string numbersString = null;

            foreach (var token in lexer.Read())
            {
                if (token is DelimiterToken)
                {
                    delimiters.Add(token.Content);
                }

                if (token is NumbersToken)
                {
                    numbersString = token.Content;
                }
            }

            if (string.IsNullOrEmpty(numbersString))
            {
                return Enumerable.Empty<int>();
            }

            var numberSplitter = delimiters.Any() ?
                delimiters.GenerateSplitter() :
                _defaultSplitter;

            return numberSplitter
                .Split(numbersString)
                .Select(int.Parse);
        }
Example #8
0
        public static ClaimsIdentity CreateUserIdentity(string emailAddress, string id, string[] organizationIds, string[] roles, string defaultProjectId = null) {
            var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name, emailAddress),
                    new Claim(ClaimTypes.NameIdentifier, id),
                    new Claim(OrganizationIdsClaim, String.Join(",", organizationIds))
                };

            if (!String.IsNullOrEmpty(defaultProjectId))
                claims.Add(new Claim(DefaultProjectIdClaim, defaultProjectId));

            var userRoles = new HashSet<string>(roles);
            if (userRoles.Any()) {
                // add implied scopes
                if (userRoles.Contains(AuthorizationRoles.GlobalAdmin))
                    userRoles.Add(AuthorizationRoles.User);

                if (userRoles.Contains(AuthorizationRoles.User))
                    userRoles.Add(AuthorizationRoles.Client);

                claims.AddRange(userRoles.Select(scope => new Claim(ClaimTypes.Role, scope)));
            } else {
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.Client));
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.User));
            }

            return new ClaimsIdentity(claims, UserAuthenticationType);
        }
        public static IEnumerable<string> GetJarsFromPOM(this IMavenArtifactHandler handler, MavenPartialPOM pom)
        {
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }
            if (pom == null)
            {
                throw new ArgumentNullException("pom");
            }

            ISet<string> jarFilePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            foreach (MavenDependency dependency in pom.Dependencies)
            {
                string jarFilePath = handler.FetchArtifactJarFile(dependency);
                if (jarFilePath != null)
                {
                    Debug.Assert(!jarFilePaths.Contains(jarFilePath, StringComparer.OrdinalIgnoreCase), "Expecting full jar paths to be unique");
                    Debug.Assert(!jarFilePaths.Any(j => Path.GetFileName(j).Equals(Path.GetFileName(jarFilePath), StringComparison.OrdinalIgnoreCase)),
                        "Expecting jars file names to be unique");

                    jarFilePaths.Add(jarFilePath);
                }
            }
            return jarFilePaths;
        }
Example #10
0
        public void all_events_are_checked()
        {
            var eventAssembly = typeof (CreditCourseCreatedEvent).Assembly;
            var testAssembly = Assembly.GetExecutingAssembly();

            var eventTypes = eventAssembly.GetTypes()
                .Where(t => t.IsClass
                            && !t.IsAbstract
                            && typeof (IEvent).IsAssignableFrom(t));

            var eventFixtureTypes = testAssembly.GetTypes()
                .Where(t => t.IsClass && !t.IsAbstract);

            var missingTests = new HashSet<Type>();

            foreach (var eventType in eventTypes)
            {
                var fixtureBaseType = typeof (EventSerializationFixture<>)
                    .MakeGenericType(eventType);

                var fixtureTypes = eventFixtureTypes
                    .Where(t => fixtureBaseType.IsAssignableFrom(t))
                    .ToArray();

                if (!fixtureTypes.Any())
                    missingTests.Add(eventType);
            }

            if (missingTests.Any())
                Assert.Fail("The following events are not being tested: {0}",
                            string.Join(Environment.NewLine, missingTests));
        }
        public void CustomizeCodeDom(CodeCompileUnit codeUnit, IServiceProvider services)
        {
            var types = codeUnit.Namespaces[0].Types;
            var attributes = new HashSet<string>();
            foreach (var type in types.Cast<CodeTypeDeclaration>().
                                 Where(type => type.IsClass && !type.IsContextType()))
            {
                attributes.Clear();
                var @struct = new CodeTypeDeclaration {
                    Name = AttributeConstsStructName, 
                    IsStruct = true, 
                    TypeAttributes = TypeAttributes.Public
                };

                foreach (var member in from CodeTypeMember member in type.Members 
                                       let prop = member as CodeMemberProperty 
                                       where prop != null 
                                       select prop)
                {
                    CreateAttributeConstForProperty(@struct, member, attributes);
                }

                if (attributes.Any())
                {
                    type.Members.Insert(0, GenerateTypeWithoutEmptyLines(@struct));
                }
            }
        }
Example #12
0
        public static ClaimsIdentity ToIdentity(this User user, string defaultProjectId = null) {
            if (user == null)
                return WindowsIdentity.GetAnonymous();
            
            var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name, user.EmailAddress),
                    new Claim(ClaimTypes.NameIdentifier, user.Id),
                    new Claim(OrganizationIdsClaim, String.Join(",", user.OrganizationIds.ToArray()))
                };

            if (!String.IsNullOrEmpty(defaultProjectId))
                claims.Add(new Claim(DefaultProjectIdClaim, defaultProjectId));

            var userRoles = new HashSet<string>(user.Roles.ToArray());
            if (userRoles.Any()) {
                // add implied scopes
                if (userRoles.Contains(AuthorizationRoles.GlobalAdmin))
                    userRoles.Add(AuthorizationRoles.User);

                if (userRoles.Contains(AuthorizationRoles.User))
                    userRoles.Add(AuthorizationRoles.Client);

                claims.AddRange(userRoles.Select(scope => new Claim(ClaimTypes.Role, scope)));
            } else {
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.Client));
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.User));
            }

            return new ClaimsIdentity(claims, UserAuthenticationType);
        }
Example #13
0
        static int Main(string[] args)
        {
            var commandArguments = CommandArguments.Parse(args);
            if (!string.IsNullOrEmpty(commandArguments.Error))
            {
                Console.WriteLine(commandArguments.Error);
                return -1;
            }

            var returnCode = 0;
            var options = commandArguments.ParsedOptions;
            var modelsToProcess = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            if (!string.IsNullOrEmpty(options.ServiceModels))
            {
                foreach (var s in options.ServiceModels.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    modelsToProcess.Add(s);
                }
            }

            try
            {
                if (options.CompileCustomizations) // Compile all servicename.customizations*.json files into one json file in bin
                    CustomizationCompiler.CompileServiceCustomizations(options.ModelsFolder);

                var generationManifest = GenerationManifest.Load(options.Manifest, options.Versions, options.ModelsFolder);
                foreach (var serviceConfig in generationManifest.ServiceConfigurations)
                {
                    if (modelsToProcess.Any() && !modelsToProcess.Contains(serviceConfig.ModelName))
                    {
                        Console.WriteLine("Skipping model (not in -servicemodels set to process): {0} ({1})", serviceConfig.ModelName, serviceConfig.ModelPath);
                        continue;
                    }

                    Console.WriteLine("Processing model: {0} ({1})", serviceConfig.ModelName, serviceConfig.ModelPath);
                    var driver = new GeneratorDriver(serviceConfig, generationManifest, options);
                    driver.Execute();
                }

                GeneratorDriver.UpdateSolutionFiles(options);
                GeneratorDriver.UpdateAssemblyVersionInfo(generationManifest, options);
                GeneratorDriver.UpdateUnitTestProjectReferences(options);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error running generator: " + e.Message);
                Console.Error.WriteLine(e.StackTrace);
                returnCode = -1;
            }

            if (options.WaitOnExit)
            {
                Console.WriteLine();
                Console.WriteLine("Generation complete. Press a key to exit.");
                Console.ReadLine();
            }

            return returnCode;
        }
		public static IEnumerable<SyntaxNode> GetUnnecessaryImports(SemanticModel semanticModel, SyntaxNode root, CancellationToken cancellationToken)
		{
			var diagnostics = semanticModel.GetDiagnostics(cancellationToken: cancellationToken);
			if (!diagnostics.Any())
			{
				return null;
			}

			var unnecessaryImports = new HashSet<UsingDirectiveSyntax>();

			foreach (var diagnostic in diagnostics)
			{
				if (diagnostic.Id == "CS8019")
				{
					var node = root.FindNode(diagnostic.Location.SourceSpan) as UsingDirectiveSyntax;

					if (node != null)
					{
						unnecessaryImports.Add(node);
					}
				}
			}

			if (cancellationToken.IsCancellationRequested || !unnecessaryImports.Any())
			{
				return null;
			}

			return unnecessaryImports;
		}
        public static bool CreatesNewLife(this Cell cell, ISet<Cell> cells, out ISet<Cell> newLife)
        {
            var emptyNeighbors = cellTransform.Select(t => cell + t).Where(c => !cells.Contains(c));
            newLife = new HashSet<Cell>(emptyNeighbors.Where(n => GetNeighbors(n, cells).Count() == 3));

            return newLife.Any();
        }
        public long GetNextAvailableLong(List<long> values, bool returnZero)
        {
            if (values == null || !values.Any())
            {
                if (returnZero)
                {
                    return 0;
                }
                else
                {
                    return 1;
                }
            }

            HashSet<long> hashSetValues = new HashSet<long>(values);

            long x = hashSetValues.Min();

            while (hashSetValues.Any(m => m == x))
            {
                x++;
                if (x == 0 && !returnZero)
                {
                    x++;
                }
            }

            return x;
        }
Example #17
0
        protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) {

            try {

                base.ProcessPackage(provider, searchKey, package);
            
                // return the object to the caller now.
                WriteObject(package);

                if (IncludeDependencies) {
                    var missingDependencies = new HashSet<string>();
                    foreach (var dep in package.Dependencies) {
                        // note: future work may be needed if the package sources currently selected by the user don't
                        // contain the dependencies.
                        var dependendcies = PackageManagementService.FindPackageByCanonicalId(dep, this);
                        var depPkg = dependendcies.OrderByDescending(pp => pp, SoftwareIdentityVersionComparer.Instance).FirstOrDefault();

                        if (depPkg == null) {
                            missingDependencies.Add(dep);
                            Warning(Constants.Messages.UnableToFindDependencyPackage, dep);
                        } else {
                            ProcessPackage(depPkg.Provider, searchKey.Select(each => each + depPkg.Name).ToArray(), depPkg);
                        }
                    }
                    if (missingDependencies.Any()) {
                        Error(Constants.Errors.UnableToFindDependencyPackage, missingDependencies.JoinWithComma());
                    }
                }
            } catch (Exception ex) {

                Debug("Calling ProcessPackage {0}", ex.ToString());
            }
        }
Example #18
0
        private static void Main()
        {
            var input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            var n = input[0];
            var coord0 = new Coord(input[1], input[2]);
            var rgcoord = new HashSet<Coord>();
            for (var i = 0; i < n; i++)
            {
                input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
                rgcoord.Add(new Coord(input[0], input[1]));
            }

            var d = 0;
            while (rgcoord.Any())
            {
                d++;
                var coord = rgcoord.First();
                var vX = coord.x - coord0.x;
                var vY = coord.y - coord0.y;

                foreach (var coordT in rgcoord.ToList())
                {
                    if (vY*(coordT.x - coord0.x) == vX*(coordT.y - coord0.y))
                        rgcoord.Remove(coordT);
                }
            }

            Console.WriteLine(d);
        }
        private static void FindIndirectCircularReferences(ISet<Node> childList)
        {
            var toIgnore = new HashSet<Node>();
            foreach (var node in childList.ToHashSet())
            {
                if(toIgnore.Contains(node))
                    continue;

                var path = new HashSet<Node>();
                if (IndirectlyDependsOnItself(node, node, ref path))
                {
                    path.Add(node);
                    toIgnore.UnionWith(path);
                    childList.ExceptWith(path);
                    var dependantOnCircularDependencies = childList.Where(x => path.Any(x.DependsOn));
                    var cirularHolder = new CircularDependencyHolderNode(path);
                    foreach (var dependantOnCircularDependency in dependantOnCircularDependencies)
                    {
                        //Remove all dependencies on nodes in the path
                        dependantOnCircularDependency.SiblingDependencies.RemoveWhere(x => path.Contains(x));
                        //Add dependency on circular holder
                        dependantOnCircularDependency.SiblingDependencies.Add(cirularHolder);
                    }
                    //Add all dependencies in the path to the new node
                    cirularHolder.SiblingDependencies.UnionWith(path.SiblingDependencies().Except(path)); //Should not be dependant on themselves
                    childList.Add(cirularHolder);
                }
            }
        }
    public int[] FindBest()
    {
      var remaining = new HashSet<Point>(_cities);
      var first = remaining.First();
      var route = new List<Point> { first };
      remaining.Remove(first);

      var numericRoute = new List<int>{_cities.IndexOf(first)};
      var distance = 0.0d;
      while (remaining.Any())
      {
        var shortest = double.MaxValue;
        Point next = null;
        foreach (var p in remaining)
        {
          var d = Distance(route.Last(), p);
          if (d < shortest)
          {
            shortest = d;
            next = p;
          }
        }
        route.Add(next);
        numericRoute.Add(_cities.IndexOf(next));
        remaining.Remove(next);
        distance += shortest;
    
      }


      distance += Distance(route.First(), route.Last());
      Console.WriteLine("Distance calculated in closestneighbour: " + distance);
      return numericRoute.ToArray();
    }
        private void OutputReferences(Output result, DependencyGraph graph, Library lib, string type)
        {
            result.AppendLine(GetName(lib) + ":");

            var directDeps = new HashSet<Library>(graph.OutEdges(lib)
                .Select(d => d.Target));

            result.IncreaseIndent();
            result.AppendLine("Direct " + type + ":");

            result.IncreaseIndent();
            Output(result, directDeps);
            result.DecreaseIndent();

            result.DecreaseIndent();

            if (directDeps.Any())
            {
                var indirectDeps = ComputeIndirectDeps(graph, lib)
                    .Where(d => !directDeps.Contains(d))
            // ReSharper disable once PossibleUnintendedReferenceComparison
                    .Where(d => d != lib);

                result.IncreaseIndent();
                result.AppendLine("Indirect " + type + ":");

                result.IncreaseIndent();
                Output(result, indirectDeps);
                result.DecreaseIndent();

                result.DecreaseIndent();
            }

            result.AppendLine();
        }
        public static ISet<int> GetSchemaVersionsForSubscription(List<string> capabilities)
        {
            //The first two schema versions follow the old regex, and versions 3 on follow the new one.
            if (capabilities == null)
            {
                throw new ArgumentNullException("capabilities");
            }

            var matchesOld = capabilities.Select(s => ClustersContractCapabilityRegexOld.Match(s)).Where(match => match.Success).ToList();

            var schemaVersions = new HashSet<int>(matchesOld.Select(m => Int32.Parse(m.Groups[1].Value, CultureInfo.CurrentCulture)).ToList());

            var matchesNew = capabilities.Select(s => ClustersContractCapabilityRegex.Match(s)).Where(match => match.Success).ToList();
            if (matchesNew.Count != 0)
            {
                schemaVersions.UnionWith(
                    matchesNew.Select(m => Int32.Parse(m.Groups[1].Value, CultureInfo.CurrentCulture)));
            }

            if (schemaVersions == null || !schemaVersions.Any())
            {
                throw new NotSupportedException("This subscription is not enabled for the clusters contract.");
            }

            return schemaVersions;
        }
Example #23
0
		public IEnumerable<State> TransitiveClosure (
			Func<SimpleTransition, bool> selector,
			Func<SimpleTransition, bool> cancel)
		{
			var done = new HashSet<State> ();
			var work = new HashSet<State> ();
			work.Add (this);

			while (work.Any ()) {
				var q = work.First ();
				work.Remove (q);
				done.Add (q);

				if (q.Delta == null) {
					continue;
				}

				var ts = q.Delta
					.Where (t => selector == null || selector (t))
					.ToArray ();
				if (cancel != null && ts.Any (cancel)) {
					return null;
				}
				foreach (var qn in ts.Select (t => t.Next)) {
					if (!done.Contains (qn)) {
						work.Add (qn);
					}
				}
			}

			return done;
		}
Example #24
0
 /// <summary>
 /// When the tessellated solid is sliced at the specified plane, the contact surfaces are
 /// described by the return ContactData object. This is a non-destructive function typically
 /// used to find the shape and size of 2D surface on the prescribed plane..
 /// </summary>
 /// <param name="plane">The plane.</param>
 /// <param name="ts">The ts.</param>
 /// <returns>ContactData.</returns>
 /// <exception cref="System.Exception">Contact Edges found that are not contained in loop.</exception>
 public static ContactData DefineContact(Flat plane, TessellatedSolid ts)
 {
     var vertexDistancesToPlane = new double[ts.NumberOfVertices];
     for (int i = 0; i < ts.NumberOfVertices; i++)
         vertexDistancesToPlane[i] = ts.Vertices[i].Position.dotProduct(plane.Normal) - plane.DistanceToOrigin;
     // the edges serve as the easiest way to identify where the solid is interacting with the plane.
     // Instead of a foreach, the while loop lets us look ahead to known edges that are irrelevant.
     var edgeHashSet = new HashSet<Edge>(ts.Edges);
     // Contact elements are constructed and then later arranged into loops. Loops make up the returned object, ContactData.
     var straddleContactElts = new List<ContactElement>();
     var inPlaneContactElts = new List<CoincidentEdgeContactElement>();
     while (edgeHashSet.Any())
     {
         // instead of the foreach, we have this while statement and these first 2 lines to enumerate over the edges.
         var edge = edgeHashSet.First();
         edgeHashSet.Remove(edge);
         var toDistance = vertexDistancesToPlane[edge.To.IndexInList];
         var fromDistance = vertexDistancesToPlane[edge.From.IndexInList];
         if (StarMath.IsNegligible(toDistance) && StarMath.IsNegligible(fromDistance))
             ContactElement.MakeInPlaneContactElement(plane, edge, edgeHashSet, vertexDistancesToPlane,
                 inPlaneContactElts);
         else if ((toDistance > 0 && fromDistance < 0)
                  || (toDistance < 0 && fromDistance > 0))
             straddleContactElts.Add(new ThroughFaceContactElement(plane, edge, toDistance));
     }
     foreach (var contactElement in inPlaneContactElts)
     {
         // next, we find any additional vertices that just touch the plane but don't have in-plane edges
         // to facilitate this we negate all vertices already captures in the inPlaneContactElts
         vertexDistancesToPlane[contactElement.StartVertex.IndexInList] = double.NaN;
         vertexDistancesToPlane[contactElement.EndVertex.IndexInList] = double.NaN;
     }
     for (int i = 0; i < ts.NumberOfVertices; i++)
     {
         if (!StarMath.IsNegligible(vertexDistancesToPlane[i])) continue;
         var v = ts.Vertices[i];
         PolygonalFace negativeFace, positiveFace;
         if (ThroughVertexContactElement.FindNegativeAndPositiveFaces(plane, v, vertexDistancesToPlane,
             out negativeFace, out positiveFace))
             straddleContactElts.Add(new ThroughVertexContactElement(v, negativeFace, positiveFace));
     }
     straddleContactElts.AddRange(inPlaneContactElts);
     var loops = new List<Loop>();
     var numberOfTries = 0;
     while (straddleContactElts.Any() && numberOfTries < straddleContactElts.Count)
     {
         // now build loops from stringing together contact elements
         var loop = FindLoop(plane, straddleContactElts, vertexDistancesToPlane);
         if (loop != null)
         {
             Debug.WriteLine(loops.Count + ": " + loop.MakeDebugContactString() + "  ");
             loops.Add(loop);
             numberOfTries = 0;
         }
         else numberOfTries++;
     }
     if (straddleContactElts.Any()) Debug.WriteLine("Contact Edges found that are not contained in loop.");
     return new ContactData(loops);
 }
Example #25
0
        public override QState Initialize()
        {
            WriteOutput("Dimensions: " + width + "x" + height);
            self = new Point(start.X, start.Y);
            score = 0;

            walls = new Point[] { };

            // Generate Walls Randomly
            if (wallDensity > 0)
            {
                
                HashSet<Point> bestPathSoFar = new HashSet<Point>();
                WriteOutput("Generating walls randomly with density target of " + wallDensity + "...");
                for (int w = 0; w < width; w++)
                {
                    for (int h = 0; h < height; h++)
                    {
                        double r = random.NextDouble();
                        //WriteOutput("Wall Probability for " + w + "x" + h + ": " + r+" vs threshold "+walls);
                        if (r < wallDensity)
                        {
                            //WriteOutput("Wall created at " + w + "x" + h);
                            Point newWall = new Point(w, h);
                            if (start == newWall || goal == newWall) continue;
                            Point[] tempWalls = walls.Concat(new Point[] { newWall }).ToArray();
                            QState tempState = new Maze() { maze = maze, self = self, goal = goal, width = width, height = height, walls = tempWalls};
                            if (!bestPathSoFar.Any() || bestPathSoFar.Contains(newWall))
                            {
                                QSearchResult path = new QSearch().AStar(tempState);
                                if (path != null)
                                {
                                    bestPathSoFar.Clear();
                                    foreach (QState q in path.QStatesList)
                                        bestPathSoFar.Add(((Maze)q).self);
                                    walls = tempWalls;
                                }
                            }
                            else walls = tempWalls;
                        }

                    }
                }
                WriteOutput("Maze generation complete.");
            }

            opponent = new List<Point>();
            for (int i = 0; i < opponents; i++)
                opponent.Add(new Point(goal.X, goal.Y));

            if (!HideOutput)
            {
                ManualResetEvent wait = new ManualResetEvent(false);
                ThreadPool.QueueUserWorkItem(new WaitCallback(CreateGUI), new object[] { width, height, self.X, self.Y, goal.X, goal.Y, walls, this, wait });
                wait.WaitOne();
            }

            return new Maze() { width = width, height = height, self = self, goal = goal, walls = walls, wallDensity = wallDensity, opponent = opponent, opponentDifficulty = opponentDifficulty, random = random, maze = maze, start = start, opponents = opponents, bestOpponentPath = bestOpponentPath, score = score };
        }
        public void HashSetExtensions_Any_ReturnsTrueIfHashSetContainsItems()
        {
            var set = new HashSet<Int32>() { 1 };

            var result = set.Any();

            TheResultingValue(result).ShouldBe(true);
        }
        public void HashSetExtensions_AnyWithPredicate_ReturnsTrueIfHashSetContainsMatchingItems()
        {
            var set = new HashSet<Int32>() { 1, 2, 3 };

            var result = set.Any(x => x % 2 == 0);

            TheResultingValue(result).ShouldBe(true);
        }
        public void HashSetExtensions_Any_ReturnsFalseIfHashSetDoesNotContainItems()
        {
            var set = new HashSet<Int32>();

            var result = set.Any();

            TheResultingValue(result).ShouldBe(false);
        }
		public string ValidateFile(string pathToFile)
		{
			try
			{
				var doc = XDocument.Load(pathToFile);
				var root = doc.Root;
				if (root.Name.LocalName != SharedConstants.AdditionalFieldsTag)
					return "Not valid custom properties file";
				if (!root.HasElements)
					return null; // CustomFields are optional.

				var requiredAttrs = new HashSet<string>
										{
											"name",
											"class",
											"type",
											Key // Special attr added so fast xml splitter can find each one.
										};
				var optionalAttrs = new HashSet<string>
										{
											"destclass",
											"wsSelector",
											"helpString",
											"listRoot",
											"label"
										};
				foreach (var customFieldElement in root.Elements(SharedConstants.CustomField))
				{
					if (requiredAttrs
						.Any(requiredAttr => customFieldElement.Attribute(requiredAttr) == null))
					{
						return "Missing required custom property attribute";
					}
					if (customFieldElement.Attributes()
						.Any(attribute => !requiredAttrs.Contains(attribute.Name.LocalName)
							&& !optionalAttrs.Contains(attribute.Name.LocalName)))
					{
						return "Contains unrecognized attribute";
					}
					// Make sure 'key' attr is class+name.
					if (customFieldElement.Attribute("class").Value + customFieldElement.Attribute("name").Value != customFieldElement.Attribute(Key).Value)
						return "Mis-matched 'key' attribute with property class+name atributes";

					if (customFieldElement.HasElements)
						return "Contains illegal child element";
				}

				MetadataCache.MdCache.AddCustomPropInfo(new MergeOrder(
					pathToFile, pathToFile, pathToFile,
					new MergeSituation(pathToFile, "", "", "", "", MergeOrder.ConflictHandlingModeChoices.WeWin)));

				return null;
			}
			catch (Exception e)
			{
				return e.Message;
			}
		}
Example #30
0
 public static void AssertLinesInclude(this DocumentAnalyzer actual, params LineSpan[] expected)
 {
     var missingLines = new HashSet<LineSpan>(expected).Except(actual.GetAllLines());
     if (missingLines.Any()) {
         Assert.Fail("Lines not found:\r\n{0}\r\n\r\nActual lines:\r\n{1}",
             missingLines.ToFormattedString(),
             actual.GetAllLines().ToFormattedString());
     }
 }