예제 #1
0
        public async Task <Railway> PutRailwayAsync(int railwayId, Railway railway)
        {
            if (railwayId != railway.Id)
            {
                throw new Exception("Id is not equal to railway Id.");
            }

            _context.Entry(railway).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!_context.Railways.Any(e => e.Id == railwayId))
                {
                    throw new Exception("this railway is not exist.");
                }
                else
                {
                    throw;
                }
            }

            return(railway);
        }
예제 #2
0
        public async Task <HttpResponseMessage> AddNewAsync(RailwayJsonModel model)
        {
            if (model == null)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            var railway = new Railway
            {
                Id            = model.ID,
                Code          = model.Code,
                Name          = model.Name,
                ShortName     = model.ShortName,
                TelegraphName = model.TelegraphName,
                DateCreate    = model.DateCreate,
                DateUpdate    = model.DateUpdate,
                CountryId     = model.CountryID
            };

            await _context.AddAsync(railway);

            await _context.SaveChangesAsync();

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
예제 #3
0
        public async Task <HttpResponseMessage> AddNewAsync(IEnumerable <RailwayJsonModel> models)
        {
            if (models == null)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            foreach (var model in models)
            {
                var railway = new Railway
                {
                    Id            = model.ID,
                    Code          = model.Code,
                    Name          = model.Name,
                    ShortName     = model.ShortName,
                    TelegraphName = model.TelegraphName,
                    DateCreate    = model.DateCreate,
                    DateUpdate    = model.DateUpdate,
                    CountryId     = model.CountryID
                };

                await _context.AddAsync(railway);
            }

            var res = await _context.SaveChangesAsync();

            if (res > 0)
            {
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }

            return(new HttpResponseMessage(HttpStatusCode.BadRequest));
        }
예제 #4
0
 /// <summary>
 /// Called when a property of this entity has changed.
 /// </summary>
 internal override void OnModified()
 {
     if (Railway != null)
     {
         Railway.OnModified();
     }
 }
예제 #5
0
 public void SetUp()
 {
     catalogApi = new Mock <ICatalogApi>();
     productApi = new Mock <IProductApi>();
     sut        = new Railway(catalogApi.Object,
                              productApi.Object,
                              new ProductConverter());
 }
예제 #6
0
 void FillData()
 {
     Railways.Clear();
     foreach (var item in Railway.GetAllRailways())
     {
         Railways.Add(item);
     }
 }
        public void ResolveShortestTrip_ShouldReturnExpectedDistanceBasedOnTheRoute(string from, string to, int expectedDistance)
        {
            // Act
            var trip = TripService.FindShortest(Railway, Railway.GetTownByName(from), Railway.GetTownByName(to));

            // Assert
            Assert.Equal(expectedDistance, trip.TotalDistance);
        }
        public void Search_ShouldReturnExpectedMaxTrips_WithDistanceLessThanMaxDistance(string from, string to, int maxDistance, int expectedTrips)
        {
            // Act
            var trips = TripService.Search(Railway.GetTownByName(from), Railway.GetTownByName(to), trip => trip.TotalDistance >= maxDistance);

            // Assert
            Assert.Equal(expectedTrips, trips.Count());
        }
예제 #9
0
        public ActionResult DeleteConfirmed(int id)
        {
            Railway railway = db.Railway.Find(id);

            db.Railway.Remove(railway);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
예제 #10
0
        /// <summary>
        /// Решить обратную задачу
        /// </summary>
        /// <param name="model">Неполная модель исходных данных (только блоки DATA и ROUTE)</param>
        /// <param name="checker">Алгоритм решения прямой задачи - для вычисления стоимости</param>
        /// <returns>Полная модель (включая блоки ORDER и TOP)</returns>
        public FinalAnswer Solve(Model model, IDirectTaskSolver checker)
        {
            _model   = model;
            _answer  = Model.Copy(model);
            _checker = checker;

            var chain = RailwayChain.FromModel(_answer, true);

            _current1 = _chain = new Railway(RailwayType.L0);
            foreach (var railway in chain.GetRailways())
            {
                if (railway.IsHead())
                {
                    continue;
                }
                _current1.Append(railway);
                _current1 = _current1.Next;
            }

            _current1 = _current2 = _chain;

            Context = new DrawableContext();

            Context.BotsRating = "Управление:\n" +
                                 "W: Add L3\n" +
                                 "A: Add 2xT4L\n" +
                                 "S: Remove\n" +
                                 "D: Add 2xT4R\n" +
                                 "B: Add Bridge\n" +
                                 "Q: Prev item\n" +
                                 "E: Next item\n" +
                                 "Shift+W: L1\n" +
                                 "Shift+A: T4L\n" +
                                 "Shift+D: T4R\n" +
                                 "Z: Sync curs\n" +
                                 "X: Swap curs\n" +
                                 "C: Change mode\n" +
                                 "V: Insert tmpl\n" +
                                 "";

            SendAnswer();

            while (!Token.IsCancellationRequested)
            {
                Thread.Sleep(500);
            }

            _answer.Blocks.Clear();
            _answer.Blocks.AddRange(_model.Blocks);

            Context = new DrawableContext();
            SendAnswer();

            return(new FinalAnswer()
            {
                Model = _answer, Price = checker.Solve(_answer)
            });
        }
        public void Search_ShouldReturnExpectedMaxTrips_WithExactStops(string from, string to, int stops, int expectedTrips)
        {
            // Act
            var trips = TripService
                        .Search(Railway.GetTownByName(from), Railway.GetTownByName(to), trip => trip.Stops > stops, trip => trip.Stops == stops);

            // Assert
            Assert.Equal(expectedTrips, trips.Count());
        }
예제 #12
0
        public void ConnectStations_raw_2_Check_last()
        {
            Railway.RailwayParts.Clear();
            var read  = TrackReader.Read(File.ReadAllLines(@"TrainTestTrack.txt"));
            var parts = RailwayPartsORM.Map(read);

            Railway.AppendParts(parts);

            var station = parts[^ 1];
예제 #13
0
파일: RailwayTest.cs 프로젝트: Antash/j4f
        public void IfCrashExistsTest()
        {
            bool actual, expected;
            var  m = new Mesh();

            m.Add(new Line(1, 5, 2));
            m.Add(new Line(5, 7, 5));
            m.Add(new Line(7, 4, 6));
            m.Add(new Line(4, 3, 1));
            m.Add(new Line(4, 6, 8));
            m.Add(new Line(7, 6, 3));
            m.Add(new Line(1, 2, 3));
            m.Add(new Line(3, 2, 3));
            m.Add(new Line(1, 3, 6));
            m.Add(new Line(5, 6, 2));

            Railway target = new Railway(m);

            target.ClearPaths();
            // Scenario 1. Crash happens at the station
            target.AddPath(new uint[] { 1, 5, 7, 4, 3 });
            target.AddPath(new uint[] { 3, 4, 7, 6 });
            target.AddPath(new uint[] { 4, 6, 5, 1, 3 });
            target.AddPath(new uint[] { 2, 1, 3, 4, 7 });

            expected = true;
            actual   = target.IfCrashExists();
            Assert.AreEqual(expected, actual);

            target.ClearPaths();
            // Scenario 2. Crash happens at the line
            target.AddPath(new uint[] { 3, 4, 7, 6 });
            target.AddPath(new uint[] { 4, 6, 7, 5 });
            target.AddPath(new uint[] { 2, 1, 3, 4, 7 });

            actual = target.IfCrashExists();
            Assert.AreEqual(expected, actual);

            target.ClearPaths();
            // Scenario 3.1 There are no crashes
            target.AddPath(new uint[] { 3, 4, 7, 6 });
            target.AddPath(new uint[] { 5, 6, 5, 1, 3 });
            target.AddPath(new uint[] { 2, 1, 3, 4, 7 });

            expected = false;
            actual   = target.IfCrashExists();
            Assert.AreEqual(expected, actual);

            target.ClearPaths();
            // Scenario 3.2 There are no crashes (trans passing same line together)
            target.AddPath(new uint[] { 7, 6, 4, 3 });
            target.AddPath(new uint[] { 5, 6, 4, 7 });

            actual = target.IfCrashExists();
            Assert.AreEqual(expected, actual);
        }
예제 #14
0
        public void ConnectStations_raw_2_test_to_Railway()
        {
            Railway.RailwayParts.Clear();
            var read  = TrackReader.Read(File.ReadAllLines(@"TrainTestTrack.txt"));
            var parts = RailwayPartsORM.Map(read);

            Railway.AppendParts(parts);

            Assert.True(parts.Count == 5);
        }
예제 #15
0
 public ActionResult Edit([Bind(Include = "idRailway,RailwayType,RailwayName")] Railway railway)
 {
     if (ModelState.IsValid)
     {
         db.Entry(railway).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(railway));
 }
예제 #16
0
        List <Edge>[] Construct(IOManager io, int stations, int railwayCount)
        {
            int stationID = stations;
            var railways  = new Railway[railwayCount];
            var graph     = Enumerable.Repeat(0, stations).Select(_ => new List <Edge>()).ToList();

            for (int i = 0; i < railways.Length; i++)
            {
                var p = io.ReadInt() - 1;
                var q = io.ReadInt() - 1;
                var c = io.ReadInt() - 1;
                railways[i] = new Railway(p, q, c);
            }

            Array.Sort(railways);

            var rail = 0;

            for (int co = 0; co < 1_000_000; co++)
            {
                var myStations = new Dictionary <int, int>();
                var myRailways = new List <Railway>();

                while (rail < railways.Length && railways[rail].Company == co)
                {
                    if (!myStations.ContainsKey(railways[rail].From))
                    {
                        myStations.Add(railways[rail].From, stationID++);
                    }
                    if (!myStations.ContainsKey(railways[rail].To))
                    {
                        myStations.Add(railways[rail].To, stationID++);
                    }

                    myRailways.Add(railways[rail++]);
                }

                foreach (var(localID, globalID) in myStations)
                {
                    graph.Add(new List <Edge>());
                    // 乗車(有料)
                    graph[localID].Add(new Edge(globalID, true));
                    // 下車(無料)
                    graph[globalID].Add(new Edge(localID, false));
                }

                foreach (var r in myRailways)
                {
                    graph[myStations[r.From]].Add(new Edge(myStations[r.To], false));
                    graph[myStations[r.To]].Add(new Edge(myStations[r.From], false));
                }
            }

            return(graph.ToArray());
        }
예제 #17
0
        public ActionResult Create([Bind(Include = "idRailway,RailwayType,RailwayName")] Railway railway)
        {
            if (ModelState.IsValid)
            {
                db.Railway.Add(railway);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(railway));
        }
예제 #18
0
        public void ConnectStations_raw_2_CheckStation()
        {
            Railway.RailwayParts.Clear();
            var read  = TrackReader.Read(File.ReadAllLines(@"TrainTestTrack.txt"));
            var parts = RailwayPartsORM.Map(read);

            Railway.AppendParts(parts);

            var station = parts[0];

            Assert.IsType <Station>(station);
        }
        public void GetModelItem_Railway_Test()
        {
            Railway railway = iwSvc.GetModelItem <Railway>(1, "railways", "railways", 16);

            Assert.IsNotNull(railway, "null result, error happens.");
            Assert.AreEqual("16", railway.id);
            Assert.AreEqual(AiwGeometryType.LineString, railway.geometry.Type);
            Assert.IsTrue((railway.geometry as AiwLineString).Coordinates.Length > 0);
            Assert.AreEqual(-122.38800243418041, (railway.geometry as AiwLineString).Coordinates[0].X, 0.001);

            Assert.AreEqual(AiwGeometryType.NoGeometry, railway.model_rotate.Type);
        }
        public void ResolveDistance_WhenRouteDoesNotExists_ShouldThrowInvalidRouteException()
        {
            // Arrange
            var path = new Path();

            path.AddStop(Railway.GetTownByName("A"));
            path.AddStop(Railway.GetTownByName("E"));
            path.AddStop(Railway.GetTownByName("D"));

            // Act and assert
            Assert.Throws <InvalidRouteException>(() => TripService.ResolveDistance(path));
        }
예제 #21
0
        public async Task <IActionResult> PutRailway(int railwayId, Railway railway)
        {
            try
            {
                var result = await _railwayService.PutRailwayAsync(railwayId, railway);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                return(BadRequest("Error: " + ex.Message));
            }
        }
예제 #22
0
        private void ButtonAddClick(object sender, RoutedEventArgs e)
        {
            var railway = new Railway()
            {
                Name          = "British Royal Railways",
                TrainQuantity = 50,
                RailwayLength = 7500,
                StaffNumber   = 120
            };

            railway.Insert();
            FillData();
        }
예제 #23
0
        public static void Main(string[] args)
        {
            // combine validation functions
            var combinedValidation = Railway
                                     // log inpiut request
                                     .Apply <Request> (r => LogRequest(r))
                                     // do email and name validation in parallel and combine errors
                                     .OnSuccess(
                (r1, r2) => r1,
                (e1, e2) => new AggregateException(e1, e2),
                r => ValidateName(r),
                r => ValidateEmail(r)
                )
                                     // extract request name
                                     .OnSuccess(request => request.Name)
                                     // log extracted name
                                     .OnSuccess(name => Console.WriteLine("Name: {0}", name))
                                     // append dash to name
                                     .OnSuccess(name => name + "-")
                                     // log name
                                     .OnSuccess(name => Console.WriteLine("Name: {0}", name))
                                     // make nume uppercase
                                     .OnSuccess(name => name.ToUpper())
                                     // log name
                                     .OnSuccess(name => Console.WriteLine("Name: {0}", name))
                                     // log failure if any occured during the pipeline execution
                                     .OnFailure(e => Console.WriteLine("Failure: {0} ", e.Message));

            // invoke combined function
            var result = combinedValidation(new Request {
                Name = "", Email = ""
            });

            //var result = combinedValidation (new Request { Name = "", Email = "[email protected]" });
            //var result = combinedValidation (new Request { Name = "Kirill", Email = "" });
            //var result = combinedValidation (new Request { Name = "Kirill", Email = "[email protected]" });

            // process result
            switch (result.IsSuccess)
            {
            case true:
                Console.WriteLine("Success. {0}", result.Value);
                break;

            case false:
                Console.WriteLine("Failure: {0}", result.Error);
                break;
            }

            Console.ReadLine();
        }
예제 #24
0
        // GET: Railways/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Railway railway = db.Railway.Find(id);

            if (railway == null)
            {
                return(HttpNotFound());
            }
            return(View(railway));
        }
예제 #25
0
 /// <summary>
 /// Default ctor
 /// </summary>
 private Package(Dictionary <Uri, byte[]> parts)
 {
     this.parts = parts;
     railway    = ReadEntity <Railway>(PackageFolders.Railway, RailwayId);
     if (railway == null)
     {
         railway         = new Railway();
         railway.Package = this;
         railway.Id      = Entity.UniqueId();
         var uri = CreatePartUri(railway.PackageFolder, RailwayId);
         loadedEntities[uri] = railway;
     }
     dirty = false;
 }
        public void ResolveDistance_ShouldReturnDistanceBetweenABC(int expectedDistance, params string[] towns)
        {
            // Arrange
            var path = new Path();

            foreach (var town in towns)
            {
                path.AddStop(Railway.GetTownByName(town));
            }

            // Act
            var actualDistance = TripService.ResolveDistance(path);

            // Assert
            Assert.Equal(expectedDistance, actualDistance);
        }
예제 #27
0
 /// <summary>
 /// Default ctor
 /// </summary>
 private Package(System.IO.Packaging.Package package)
 {
     if (package != null)
     {
         LoadAll(package);
     }
     railway = ReadEntity <Railway>(PackageFolders.Railway, RailwayId);
     if (railway == null)
     {
         railway         = new Railway();
         railway.Package = this;
         railway.Id      = Entity.UniqueId();
         var uri = CreatePartUri(railway.PackageFolder, RailwayId);
         loadedEntities[uri] = railway;
     }
     dirty = false;
 }
예제 #28
0
        public void Test_1_SubTemplate_L6T2R()
        {
            var chain = new RailwayChain(Railway.L3, Railway.L3, Railway.T4R, Railway.T4R);

            var head = new Railway(RailwayType.L0);

            head.Append(chain);

            var destination = new Point(3, 9, -Math.PI / 2);

            var indexes = chain.FindSubTemplate(destination);

            Assert.IsNotNull(indexes);

            Assert.AreEqual(chain[0], indexes?.start);
            Assert.AreEqual(chain[3], indexes?.end);
        }
예제 #29
0
 public Space[] GetSpaces()
 {
     Space[] board = new Space[40];
     board[0]  = new Mechanic("Start");
     board[1]  = new Regular("Mediterranean Avenue", 60, Colours.Brown);
     board[2]  = new Lottery("Community Chest", TypeOfLottery.CommunityChest);
     board[3]  = new Regular("Baltic Avenue", 60, Colours.Brown);
     board[4]  = new Mechanic("Income Tax");
     board[5]  = new Railway("Reading Railroad", 200);
     board[6]  = new Regular("Oriental Avenue", 100, Colours.LightBlue);
     board[7]  = new Lottery("Chance", TypeOfLottery.Chance);
     board[8]  = new Regular("Vermont Avenue", 100, Colours.LightBlue);
     board[9]  = new Regular("Connecticut Avenue", 120, Colours.LightBlue);
     board[10] = new Mechanic("Jail");
     board[11] = new Regular("St. Charles Place", 140, Colours.Purple);
     board[12] = new Utility("Electric Company", 150);
     board[13] = new Regular("States Avenue", 140, Colours.Purple);
     board[14] = new Regular("Virginia Avenue", 160, Colours.Purple);
     board[15] = new Railway("Pennsylvanla Railroad", 200);
     board[16] = new Regular("St. James Place", 180, Colours.Orange);
     board[17] = new Lottery("Community Chest", TypeOfLottery.CommunityChest);
     board[18] = new Regular("Tennessee Avenue", 180, Colours.Orange);
     board[19] = new Regular("New York Avenue", 200, Colours.Orange);
     board[20] = new Mechanic("Free Parking");
     board[21] = new Regular("Kentucky Avenue", 220, Colours.Red);
     board[22] = new Lottery("Chance", TypeOfLottery.Chance);
     board[23] = new Regular("Indiana Avenue", 220, Colours.Red);
     board[24] = new Regular("Illinois Avenue", 240, Colours.Red);
     board[25] = new Railway("B. & O. Railroad", 200);
     board[26] = new Regular("Atlantic Avenue", 260, Colours.Yellow);
     board[27] = new Regular("Ventnor Avenue", 260, Colours.Yellow);
     board[28] = new Utility("Water Work", 150);
     board[29] = new Regular("Marvin Gardens", 280, Colours.Yellow);
     board[30] = new Mechanic("Go To Jail");
     board[31] = new Regular("Pacific Avenue", 300, Colours.Green);
     board[32] = new Regular("North Carolina Avenue", 300, Colours.Green);
     board[33] = new Lottery("Community Chest", TypeOfLottery.CommunityChest);
     board[34] = new Regular("North Carolina Avenue", 320, Colours.Green);
     board[35] = new Railway("Short Line", 200);
     board[36] = new Lottery("Chance", TypeOfLottery.Chance);
     board[37] = new Regular("Park Place", 350, Colours.DarkBlue);
     board[38] = new Mechanic("Luxury Tax");
     board[39] = new Regular("BoardWork", 400, Colours.DarkBlue);
     return(board);
 }
예제 #30
0
 public static Space[] GetDefaultBoard(GameState gameState)
 {
     Space[] board = new Space[40];
     board[0]  = new NoEffectSpace(gameState, "Start");
     board[1]  = new Regular(gameState, "Mediterranean Avenue", 60, Colours.Brown, 2, 10, 30, 90, 160, 250);
     board[2]  = new Lottery(gameState, "Community Chest", TypeOfLottery.CommunityChest);
     board[3]  = new Regular(gameState, "Baltic Avenue", 60, Colours.Brown, 4, 20, 60, 180, 320, 450);
     board[4]  = new Tax(gameState, "Income Tax", TypeOfTax.IncomeTax, 100);
     board[5]  = new Railway(gameState, "Reading Railroad", 200);
     board[6]  = new Regular(gameState, "Oriental Avenue", 100, Colours.LightBlue, 6, 30, 90, 270, 400, 550);
     board[7]  = new Lottery(gameState, "Chance", TypeOfLottery.Chance);
     board[8]  = new Regular(gameState, "Vermont Avenue", 100, Colours.LightBlue, 6, 30, 90, 270, 400, 550);
     board[9]  = new Regular(gameState, "Connecticut Avenue", 120, Colours.LightBlue, 8, 40, 100, 300, 450, 600);
     board[10] = new NoEffectSpace(gameState, "Jail");
     board[11] = new Regular(gameState, "St. Charles Place", 140, Colours.Purple, 10, 50, 150, 450, 625, 750);
     board[12] = new Utility(gameState, "Electric Company", 150);
     board[13] = new Regular(gameState, "States Avenue", 140, Colours.Purple, 10, 50, 150, 450, 625, 750);
     board[14] = new Regular(gameState, "Virginia Avenue", 160, Colours.Purple, 12, 60, 180, 500, 700, 900);
     board[15] = new Railway(gameState, "Pennsylvanla Railroad", 200);
     board[16] = new Regular(gameState, "St. James Place", 180, Colours.Orange, 14, 70, 200, 550, 750, 950);
     board[17] = new Lottery(gameState, "Community Chest", TypeOfLottery.CommunityChest);
     board[18] = new Regular(gameState, "Tennessee Avenue", 180, Colours.Orange, 14, 70, 200, 550, 750, 950);
     board[19] = new Regular(gameState, "New York Avenue", 200, Colours.Orange, 16, 80, 220, 600, 800, 1000);
     board[20] = new NoEffectSpace(gameState, "Free Parking");
     board[21] = new Regular(gameState, "Kentucky Avenue", 220, Colours.Red, 18, 90, 250, 700, 875, 1050);
     board[22] = new Lottery(gameState, "Chance", TypeOfLottery.Chance);
     board[23] = new Regular(gameState, "Indiana Avenue", 220, Colours.Red, 18, 90, 250, 700, 875, 1050);
     board[24] = new Regular(gameState, "Illinois Avenue", 240, Colours.Red, 20, 100, 300, 750, 925, 1100);
     board[25] = new Railway(gameState, "B. & O. Railroad", 200);
     board[26] = new Regular(gameState, "Atlantic Avenue", 260, Colours.Yellow, 22, 110, 330, 800, 975, 1150);
     board[27] = new Regular(gameState, "Ventnor Avenue", 260, Colours.Yellow, 22, 110, 330, 800, 975, 1150);
     board[28] = new Utility(gameState, "Water Work", 150);
     board[29] = new Regular(gameState, "Marvin Gardens", 280, Colours.Yellow, 24, 120, 360, 850, 1025, 1200);
     board[30] = new GoToJail(gameState, "Go To Jail");
     board[31] = new Regular(gameState, "Pacific Avenue", 300, Colours.Green, 26, 130, 390, 900, 1100, 1275);
     board[32] = new Regular(gameState, "North Carolina Avenue", 300, Colours.Green, 26, 130, 390, 900, 1100, 1275);
     board[33] = new Lottery(gameState, "Community Chest", TypeOfLottery.CommunityChest);
     board[34] = new Regular(gameState, "North Carolina Avenue", 320, Colours.Green, 28, 150, 450, 1000, 1200, 1400);
     board[35] = new Railway(gameState, "Short Line", 200);
     board[36] = new Lottery(gameState, "Chance", TypeOfLottery.Chance);
     board[37] = new Regular(gameState, "Park Place", 350, Colours.DarkBlue, 35, 175, 500, 1100, 1300, 1500);
     board[38] = new Tax(gameState, "Luxury Tax", TypeOfTax.LuxuryTax, 100);
     board[39] = new Regular(gameState, "BoardWork", 400, Colours.DarkBlue, 50, 200, 600, 1400, 1700, 2000);
     return(board);
 }