Exemple #1
0
        public void Case01()
        {
            var grid = new GridParser().Parse(Properties.Resources.GridParserFixture_Case01);

            Assert.NotNull(grid);
            Assert.Equal(3, grid.Rows.Count);

            var row0 = grid.Rows[0];

            Assert.NotNull(row0);
            Assert.Single(row0);
            Assert.NotNull(row0[0]);
            Assert.Equal("0-1", row0[0].Value);

            var row1 = grid.Rows[1];

            Assert.NotNull(row1);
            Assert.Equal(2, row1.Count);
            Assert.NotNull(row1[0]);
            Assert.Equal("1-1", row1[0].Value);
            Assert.NotNull(row1[1]);
            Assert.Equal("1-2", row1[1].Value);

            var row2 = grid.Rows[2];

            Assert.NotNull(row2);
            Assert.Equal(3, row2.Count);
            Assert.NotNull(row2[0]);
            Assert.Equal("2-1", row2[0].Value);
            Assert.NotNull(row2[1]);
            Assert.Equal(string.Empty, row2[1].Value);
            Assert.NotNull(row2[2]);
            Assert.Equal("2-3", row2[2].Value);
        }
Exemple #2
0
        public void HasNotAlignmentRow()
        {
            var grid = new GridParser().Parse(Properties.Resources.GridParserFixture_HasNotAlignmentRows);

            Assert.NotNull(grid);
            Assert.False(grid.HasAlignmentRows);
        }
Exemple #3
0
        public static IPage <T> List <T>(this GridCommand command, int pageSize)
            where T : class, IEntity <T>
        {
            var def = GridParser.Parse <T>(command, pageSize);

            return(Entity <T> .Linq(def.Map, def.Reduce));
        }
