Ejemplo n.º 1
0
    public IEnumerable <Tile> GetChain(int range, CostCalculator cost, ChainInfo.IgnoreCondition ignoreCond)
    {
        if (range >= 0)
        {
            if (ignoreCond == null || (ignoreCond != null && !ignoreCond(this)))
            {
                yield return(this);
            }

            var closedTiles = this.GetClosedTiles();

            range = range - 1;

            foreach (var closedTile in closedTiles)
            {
                if (closedTile != null)
                {
                    int rangeWithCost = range;

                    if (cost != null)
                    {
                        rangeWithCost -= cost.Calc(closedTile);
                    }

                    foreach (var recTile in closedTile.GetChain(rangeWithCost, cost, ignoreCond))
                    {
                        yield return(recTile);
                    }
                }
            }
        }
    }
Ejemplo n.º 2
0
        public void Should_Use_ExtendedPriceRules_When_Applies_To_Is_True()
        {
            var expectedPrice = 10;
            var validRuleMock = new Mock <IExtendedPriceRule>();

            validRuleMock.Setup(x => x.RuleName).Returns("ValidRule").Verifiable();
            validRuleMock.Setup(x => x.AppliesTo(It.Is <MessageForProcessing>((msg) => msg.Text == message.Text)))
            .Returns(true)
            .Verifiable();
            validRuleMock.Setup(x => x.Apply(It.Is <MessageForProcessing>((msg) => msg.Text == message.Text)))
            .Returns(expectedPrice)
            .Verifiable();
            extPriceRules.Add(validRuleMock.Object);

            var invalidRuleMock = new Mock <IExtendedPriceRule>();

            invalidRuleMock.Setup(x => x.RuleName).Returns("InvalidRule").Verifiable();
            invalidRuleMock.Setup(x => x.AppliesTo(It.Is <MessageForProcessing>((msg) => msg.Text == message.Text)))
            .Returns(false);
            extPriceRules.Add(invalidRuleMock.Object);

            var sut    = new CostCalculator(basePriceRules, extPriceRules, _logger);
            var result = sut.CalculatePrice(message.Text);

            Assert.IsTrue(result == expectedPrice);
            validRuleMock.VerifyAll();
            invalidRuleMock.Verify(x => x.RuleName, Times.Never);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Final Cost Settings
        /// </summary>
        /// <returns></returns>
        public Boolean SetFinalCost()
        {
            var GRV = new CostCalculator();

            GRV.LoadGRV(ReceiptID);
            GRV.CalculateFinalCost();
            foreach (DataRowView drv in GRV.GRVSoundDetail.DefaultView)
            {
                double NewUnitCost, NewSellingPrice;
                NewUnitCost = Math.Round(Convert.ToDouble(drv["AverageCost"]),
                                         BLL.Settings.NoOfDigitsAfterTheDecimalPoint);
                NewSellingPrice = Math.Round(Convert.ToDouble(drv["SellingPrice"]),
                                             BLL.Settings.NoOfDigitsAfterTheDecimalPoint);
                var sellingPriceForm = new SellingPricePage(ReceiptID, Convert.ToInt32(drv["ItemID"]),
                                                            Convert.ToInt32(drv["ManufacturerID"]),
                                                            Convert.ToInt32(drv["ItemUnitID"]),
                                                            Convert.ToInt32(drv["AccountID"]), NewUnitCost,
                                                            NewSellingPrice);
                if (sellingPriceForm.ShowDialog(this) == DialogResult.Cancel)
                {
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 4
0
        static void GetNextDeparture()
        {
            Console.WriteLine("Press a key to get next departure. Terminate with '.' key.");
            Console.WriteLine("Press 'c' for cache or press 'd' for DB retreival.");
            char key;

            while ((key = Console.ReadKey().KeyChar).CompareTo('.') != 0)
            {
                if (key.CompareTo('d') == 0)
                {
                    Console.Write("Getting next departure from DB...");
                    var stopwatch = new Stopwatch();

                    stopwatch.Start();
                    CostCalculator.GetNextDeparture();
                    stopwatch.Stop();

                    Console.WriteLine("\t Idő: " + (stopwatch.ElapsedMilliseconds / 1000.0) + "s");
                }
                else if (key.CompareTo('c') == 0)
                {
                    Console.Write("Getting next departure from cache...");
                    var stopwatch = new Stopwatch();

                    stopwatch.Start();
                    CostCalculator.GetNextDepartureFromCache();
                    stopwatch.Stop();

                    Console.WriteLine("\t Idő: " + (stopwatch.ElapsedMilliseconds / 1000.0) + "s");
                }
            }
        }
Ejemplo n.º 5
0
        public async Task <ActionResult> EndRental(int rentalId)
        {
            Rental rentToEnd = _context.Rentals.Include(r => r.Bike).ToList().FirstOrDefault(r => r.RentalId == rentalId);

            if (rentToEnd == null)
            {
                return(StatusCode(404, "The rental could not be found."));
            }

            // Check if it was already ended
            if (rentToEnd.RentalEnd != DateTime.MinValue)
            {
                return(StatusCode(400, "The rental has already been ended."));
            }

            // Assign the values
            rentToEnd.RentalEnd = DateTime.Now;
            CostCalculator costCalculator = new CostCalculator();

            rentToEnd.Total = costCalculator.CalculateTotalCost(rentToEnd);

            _context.SaveChanges();

            return(StatusCode(200, rentToEnd));
        }
Ejemplo n.º 6
0
        public void Should_DebugLog_RuleName()
        {
            var expectedPrice = 10;
            var ruleName      = "Valid Rule is Awesome";
            var validRuleMock = new Mock <IExtendedPriceRule>();

            validRuleMock.Setup(x => x.RuleName).Returns(ruleName).Verifiable();
            validRuleMock.Setup(x => x.AppliesTo(It.Is <MessageForProcessing>((msg) => msg.Text == message.Text)))
            .Returns(true)
            .Verifiable();
            validRuleMock.Setup(x => x.Apply(It.Is <MessageForProcessing>((msg) => msg.Text == message.Text)))
            .Returns(expectedPrice)
            .Verifiable();
            extPriceRules.Add(validRuleMock.Object);

            var logMock = new Mock <IAppLogger>();

            logMock.Setup(x => x.Debug(It.Is <string>((str) => str.Contains(ruleName)))).Verifiable();

            var sut    = new CostCalculator(basePriceRules, extPriceRules, logMock.Object);
            var result = sut.CalculatePrice(message.Text);

            Assert.IsTrue(result == expectedPrice);
            validRuleMock.VerifyAll();
            logMock.VerifyAll();
        }
Ejemplo n.º 7
0
        public PartialViewResult ChangeClientAccount(ChangeClientAccountModel model)
        {
            bool isOperationValid = true;

            if (model.Id.HasValue && ModelState.IsValid) //Счет должен быть известен, без вариантов
            {
                // Получаем Id клиента по Id его счета
                long?clientId = ClientAccountRepo.GetClientIdByAccountId(model.Id.Value);

                // Еще раз делаем проверку - является ли клиент дилером и не изменяет свой счет.
                if (clientId.HasValue && ValidateAccountChangeAction(clientId.Value))
                {
                    ChangeClientAccountModel emptyModel = GetClientAccountChangeModel(clientId.Value);
                    if (emptyModel != null) //Только если мы точно уверены в Id счета и легитимности его изменения
                    {
                        CostCalculator calc = new CostCalculator(model.CalcMode);
                        calc.RecalcModel(model);
                        isOperationValid = ClientAccountRepo.ChangeAccount(model);
                        if (isOperationValid)
                        {
                            model = emptyModel;
                            ViewData.Add("AccountUpdated", true);
                        }
                    }
                }
            }
            return(PartialView("ChangeClientAccount", model));
        }
Ejemplo n.º 8
0
        public RouteEdge(int toStopId, int routeId, DateTime date, TimeSpan time, int?cost = null)
        {
            _toStopId = toStopId;
            _routeId  = routeId;
            _date     = date;
            _time     = time;

            if (cost != null)
            {
                _cost = cost;
            }
            else
            {
                var when = new DateTime(_date.Year, _date.Month, _date.Day, _time.Hours, _time.Minutes, _time.Seconds);
                var dep  = CostCalculator.GetNextDeparture(when, _routeId, _toStopId);

                if (dep == null)
                {
                    _cost = null;
                }
                else
                {
                    _cost = (int)(((TimeSpan)(dep - when.TimeOfDay)).TotalMinutes);
                }
            }
        }
 public CostCalculatorTests()
 {
     holidayServiceMock = new Mock <IHolidayService>();
     sut         = new CostCalculator(Context, holidayServiceMock.Object);
     HolidayRate = CostCalculator.HolidayRate;
     WeekendRate = CostCalculator.WeekendRate;
 }
Ejemplo n.º 10
0
        public void CostLessThanMinimumCost()
        {
            CostCalculator    costCalculator    = new CostCalculator(30, 5);
            DistanceTravelled distanceTravelled = new DistanceTravelled(5);

            Assert.Equal(30, costCalculator.CalculatingCost(distanceTravelled));
        }
Ejemplo n.º 11
0
 public HomeController(
     IRepository <Stack> stackRepository,
     IRepository <AwsProfile> profileRepository,
     IRepository <Product> productRepository,
     IRepository <Instance> instanceRepository,
     IRepository <Schedule> scheduleRepository,
     IBackgroundJobClient backgroundJobClient,
     IMappingEngine mappingEngine,
     IOwinContext owinContext,
     INumberedStringGenerator numberedStringGenerator,
     IUserProfileAccessManager userProfileAccessManager,
     IStackItConfiguration stackItConfiguration,
     CostCalculator costCalculator,
     IStackViewModelHelper stackViewModelHelper)
 {
     _stackRepository     = stackRepository;
     _profileRepository   = profileRepository;
     _productRepository   = productRepository;
     _instanceRepository  = instanceRepository;
     _scheduleRepository  = scheduleRepository;
     _backgroundJobClient = backgroundJobClient;
     _mapper                   = mappingEngine;
     _owinContext              = owinContext;
     _numberedStringGenerator  = numberedStringGenerator;
     _userProfileAccessManager = userProfileAccessManager;
     _stackItConfiguration     = stackItConfiguration;
     _costCalculator           = costCalculator;
     _stackViewModelHelper     = stackViewModelHelper;
 }
Ejemplo n.º 12
0
    static void Init()
    {
        // Get existing open window or if none, make a new one:
        CostCalculator window = (CostCalculator)EditorWindow.GetWindow(typeof(CostCalculator));

        window.Show();
    }
Ejemplo n.º 13
0
 public ChainInfo(IgnoreCondition ignoreCond, CostCalculator cost = null)
 {
     this.RootObj         = null;
     this.ActiveTileImage = string.Empty;
     this.IgnoreCond      = ignoreCond;
     this.Cost            = cost;
 }
Ejemplo n.º 14
0
        public void StandardDiscount_Returns(decimal originalAmount, decimal finalAmount)
        {
            var sut = new CostCalculator();

            var result = sut.ApplyDiscount(originalAmount);

            Assert.AreEqual(finalAmount, result);
        }
        public void _should_price_Zero_if_no_rules_included()
        {
            var sut    = new CostCalculator(new List <IBasePriceRule>(), new List <IExtendedPriceRule>(), _loggerMock.Object);
            var result = sut.CalculatePrice(message);

            //result.ShouldEqual<int>(0);
            Assert.AreEqual <int>(0, result);
        }
        public void SetUp()
        {
            Startup.ConfigureAutomapper();
            StackRepository = new Mock <IRepository <Stack> >();
            var costCalculator = new CostCalculator(new Mock <IRepository <Instance> >().Object, new Mock <IRepository <ResourceLedger> >().Object);

            HomeController = new HomeController(StackRepository.Object, null, null, null, null, null, Mapper.Engine, null, null, null, null, costCalculator, null);
        }
Ejemplo n.º 17
0
 public static void initDatabase(string BasePath, string appHomeDir = "")
 {
     if (GtfsDatabase.initDatabase(BasePath))
     {
         GraphTransformer.CreateStopGroups(200);
         GraphBuilder.BuildGraph();
         CostCalculator.CreateTimetableCache(appHomeDir);
     }
 }
        public void GenerateAndSortCollectionOfEstimates_GivenInputOfCustomerTransaction(string scenario, CostCalculatorTheoryData theory)
        {
            // Arrange + Act
            var actual = CostCalculator.EstimateTransactionCost(theory.Input);

            // Assert
            actual.Should().NotBeNull();
            actual.Should().BeEquivalentTo(theory.Estimates, because: scenario);
            actual.TicketEstimates.Should().BeInAscendingOrder(x => x.TicketType);
        }
Ejemplo n.º 19
0
        static void CreateTimetableCache()
        {
            Console.WriteLine("Creating timetable cache...");
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            CostCalculator.CreateTimetableCache();
            stopwatch.Stop();

            Console.WriteLine("\t Idő: " + (stopwatch.ElapsedMilliseconds / 1000.0) + "s");
        }
        public void _should_determine_weight_based_on_message_length()
        {
            var shouldBe1 = "1";
            var shouldBe2 = "12";
            var shouldBe3 = "123";
            var shouldBe4 = "1234";

            Assert.AreEqual <int>(1, CostCalculator.CalculateWeight(shouldBe1));
            Assert.AreEqual <int>(2, CostCalculator.CalculateWeight(shouldBe2));
            Assert.AreEqual <int>(3, CostCalculator.CalculateWeight(shouldBe3));
            Assert.AreEqual <int>(4, CostCalculator.CalculateWeight(shouldBe4));
        }
        public void CalculateCost()
        {
            // prepare
            var c = new CostCalculator();

            // execute
            var calc0 = c.Calculate(DateTime.Now, DateTime.Now.AddMinutes(1), 1, 2);
            var calc3 = c.Calculate(DateTime.Now, DateTime.Now.AddHours(1).AddMinutes(1), 1, 2);

            // assertions
            Assert.Equal(0, calc0);
            Assert.Equal(3, calc3);
        }
        public void Calculate135Minutes()
        {
            CostCalculator costCalculator = new CostCalculator();
            Bike           bike           = new Bike()
            {
                BikeId = 0, Brand = "", BikeCategory = "Mountainbike", PurchaseDate = DateTime.Now, RentalPriceFirstHour = 10, RentalPriceAdditionalHour = 15
            };
            Rental rental = new Rental()
            {
                Bike = bike, RentalBegin = DateTime.Now, RentalEnd = DateTime.Now.AddMinutes(135)
            };

            var result = costCalculator.CalculateTotalCost(rental);

            Assert.Equal(40, result);
        }
        private void LoadSelectedGRVDetailForUnitCostCalculation(int ReceiptID)
        {
            // if The Flow is correct Calculate the Cost Coeff and all information on the Previous Tab

            gridCostBuild.DataSource = GRV.GetCostBuildUp();

            //Display Correct Tab
            selectTab = grpTabUnitCost;
            FocusOnSelectedTab();

            // Load the GRV First
            GRV = new CostCalculator();
            GRV.LoadGRV(ReceiptID);
            GRV.SuspendFromIssuing();
            gridUnitCost.DataSource = GRV.GRVDetail;
        }
Ejemplo n.º 24
0
        public void TestCase()
        {
            // Arrange
            var fixtya = new Fixtya();
            fixtya.Use(@"Fixtures/ShoppingBasket.yaml");
            var shoppingBasket = fixtya.Get<ShoppingBasket>("Test");
            CostCalculator calculator = new CostCalculator(shoppingBasket);
            var expected = 13.29M;
            decimal actual = 0;

            // Act
            actual = calculator.Calculate();

            // Assert
            Assert.AreEqual (expected, actual);
        }
Ejemplo n.º 25
0
        public SendResponse Send(string message)
        {
            CostCalculator calc   = new CostCalculator();
            Sender         sender = new Sender();

            var price = calc.CalculatePrice(message);

            sender.Send(message);

            return(new SendResponse()
            {
                Message = message,
                Price = price,
                ResultMessage = "success"
            });
        }
Ejemplo n.º 26
0
        public void TestCalculationOfRentalPrice()
        {
            ICostCalculator calculator = new CostCalculator();

            var price = calculator.Calculate(new DateTime(2019, 2, 14, 8, 15, 0), new DateTime(2019, 2, 14, 10, 30, 0), 3, 5);

            Assert.Equal(13, price);

            price = calculator.Calculate(new DateTime(2018, 2, 14, 8, 15, 0), new DateTime(2018, 2, 14, 8, 45, 0), 3, 100);
            Assert.Equal(3, price);

            price = calculator.Calculate(new DateTime(2018, 2, 14, 8, 15, 0), new DateTime(2018, 2, 14, 8, 25, 0), 20, 100);
            Assert.Equal(0, price);

            Assert.Throws <InvalidDurationException>(() => calculator.Calculate(new DateTime(2019, 2, 14, 10, 30, 0), new DateTime(2018, 2, 14, 10, 30, 0), 3, 5));
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            String  collegeName;
            Boolean addRoom;
            decimal cost;

            Console.WriteLine("Enter the name of the college to find its annual cost: ");
            collegeName = Console.ReadLine();
            Console.WriteLine("Add room and board to the total cost (true or false): ");
            addRoom = Console.ReadLine().CompareTo("false") != 0;

            cost = CostCalculator.determineCost(collegeName, "college_costs.csv", addRoom);

            Console.WriteLine("Total cost: $" + cost + " dollars. Press any key to exit.");
            Console.ReadKey();
        }
        private void LoadSelectedGRVDetailForInvoiceEntry(int ReceiptID)
        {
            //Display Correct Tab
            selectTab = grpTabInvoiceValue;
            FocusOnSelectedTab();

            // Load The GRV First
            GRV = new CostCalculator();
            GRV.LoadGRV(ReceiptID);
            // Display the GRV Detail for Data Entry(Price Per Pack)
            gridInvoiceDetail.DataSource = GRV.GRVDetail;

            //Load Summary
            txtSubTotal.EditValue   = GRV.SubTotal;
            txtInsurance.EditValue  = GRV.Insurance;
            txtGrandTotal.EditValue = GRV.GrandTotal;
        }
Ejemplo n.º 29
0
 public SquadOption(string _name, string _desc, int _cost, int _optionLimit, Option _implement, Option _deimplement, CostCalculator _ccalc, params Tag[] _tags)
 {
     name           = _name;
     desc           = _desc;
     implement      = _implement;
     deimplement    = _deimplement;
     isActive       = false;
     baseCost       = _cost;
     optionLimit    = _optionLimit;
     optionNum      = 0;
     costCalculator = _ccalc;
     tags           = new List <Tag>();
     foreach (var entry in _tags)
     {
         tags.Add(entry);
     }
 }
        public static void Main(string[] args)
        {
            try
            {
                string input        = File.ReadAllText($"{AppDomain.CurrentDomain.BaseDirectory}/transactions.json");
                var    transactions = JsonConvert.DeserializeObject <List <Transaction> >(input);

                foreach (var txn in transactions)
                {
                    var estimate = CostCalculator.EstimateTransactionCost(txn);
                    WriteLine(estimate);
                }
            }
            catch (Exception ex)
            {
                WriteLine($"Fatal error, unable to process input. Exiting... | {ex.GetType()} {ex.Message}");
            }
        }
Ejemplo n.º 31
0
        static SuperApplicationConsoleApp AppComposite()
        {
            IEncryptHelper crypto = new nope.Lib.Encryptor();

            external.ILogger logger   = new external.Logger();                   // Not singleton
            IAppLogger       myLogger = new ExternalLogAdapter(logger);
            IMessageSender   sender   = new FedExSender(crypto, myLogger);

            var basePriceRules = getBasePriceRules();
            var extPriceRules  = getExtendedPriceRules();

            ICostCalculator  calc      = new CostCalculator(basePriceRules, extPriceRules, myLogger);
            ISendingMicroApp senderApp = new SuperSendingMicroApp(calc, sender, myLogger);

            IConsole writer = new ConsoleWriter();

            return(new SuperApplicationConsoleApp(senderApp, writer));
        }
Ejemplo n.º 32
0
 public void SetUp()
 {
     subject = new CostCalculator();
 }
Ejemplo n.º 33
0
 public void Setup()
 {
     this.costCalculator = new CostCalculator();
 }
Ejemplo n.º 34
0
 public void CostIsCalculated(decimal price, int quantity, decimal expected)
 {
     var cost = new CostCalculator().CalculateCost(quantity, price);
     cost.Should().Be(expected);
 }
Ejemplo n.º 35
0
 public ShoppingCart( CostCalculator calculator)
 {
     list_of_products = new Dictionary<Product, int>();
     cost_calculator = calculator;
 }
Ejemplo n.º 36
0
 private void buttonCostCalculator_Click(object sender, EventArgs e)
 {
     CostCalculator costCalc = new CostCalculator();
     costCalc.Show();
 }