Exemple #4
0
        public static int BurstsCausingInfection(IList <string> input)
        {
            Grid infectionGridMap = GridParser.Parse(input);

            HashSet <Point> originallyInfected = new HashSet <Point>(infectionGridMap.Where(x => x.value).Select(x => x.point));
            HashSet <Point> currentlyInfected  = new HashSet <Point>(originallyInfected);

            var currentX = infectionGridMap.Width / 2;
            var currentY = infectionGridMap.Height / 2;

            Point     currentPosition  = new Point(currentX, currentY);
            Direction currentDirection = Direction.North;
            int       infectedCount    = 0;

            for (int i = 0; i < 10000; i++)
            {
                var currentDisplay = PrintCurrent(currentPosition, currentlyInfected, new HashSet <Point>(), new HashSet <Point>());

                if (currentlyInfected.Contains(currentPosition))
                {
                    currentDirection = currentDirection.Turn(Turn.Right);
                    currentlyInfected.Remove(currentPosition);
                }
                else
                {
                    currentDirection = currentDirection.Turn(Turn.Left);
                    currentlyInfected.Add(currentPosition);
                    infectedCount++;
                }
                currentPosition = currentPosition.Move(currentDirection);
            }

            return(infectedCount);
        }
        public static void Run(int size, int iterations, string simDesc, string boardPath, bool dbInsert)
        {
            Statistics stats = new Statistics(new Simulation() { SimulationId = Guid.NewGuid(), Description = simDesc, SimulationDate = DateTime.Now, AIType = (int)AIType.Random });

            try
            {
                Random random = new Random();
                for (int i = 0; i < iterations; i++)
                {
                    Game game = new Game();
                    game.GameId = Guid.NewGuid();
                    game.SimulationId = stats.Simulation.SimulationId;
                    game.GameNumber = i + 1;
                    
                    string s = Files.Read(boardPath);
                    Board board = GridParser.Parse(s, size);
                    HuntTargetAI RandAI = new HuntTargetAI(board, game.GameId, random);
                    stats.Shots.AddRange(RandAI.Play());
                    stats.Games.Add(game);
                }

                if(dbInsert)
                    DbInsert.Insert(stats);
                Console.WriteLine("Done");

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Exemple #6
0
        public void HasNotAlignmentRow()
        {
            var grid = new GridParser().Parse(@" |0-1| 
 |:-|-a|:-:|-:| ");

            Assert.NotNull(grid);
            Assert.False(grid.HasAlignmentRows);
        }
Exemple #7
0
        public void Test()
        {
            var contents   = _fileReader.ReadFile();
            var info       = new GridParser().ParseToGrid(contents);
            var grid       = new Grid(info);
            var pathFinder = new PathFinder(grid);
            var list       = pathFinder.FindPath();

            grid.PrintPath(list);
        }
 public void Release()
 {
     streamParser = null;
     gridParser   = null;
     if (gridDrawer != null)
     {
         gridDrawer.Dispose();
         gridDrawer = null;
     }
 }
        public void When_EditorAlias_Is_Correct_IsParserFor_Should_Return_True()
        {
            // arrange
            var parser = new GridParser();

            // act
            var result = parser.IsParserFor(Constants.PropertyEditors.Aliases.Grid);

            // assert
            Assert.IsTrue(result);
        }
Exemple #10
0
        public void When_Value_Is_Not_Set_GetRelatedEntities_Return_Empty_List()
        {
            // arrange
            var parser = new GridParser();

            // act
            var result = parser.GetRelatedEntities(null);

            // assert
            Assert.IsNotNull(result);
            Assert.AreEqual(0, result.Count());
        }
Exemple #11
0
        static void Main(string[] args)
        {
            //fetch the dependencies - here we just create them
            var neighbourCalculator = new NeighbourCalculator();
            var gameRules           = new GameRules(new LiveCellRule(), new DeadCellRule());
            var evolution           = new Evolution(neighbourCalculator, gameRules);
            var gridRowColumnParser = new GridParser();
            //typically we would create such an object and inject its dependencies
            //using an IoC container

            //Have to reference to via the namespace as the class and namespace are called the same thing.
            GameOfLifeInterface gameOfLife = new GameOfLife.UI.GameOfLife(evolution, gridRowColumnParser);

            gameOfLife.start();
        }
Exemple #12
0
        public void TestIsParserForValidDataType()
        {
            // arrange
            var dataTypeDefinition = new DataTypeDefinition(global::Umbraco.Core.Constants.PropertyEditors.GridAlias);

            var gridConfigMock = new Mock <IGridConfig>();

            var parser = new GridParser(gridConfigMock.Object);

            // act
            var result = parser.IsParserFor(dataTypeDefinition);

            // verify
            Assert.IsTrue(result);
        }
Exemple #13
0
        public void TestIsParserForInValidDataType()
        {
            // arrange
            var dataTypeDefinition = new DataTypeDefinition("foo");

            var gridConfigMock = new Mock <IGridConfig>();

            var parser = new GridParser(gridConfigMock.Object);

            // act
            var result = parser.IsParserFor(dataTypeDefinition);

            // verify
            Assert.IsFalse(result);
        }
Exemple #14
0
        public void TestGetLinkedEntitiesWithEmptyValue()
        {
            // arrange
            var gridConfigMock = new Mock <IGridConfig>();

            var parser = new GridParser(gridConfigMock.Object);

            // act
            var result = parser.GetLinkedEntities(null);

            // verify
            Assert.IsNotNull(result);
            var entities = result.ToList();

            Assert.AreEqual(0, entities.Count());
        }
Exemple #15
0
 public void Initialize()
 {
     streamParser = new StreamParser(new char[] { '.', 'B', 'W' });
     gridParser   = new GridParser <CellColor>(new Dictionary <char, CellColor>()
     {
         { '.', CellColor.Blank },
         { 'W', CellColor.White },
         { 'B', CellColor.Black }
     });
     gridDrawer = new GridTextDrawer <CellColor>(Console.Out, new Dictionary <CellColor, char>()
     {
         { CellColor.Blank, '.' },
         { CellColor.White, 'W' },
         { CellColor.Black, 'B' }
     }, '0');
 }
Exemple #16
0
        public static async Task <IGridData <string> > GetGridDataAsync(string expression, GridRange?gridRange, IRSession rSession = null)
        {
            await TaskUtilities.SwitchToBackgroundThread();

            if (rSession == null)
            {
                rSession = VsAppShell.Current.ExportProvider.GetExportedValue <IRSessionProvider>().GetInteractiveWindowRSession();
                if (rSession == null)
                {
                    throw new InvalidOperationException(Invariant($"{nameof(IRSessionProvider)} failed to return RSession for {nameof(EvaluationWrapper)}"));
                }
            }

            string rows    = gridRange?.Rows.ToRString();
            string columns = gridRange?.Columns.ToRString();

            REvaluationResult?result = null;

            using (var evaluator = await rSession.BeginEvaluationAsync()) {
                result = await evaluator.EvaluateAsync($"rtvs:::grid.dput(rtvs:::grid.data({expression}, {rows}, {columns}))", REvaluationKind.Normal);

                if (result.Value.ParseStatus != RParseStatus.OK || result.Value.Error != null)
                {
                    throw new InvalidOperationException($"Grid data evaluation failed{Environment.NewLine} {result}");
                }
            }

            GridData data = null;

            if (result.HasValue)
            {
                data = GridParser.Parse(result.Value.StringResult.ToUnicodeQuotes());
                if (gridRange.HasValue)
                {
                    data.Range = gridRange.Value;
                }

                if ((data.ValidHeaderNames.HasFlag(GridData.HeaderNames.Row) && data.RowNames.Count != data.Range.Rows.Count) ||
                    (data.ValidHeaderNames.HasFlag(GridData.HeaderNames.Column) && data.ColumnNames.Count != data.Range.Columns.Count))
                {
                    throw new InvalidOperationException("Header names lengths are different from data's length");
                }
            }

            return(data);
        }
        public void CanParseGridFromString()
        {
            var input = "Generation 1:" + Environment.NewLine
                        + "4 8" + Environment.NewLine
                        + "........" + Environment.NewLine
                        + "....*..." + Environment.NewLine
                        + "...**..." + Environment.NewLine
                        + "........" + Environment.NewLine;

            var actual = new GridParser().Parse(input);

            Assert.That(actual.IsAlive(1, 4));
            Assert.That(actual.IsAlive(2, 3));
            Assert.That(actual.IsAlive(2, 4));
            Assert.IsFalse(actual.IsAlive(0, 0));
            Assert.IsFalse(actual.IsAlive(1, 0));
            Assert.IsFalse(actual.IsAlive(3, 0));
        }
Exemple #18
0
        static void Main(string[] args)
        {
            var streamParser = new StreamParser(new char[] { '.', 'B', 'W' });
            var gridParser   = new GridParser <CellColor>(new Dictionary <char, CellColor>()
            {
                { '.', CellColor.Blank },
                { 'W', CellColor.White },
                { 'B', CellColor.Black }
            });
            var gridWriter = new GridTextDrawer <CellColor>(Console.Out, new Dictionary <CellColor, char>()
            {
                { CellColor.Blank, '.' },
                { CellColor.White, 'W' },
                { CellColor.Black, 'B' }
            }, '0');

            while (true)
            {
                Console.Clear();

                if (!streamParser.TryParse(Console.In, out string streamResult))
                {
                    continue;
                }
                if (!gridParser.TryParse(streamResult, out var grid))
                {
                    continue;
                }

                Console.WriteLine();

                var owner              = CellColor.Black;
                var finder             = new PossibleMoveCellFinder(grid);
                var possibleMovePoints = finder.Find(owner);
                gridWriter.Draw(grid, possibleMovePoints, owner);

                Console.ReadKey();

                break;
            }
        }
Exemple #19
0
        public void When_starting_with_blank_line_Then_blank_line_will_be_trimmed()
        {
            var grid = new GridParser().Parse(@"		
      
 |0-1| 
|1-1|1-2
2-1||2-3|
");

            Assert.NotNull(grid);
            Assert.Equal(3, grid.Rows.Count);

            var row0 = grid.Rows[0];

            Assert.NotNull(row0);
            Assert.Single(row0);
            Assert.NotNull(row0[0]);
            Assert.Equal("0-1", row0[0].Value);

            var row1 = grid.Rows[1];

            Assert.NotNull(row1);
            Assert.Equal(2, row1.Count);
            Assert.NotNull(row1[0]);
            Assert.Equal("1-1", row1[0].Value);
            Assert.NotNull(row1[1]);
            Assert.Equal("1-2", row1[1].Value);

            var row2 = grid.Rows[2];

            Assert.NotNull(row2);
            Assert.Equal(3, row2.Count);
            Assert.NotNull(row2[0]);
            Assert.Equal("2-1", row2[0].Value);
            Assert.NotNull(row2[1]);
            Assert.Equal(string.Empty, row2[1].Value);
            Assert.NotNull(row2[2]);
            Assert.Equal("2-3", row2[2].Value);
        }
Exemple #20
0
        public void When_Value_Is_Set_GetRelatedEntities_Return_List_With_Related_Entities()
        {
            // arrange
            var gridJson = @"{
  ""name"": ""1 column layout"",
  ""sections"": [
    {
      ""grid"": 12,
      ""allowAll"": true,
      ""rows"": [
        {
          ""name"": ""FullWidth"",
          ""areas"": [
            {
              ""grid"": 12,
              ""allowAll"": true,
              ""hasConfig"": false,
              ""controls"": [
                {
                  ""value"": ""Oooh la la"",
                  ""editor"": {
                    ""name"": ""Headline"",
                    ""alias"": ""headline"",
                    ""view"": ""textstring"",
                    ""render"": null,
                    ""icon"": ""icon-coin"",
                    ""config"": {
                      ""style"": ""font-size: 36px; line-height: 45px; font-weight: bold"",
                      ""markup"": ""<h1>#value#</h1>""
                    }
                  },
                  ""active"": false
                }
              ]
            }
          ],
          ""hasConfig"": false,
          ""id"": ""f10995f1-918d-3e50-e50d-8c41bbe297ce""
        },
        {
          ""label"": ""Article"",
          ""name"": ""Article"",
          ""areas"": [
            {
              ""grid"": 4,
              ""hasConfig"": false,
              ""controls"": [
                {
                  ""value"": {
                    ""udi"": ""umb://media/c0969cab13ab4de9819a848619ac2b5d"",
                    ""image"": ""/media/c0969cab13ab4de9819a848619ac2b5d/00000006000000000000000000000000/18095416144_44a566a5f4_h.jpg""
                  },
                  ""editor"": {
                    ""name"": ""Image"",
                    ""alias"": ""media"",
                    ""view"": ""media"",
                    ""render"": null,
                    ""icon"": ""icon-picture"",
                    ""config"": {}
                  },
                  ""active"": false
                }
              ]
            },
            {
              ""grid"": 8,
              ""hasConfig"": false,
              ""controls"": [
                {
                  ""value"": ""<p>Vestibulum ac diam sit <a data-udi=\""umb://document/e8ad9b65cff64952ac5befe56a60db62\"" href=\""/{localLink:umb://document/e8ad9b65cff64952ac5befe56a60db62}\"" title=\""People\"">amet</a> quam vehicula elementum sed sit amet dui. Curabitur aliquet quam id dui posuere blandit. Vivamus suscipit tortor eget felis porttitor volutpat. Proin eget tortor risus. Sed porttitor lectus nibh. Cras ultricies ligula sed magna dictum porta. Pellentesque in ipsum id orci porta dapibus. Pellentesque in ipsum id orci porta dapibus. Nulla porttitor accumsan tincidunt. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a.</p>\n<p>Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Curabitur aliquet quam id dui posuere blandit. Vivamus suscipit tortor eget felis porttitor volutpat. Proin eget tortor risus. Sed porttitor lectus nibh. Cras ultricies ligula sed magna dictum porta. Pellentesque in ipsum id orci porta dapibus. Pellentesque in ipsum id orci porta dapibus. Nulla porttitor accumsan tincidunt. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a.</p>"",
                  ""editor"": {
                    ""name"": ""Rich text editor"",
                    ""alias"": ""rte"",
                    ""view"": ""rte"",
                    ""render"": null,
                    ""icon"": ""icon-article"",
                    ""config"": {}
                  },
                  ""active"": false
                },
                {
                  ""value"": ""<iframe width=\""360\"" height=\""203\"" src=\""https://www.youtube.com/embed/HPgKSCp_Y_U?feature=oembed\"" frameborder=\""0\"" allow=\""accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\"" allowfullscreen></iframe>"",
                  ""editor"": {
                    ""name"": ""Embed"",
                    ""alias"": ""embed"",
                    ""view"": ""embed"",
                    ""render"": null,
                    ""icon"": ""icon-movie-alt"",
                    ""config"": {}
                  },
                  ""active"": false
                }
              ]
            }
          ],
          ""hasConfig"": false,
          ""id"": ""4d6e2221-e2d9-95bc-8ceb-624bc8df8e3f""
        }
      ]
    }
  ]
}";

            var parser = new GridParser();

            // act
            var result = parser.GetRelatedEntities(gridJson).ToList();

            // assert
            Assert.IsNotNull(result);
            Assert.That(result.Count == 2);

            Assert.That(result.Count(x => x.RelationType == RelationTypes.DocumentToDocument) == 1);

            Assert.That(result.Exists(x => x.RelatedEntityUdi.ToString() == "umb://document/e8ad9b65cff64952ac5befe56a60db62" && x.RelationType == RelationTypes.DocumentToDocument));
            Assert.That(result.Exists(x => x.RelatedEntityUdi.ToString() == "umb://media/c0969cab13ab4de9819a848619ac2b5d" && x.RelationType == RelationTypes.DocumentToMedia));
        }
Exemple #21
0
 public void SetUp()
 {
     subject = new GridParser();
 }
Exemple #22
0
        public void TestGetLinkedEntitiesWithValue()
        {
            // arrange
            var mediaEditorAlias          = "media_text_right";
            var mediaGridEditorConfigMock = new Mock <IGridEditorConfig>();

            mediaGridEditorConfigMock.SetupGet(x => x.Alias).Returns(mediaEditorAlias);
            mediaGridEditorConfigMock.SetupGet(x => x.View).Returns("media");

            var richTextEditorAlias       = "rte";
            var richtTextEditorConfigMock = new Mock <IGridEditorConfig>();

            richtTextEditorConfigMock.SetupGet(x => x.Alias).Returns(richTextEditorAlias);
            richtTextEditorConfigMock.SetupGet(x => x.View).Returns("rte");

            var gridEditorsConfigMock = new Mock <IGridEditorsConfig>();

            gridEditorsConfigMock.SetupGet(x => x.Editors)
            .Returns(
                new List <IGridEditorConfig> {
                mediaGridEditorConfigMock.Object, richtTextEditorConfigMock.Object
            });

            var gridConfigMock = new Mock <IGridConfig>();

            gridConfigMock.SetupGet(x => x.EditorsConfig).Returns(gridEditorsConfigMock.Object);

            var parser = new GridParser(gridConfigMock.Object);

            var mediaId   = 1086;
            var contentId = 1068;

            var value = $@"{{
  ""name"": ""1 column layout"",
  ""sections"": [
    {{
      ""grid"": 12,
      ""rows"": [        
        {{
          ""name"": ""Article"",
          ""areas"": [
            {{
              ""grid"": 4,
              ""controls"": [
                {{
                  ""value"": {{
                    ""focalPoint"": {{
                      ""left"": 0.5,
                      ""top"": 0.5
                    }},
                    ""id"": {mediaId},
                    ""image"": ""/media/1050/costa-rican-frog.jpg""
                  }},
                  ""editor"": {{
                    ""alias"": ""{mediaEditorAlias}""
                  }}
                }}
              ]
            }},
            {{
              ""grid"": 8,
              ""controls"": [
                {{
                  ""value"": ""<p>Test rich text editor with <a data-id=\""{contentId}\"" href=\""/{{localLink:{contentId}}}\"" title=\""Explore\"">links</a></p>\n<p> </p>"",
                  ""editor"": {{
                    ""alias"": ""{richTextEditorAlias}""
                  }}
                }}
              ]
            }}
          ],
          ""id"": ""1c03d717-41ff-a495-5abb-4cd6abf71d7c""
        }}
      ]
    }}
  ]
}}";

            // act
            var result = parser.GetLinkedEntities(value);

            // verify
            Assert.IsNotNull(result);
            var entities = result.ToList();

            Assert.AreEqual(2, entities.Count());

            Assert.IsTrue(entities.Any(x => x.Id == mediaId && x.LinkedEntityType == LinkedEntityType.Media));
            Assert.IsTrue(entities.Any(x => x.Id == contentId && x.LinkedEntityType == LinkedEntityType.Document));
        }
Exemple #23
0
 public void SetUp()
 {
     subject = new GridParser();
 }