static DistanceCalculator() { var calculator = new DistanceCalculator(); var distanceData = new DistanceData { DistanceM = 1, Calc = "kilometers" }; calculator.Calculate(distanceData); MilesToKilometers = distanceData.DistanceKm.Value; distanceData.DistanceKm = 1; distanceData.Calc = "miles"; calculator.Calculate(distanceData); KilometersToMiles = distanceData.DistanceM.Value; }
public virtual async Task <IList <CityEntity> > GetCitiesAsync(int cityId) { var cityE = await CityRepository.FindAsync(cityId) ?? throw new EntityNotFoundException(); var radius = Config.GetValue <float>("GeoDistance:MaxRadius"); if (radius <= 0) { throw new BusinessException(); } var point01 = GetPoint(cityE.Geolocation); var selectedList = new List <CityEntity>(); var cityEsList = await CityRepository.GetListAsync(); foreach (var cityEntity in cityEsList) { var point02 = GetPoint(cityEntity.Geolocation); var distance = DistanceCalculator.Calculate(point01, point02); if (distance <= radius) { selectedList.Add(cityEntity); } } return(selectedList); }
IEnumerator GPSChecker() { int counter = 0; for (;;) { Info.text = Input.location.status.ToString() + " " + counter.ToString(); counter++; //if (Input.location.status == LocationServiceStatus.Running) { //Info.text = Input.location.status.ToString (); lat = Input.location.lastData.latitude; lon = Input.location.lastData.longitude; SetClosestHeritage(); distance = DistanceCalculator.Calculate( lat, lon, heritages.WarsawHeritage [heritages.activeOne].position.x, heritages.WarsawHeritage [heritages.activeOne].position.y) * 1000f; Latitude.text = "Lat: " + lat.ToString(); Longitude.text = "Lon: " + lon.ToString(); Distance.text = "Dist: " + distance.ToString(); funPlacer.Place(this); yield return(new WaitForSeconds(1)); //} } }
public Distance(double distance, DistanceUnits units) { var calculator = new DistanceCalculator(); var distanceData = new DistanceData { DistanceM = distance, DistanceKm = distance }; switch (units) { case DistanceUnits.Miles: distanceData.Calc = "kilometers"; break; case DistanceUnits.Kilometers: distanceData.Calc = "miles"; break; default: throw new ArgumentException("Unknown units: " + units, "units"); } calculator.Calculate(distanceData); DistanceInM = distanceData.DistanceM.Value; DistanceInKm = distanceData.DistanceKm.Value; BaseDistance = distance; BaseUnits = units; }
/// <summary> /// The build route settings. /// </summary> /// <param name="calc"> /// The calc. /// </param> /// <param name="fleetToStore"> /// The fleet to store. /// </param> /// <param name="storeToClient"> /// The store to client. /// </param> /// <param name="distanceToClient"> /// The distance to client. /// </param> /// <returns> /// The <see cref="RouteSettings"/>. /// </returns> public static RouteSettings BuildRouteSettings( DistanceCalculator calc, RouteDistance fleetToStore, RouteDistance storeToClient, double distanceToClient) { var result = new RouteSettings(); result.ClientLocation = storeToClient.LocationToAddress; result.StoreLocation = storeToClient.LocationFromAddress; result.DroneLocation = fleetToStore.LocationFromAddress; result.DistanceToClient = distanceToClient; result.DroneFlyDistance = result.DistanceToClient + calc.Calculate( result.ClientLocation.Coordinates, result.DroneLocation.Coordinates); result.ClientWaitingTimeSec = (result.DistanceToClient * 1000) / 16.6667d; result.DroneFlyTimeSec = (result.DroneFlyDistance * 1000) / 16.6667d; result.ClientWaitingTimeMin = result.ClientWaitingTimeSec / 60; result.DroneFlyTimeMin = result.DroneFlyTimeSec / 60; return(result); }
public void GivenCalculator_WhenCalculatingAndSolutionConvergesWithHeightAboveScreenHeightDuringNormalTakeOff_ThenCallsInExpectedOrderAndThrowsCalculatorException() { // Given var random = new Random(21); const double screenHeight = 10.7; int nrOfTimeSteps = random.Next(2, int.MaxValue); double timeStep = random.NextDouble(); int failureSpeed = random.Next(); AircraftState[] states = { CreateAircraftStateWithHeight(screenHeight - 0.1), CreateAircraftStateWithHeight(screenHeight + 0.1), CreateAircraftStateWithHeight(screenHeight + 0.2) }; AircraftAccelerations[] accelerations = { CreateAircraftAccelerations(), CreateAircraftAccelerations() }; var normalTakeOffDynamicsCalculator = Substitute.For <INormalTakeOffDynamicsCalculator>(); normalTakeOffDynamicsCalculator.Calculate(Arg.Any <AircraftState>()) .Returns(accelerations[0], accelerations[1]); var failureTakeOffDynamicsCalculator = Substitute.For <IFailureTakeOffDynamicsCalculator>(); var integrator = Substitute.For <IIntegrator>(); integrator.Integrate(Arg.Any <AircraftState>(), Arg.Any <AircraftAccelerations>(), timeStep) .Returns(states[0], states[1], states[2]); var calculatorSettings = new CalculationSettings(failureSpeed, nrOfTimeSteps, timeStep); var calculator = new DistanceCalculator(normalTakeOffDynamicsCalculator, failureTakeOffDynamicsCalculator, integrator, calculatorSettings); // When TestDelegate call = () => calculator.Calculate(); // Then var exception = Assert.Throws <CalculatorException>(call); Assert.AreEqual("Calculation converged before failure occurred.", exception.Message); failureTakeOffDynamicsCalculator.DidNotReceiveWithAnyArgs().Calculate(Arg.Any <AircraftState>()); normalTakeOffDynamicsCalculator.Received(2).Calculate(Arg.Any <AircraftState>()); integrator.Received(2).Integrate(Arg.Any <AircraftState>(), Arg.Any <AircraftAccelerations>(), timeStep); Received.InOrder(() => { normalTakeOffDynamicsCalculator.Calculate(Arg.Is <AircraftState>(state => IsZeroAircraftState(state))); integrator.Integrate(Arg.Is <AircraftState>(state => IsZeroAircraftState(state)), accelerations[0], timeStep); normalTakeOffDynamicsCalculator.Calculate(states[0]); integrator.Integrate(states[0], accelerations[1], timeStep); // Do not expect additional calls after the second state was returned }); }
public void Calculate_NormalDynamicsCalculatorThrowsException_ThenExceptionRethrown() { // Setup var calculatorException = new CalculatorException(); var normalTakeOffDynamicsCalculator = Substitute.For <INormalTakeOffDynamicsCalculator>(); normalTakeOffDynamicsCalculator.Calculate(Arg.Any <AircraftState>()) .Throws(calculatorException); var failureTakeOffDynamicsCalculator = Substitute.For <IFailureTakeOffDynamicsCalculator>(); var integrator = Substitute.For <IIntegrator>(); var calculator = new DistanceCalculator(normalTakeOffDynamicsCalculator, failureTakeOffDynamicsCalculator, integrator, CalculationSettingsTestFactory.CreateDistanceCalculatorSettings()); // Call TestDelegate call = () => calculator.Calculate(); // Assert var exception = Assert.Throws <CalculatorException>(call); Assert.AreSame(calculatorException, exception); }
public void Valid_Distance_For_A_Path(string path, int expected) { var distanceCalculator = new DistanceCalculator(Map); var actual = distanceCalculator.Calculate(path); Assert.AreEqual(expected, actual); }
private double?CalculateDistance(double?originLatitude, double?originLongitude, double?destinationLatitude, double?destinationLongitude) { if (originLatitude.HasValue && originLongitude.HasValue && destinationLatitude.HasValue && destinationLongitude.HasValue) { return(Math.Round(DistanceCalculator.Calculate(originLatitude.Value, originLongitude.Value, destinationLatitude.Value, destinationLongitude.Value, 'K'), 2)); } else { return(null); } }
public ActionResult CalcDistance(DistanceData distanceCalculation) { if (!ModelState.IsValid) { return(Json(distanceCalculation)); } distanceCalc.Calculate(distanceCalculation); return(Json(distanceCalculation)); }
public void TEST_CALCULATE_DISTANCE_THROWS_EXCEPTION_WHEN_COORDINATES_ARE_NULL() { Exception expectedExp = null; var service = new DistanceCalculator(); try { service.Calculate(null, null); } catch (AssertFailedException ex) { expectedExp = ex; } Assert.IsNotNull(expectedExp); }
static void Main() { Point3D p = Point3D.StartPoint; Point3D q = new Point3D(1, 2, 3); System.Console.WriteLine("Distance: {0:F4}", DistanceCalculator.Calculate(p, q)); Path path = new Path(); path.AddPoints(p, q); System.Console.WriteLine(path); PathStorage.Save(path, "firstPath"); System.Console.WriteLine(PathStorage.Load("firstPath")); System.Console.WriteLine(PathStorage.Load("somePath")); }
static void Main(string[] args) { //////////////////////---HERE STARTS PROBLEM 1---////////////////////////// Console.WriteLine(); Console.WriteLine("---HERE STARTS PROBLEM 1---"); Point3D p1 = new Point3D(1, 2, 3); p1.ToString(); Point3D p2 = Point3D.StartingPoint; //////////////////////---HERE STARTS PROBLEM 2---////////////////////////// Console.WriteLine(); Console.WriteLine("---HERE STARTS PROBLEM 2---"); double d1 = DistanceCalculator.Calculate(p1, p2); Point3D p3 = new Point3D(5, 2, 99); double d2 = DistanceCalculator.Calculate(p1, p3); Console.WriteLine(d1 + " " + d2); }
public void Verify_DistanceIsAccuratelyCalculatedBetweenTwoLocations() { double expectedDistance = 10.57; var location1 = new GPSLocation { Longitude = -6.257664, Latitude = 53.339428 }; var location2 = new GPSLocation { Longitude = -6.238335, Latitude = 53.2451022 }; double actualDistance = DistanceCalculator.Calculate(location1, location2); Assert.Equal(expectedDistance, actualDistance, 2); }
public void TEST_CALCULATE_DISTANCE_RETURNS_DISTANCE() { var expected = 0; var service = new DistanceCalculator(); var source = new Coordinates { latitude = 10 , longitude = 10 }; var destination = new Coordinates { latitude = 10 , longitude = 10 }; var actual = service.Calculate(source, destination); Assert.AreEqual(expected, actual); }
public void Calculate_MaximumIterationsHit_ThrowsCalculatorException() { // Setup var random = new Random(21); int nrOfTimeSteps = random.Next(1, 10); double timeStep = random.NextDouble(); int failureSpeed = random.Next(); var normalTakeOffDynamicsCalculator = Substitute.For <INormalTakeOffDynamicsCalculator>(); var calculatorException = new CalculatorException(); var failureTakeOffDynamicsCalculator = Substitute.For <IFailureTakeOffDynamicsCalculator>(); failureTakeOffDynamicsCalculator.Calculate(Arg.Any <AircraftState>()) .Throws(calculatorException); var integrator = Substitute.For <IIntegrator>(); integrator.Integrate(Arg.Any <AircraftState>(), Arg.Any <AircraftAccelerations>(), timeStep) .Returns(CreateAircraftStateWithVelocity(failureSpeed)); var calculatorSettings = new CalculationSettings(failureSpeed, nrOfTimeSteps, timeStep); var calculator = new DistanceCalculator(normalTakeOffDynamicsCalculator, failureTakeOffDynamicsCalculator, integrator, calculatorSettings); // Call TestDelegate call = () => calculator.Calculate(); // Assert var exception = Assert.Throws <CalculatorException>(call); Assert.AreEqual("Calculation did not converge.", exception.Message); integrator.ReceivedWithAnyArgs(nrOfTimeSteps) .Integrate(Arg.Any <AircraftState>(), Arg.Any <AircraftAccelerations>(), timeStep); }
public void Calculate_FailureDynamicsCalculatorThrowsException_ThenExceptionRethrown() { // Setup var random = new Random(21); double timeStep = random.NextDouble(); int failureSpeed = random.Next(); var normalTakeOffDynamicsCalculator = Substitute.For <INormalTakeOffDynamicsCalculator>(); var calculatorException = new CalculatorException(); var failureTakeOffDynamicsCalculator = Substitute.For <IFailureTakeOffDynamicsCalculator>(); failureTakeOffDynamicsCalculator.Calculate(Arg.Any <AircraftState>()) .Throws(calculatorException); var integrator = Substitute.For <IIntegrator>(); integrator.Integrate(Arg.Any <AircraftState>(), Arg.Any <AircraftAccelerations>(), timeStep) .Returns(CreateAircraftStateWithVelocity(failureSpeed + 0.1)); var calculatorSettings = new CalculationSettings(failureSpeed, random.Next(), timeStep); var calculator = new DistanceCalculator(normalTakeOffDynamicsCalculator, failureTakeOffDynamicsCalculator, integrator, calculatorSettings); // Call TestDelegate call = () => calculator.Calculate(); // Assert var exception = Assert.Throws <CalculatorException>(call); Assert.AreSame(calculatorException, exception); }
public async Task <IActionResult> GetForAll() { // get stores var stores = this.storeFinder.GetStoresToServe().ToList(); var fleets = this.droneService.GetDroneFleets().ToList(); var clientAddresses = await this.locationFinder.GetAllClientLocationAsync(); var result = new List <RouteSettings>(); if (!stores.AnySafe() || !fleets.AnySafe() || !clientAddresses.AnySafe()) { return(null); } var calc = new DistanceCalculator(); var fleetStoreDistanceArr = new List <List <double> >(); var line = new LinkedList <double>(); foreach (var fleet in fleets) { line.Clear(); foreach (var store in stores) { line.AddLast(calc.Calculate(fleet.Coordinates, store.Coordinates)); } fleetStoreDistanceArr.Add(line.ToList()); } var ways = new List <BestWay>(); var distance = new List <double>(); var bestWay = new BestWay(); foreach (var client in clientAddresses) { distance.Clear(); foreach (var store in stores) { distance.Add(calc.Calculate(client.Coordinates, store.Coordinates)); } bestWay = new BestWay { Distance = double.MaxValue, FleetIndex = 0, StoreIndex = 0, Client = client }; var availableDrones = await this.droneService.GetAvailableDronesAsync(); for (var i = 0; i < fleetStoreDistanceArr.Count; i++) { // for loop bellow fleetStoreDistanceArr line length will be the same for all lines, // so we don't need to calculate it for every line for (var j = 0; j < fleetStoreDistanceArr[0].Count; j++) { if (availableDrones.Any( x => x.AddressLine.Equals( fleets[i].AddressLine, StringComparison.InvariantCultureIgnoreCase))) { if (fleetStoreDistanceArr[i][j] + distance[j] < bestWay.Distance) { bestWay.Distance = fleetStoreDistanceArr[i][j] + distance[j]; bestWay.FleetIndex = i; bestWay.StoreIndex = j; } } } } ways.Add(bestWay); } foreach (var way in ways) { result.Add( BuildRouteHelper.BuildRouteSettings( calc, new RouteDistance { LocationFrom = fleets[way.FleetIndex].AddressLine, LocationFromAddress = fleets[way.FleetIndex], LocationTo = stores[way.StoreIndex].AddressLine, LocationToAddress = stores[way.StoreIndex] }, new RouteDistance { LocationFrom = stores[way.StoreIndex].AddressLine, LocationFromAddress = stores[way.StoreIndex], LocationTo = way.Client.AddressLine, LocationToAddress = way.Client }, way.Distance)); } return(this.Ok(result)); }
public async Task <IActionResult> Get(string address) { // get stores var stores = this.storeFinder.GetStoresToServe().ToList(); var fleets = this.droneService.GetAvailableDrones().ToList(); var clientAddress = await this.locationFinder.GetAddressCoordinatesAsync(address); if (!stores.AnySafe() || !fleets.AnySafe() || clientAddress == null) { return(null); } var calc = new DistanceCalculator(); var fleetStoreDistanceArr = new List <List <double> >(); var line = new LinkedList <double>(); foreach (var fleet in fleets) { line.Clear(); foreach (var store in stores) { line.AddLast(calc.Calculate(fleet.Coordinates, store.Coordinates)); } fleetStoreDistanceArr.Add(line.ToList()); } var distance = new List <double>(); foreach (var store in stores) { distance.Add(calc.Calculate(clientAddress.Coordinates, store.Coordinates)); } var bestWay = new BestWay { Distance = double.MaxValue, FleetIndex = 0, StoreIndex = 0, Client = clientAddress }; for (var i = 0; i < fleetStoreDistanceArr.Count; i++) { // for loop bellow fleetStoreDistanceArr line length will be the same for all lines, // so we don't need to calculate it for every line for (var j = 0; j < fleetStoreDistanceArr[0].Count; j++) { if (fleetStoreDistanceArr[i][j] + distance[j] < bestWay.Distance) { bestWay.Distance = fleetStoreDistanceArr[i][j] + distance[j]; bestWay.FleetIndex = i; bestWay.StoreIndex = j; } } } return(this.Ok(BuildRouteHelper.BuildRouteSettings( calc, new RouteDistance { LocationFrom = fleets[bestWay.FleetIndex].AddressLine, LocationFromAddress = fleets[bestWay.FleetIndex], LocationTo = stores[bestWay.StoreIndex].AddressLine, LocationToAddress = stores[bestWay.StoreIndex] }, new RouteDistance { LocationFrom = stores[bestWay.StoreIndex].AddressLine, LocationFromAddress = stores[bestWay.StoreIndex], LocationTo = bestWay.Client.AddressLine, LocationToAddress = bestWay.Client }, bestWay.Distance))); }
public void SortDataByDate(IList <CarStateModel> data, DateTime day) { ClearRoutes(); var first = data.OrderBy(o => o.Date).FirstOrDefault(); if (first == null) { return; } var curroute = RouteSelect.None; var prev = new Location { Latitude = first.Lt / 10000.0, Longitude = first.Ln / 10000.0, FirstPoint = true }; double dist = 0; var dc = new DistanceCalculator(); var slowTask = new Task(delegate { var foundParking = true; var nullDate = first.Spd < 6 || StateDateTimeHelper.EqualInterval(new DateTime(), first) ? first : null; foreach (var item in data.OrderBy(o => o.Date)) { var itemtime = StateDateTimeHelper.GetTime(item); var loc = new Location { Latitude = item.Lt / 10000.0, Longitude = item.Ln / 10000.0 }; if (data.IndexOf(item) <= 0) { continue; } nullDate = nullDate ?? first; var firsttime = StateDateTimeHelper.GetTime(nullDate); var isParking = StateDateTimeHelper.IsParking(item, ref nullDate); if (foundParking && isParking) { var selectedParkingModel = new ParkingModel(firsttime, itemtime, prev); var trash = _routesModel.Parkings.FirstOrDefault(o => o.Equals(selectedParkingModel)); if (trash == null) { _routesModel.Parkings.Add(selectedParkingModel); foundParking = false; } } else if (!foundParking && !isParking) { foundParking = true; nullDate = null; if (_routesModel.Parkings.Count > 0) { _routesModel.Parkings[_routesModel.Parkings.Count - 1].SetEndDates(itemtime); } } var curdist = dc.Calculate(first, item); if (item.Spd > 0 && Math.Abs(curdist) > .001 && !(foundParking && isParking)) { curroute = SortLocation(prev, loc, curroute, item.Spd / 10.0, item.Date); dist += curdist; prev = loc; } first = item; } var last = data.LastOrDefault(); if (last == null) { return; } if (!StateDateTimeHelper.EqualInterval(DateTime.Now, last)) { return; } prev = new Location { Latitude = last.Lt / 10000.0, Longitude = last.Ln / 10000.0, }; if (StateDateTimeHelper.EqualInterval(day.AddDays(1), last)) { _routesModel.Parkings.Add(new ParkingModel(StateDateTimeHelper.GetTime(last), day.AddDays(1), prev)); } }); slowTask.ContinueWith(o => DispatherThreadRun(delegate { ContinueSortData((int)dist, data.Max(m => m.Spd / 10)); })); slowTask.Start(); }
public void GivenCalculator_WhenCalculatingAndSolutionConvergesWithScreenHeightAfterFailureDynamics_ThenCallsInExpectedOrderAndOutputReturned() { // Given var random = new Random(21); const double screenHeight = 10.7; int nrOfTimeSteps = random.Next(3, int.MaxValue); double timeStep = random.NextDouble(); int failureSpeed = random.Next(); var failureState = new AircraftState(random.NextAngle(), random.NextAngle(), failureSpeed + 0.1, random.NextDouble(), random.NextDouble()); AircraftState[] states = { failureState, CreateAircraftStateWithHeight(screenHeight - 0.2), CreateAircraftStateWithHeight(screenHeight) }; AircraftAccelerations[] accelerations = { CreateAircraftAccelerations(), CreateAircraftAccelerations(), CreateAircraftAccelerations() }; var normalTakeOffDynamicsCalculator = Substitute.For <INormalTakeOffDynamicsCalculator>(); normalTakeOffDynamicsCalculator.Calculate(Arg.Any <AircraftState>()) .Returns(accelerations[0]); var failureTakeOffDynamicsCalculator = Substitute.For <IFailureTakeOffDynamicsCalculator>(); failureTakeOffDynamicsCalculator.Calculate(Arg.Any <AircraftState>()) .Returns(accelerations[1], accelerations[2]); var integrator = Substitute.For <IIntegrator>(); integrator.Integrate(Arg.Any <AircraftState>(), Arg.Any <AircraftAccelerations>(), timeStep) .Returns(states[0], states[1], states[2]); var calculatorSettings = new CalculationSettings(failureSpeed, nrOfTimeSteps, timeStep); var calculator = new DistanceCalculator(normalTakeOffDynamicsCalculator, failureTakeOffDynamicsCalculator, integrator, calculatorSettings); // Call DistanceCalculatorOutput output = calculator.Calculate(); // Assert normalTakeOffDynamicsCalculator.Received(1).Calculate(Arg.Any <AircraftState>()); failureTakeOffDynamicsCalculator.Received(2).Calculate(Arg.Any <AircraftState>()); integrator.Received(3).Integrate(Arg.Any <AircraftState>(), Arg.Any <AircraftAccelerations>(), timeStep); Received.InOrder(() => { normalTakeOffDynamicsCalculator.Calculate(Arg.Is <AircraftState>(state => IsZeroAircraftState(state))); integrator.Integrate(Arg.Is <AircraftState>(state => IsZeroAircraftState(state)), accelerations[0], timeStep); failureTakeOffDynamicsCalculator.Calculate(states[0]); integrator.Integrate(states[0], accelerations[1], timeStep); failureTakeOffDynamicsCalculator.Calculate(states[1]); integrator.Integrate(states[1], accelerations[2], timeStep); }); Assert.AreEqual(states.Last().Distance, output.Distance); Assert.AreEqual(failureSpeed, output.FailureSpeed); }
static void Main() { #region Builder Sample Console.WriteLine("Builder Sample"); var directorRoom = new DirectorRooms(new SimpleRoomBuilder()); var simpleRoom = directorRoom.Construct(); simpleRoom.Describe(); directorRoom = new DirectorRooms(new FamilyRoomBuilder()); var familyRoom = directorRoom.Construct(); familyRoom.Describe(); #endregion #region Factory Sample var psCretor = new PaymentServiceCreator(); var brazilianPaymentService = (IPaymentService)psCretor.Factory (PaymentServiceCreator.ServicesAvailable.Brazilian); brazilianPaymentService.EmailToCharge = "*****@*****.**"; brazilianPaymentService.MoneyToCharge = 178.90f; brazilianPaymentService.OptionToCharge = FactorySample.Enums.EnumChargingOptions.CreditCard; brazilianPaymentService.ProcessCharging(); var italianPaymentService = (IPaymentService)psCretor.Factory (PaymentServiceCreator.ServicesAvailable.Italian); italianPaymentService.EmailToCharge = "*****@*****.**"; italianPaymentService.MoneyToCharge = 188.70f; italianPaymentService.OptionToCharge = FactorySample.Enums.EnumChargingOptions.DebitCard; italianPaymentService.ProcessCharging(); #endregion #region Singleton Sample Console.WriteLine("Singleton Sample"); SingletonDemo.Current.Message = "This text will be printed by the singleton."; SingletonDemo.Current.Print(); #endregion #region Singleton Configuration Sample Console.WriteLine("Singleton Configuration Sample"); for (int i = 0; i < 20; i++) { Console.WriteLine($"Random Number Parameter: {Configuration.Current.RandomNumber}. Last Time Loaded {Configuration.Current.LastTimeLoaded}"); Thread.Sleep(1000); } #endregion #region Proxy Sample Console.WriteLine("Proxy Sample"); var roomPicture = new ProxyRoomPicture(); Console.WriteLine($"Picture Id: {roomPicture.Id}"); Console.WriteLine($"Picture FileName: {roomPicture.FileName}"); Console.WriteLine($"Tags: {string.Join(";", roomPicture.Tags)}"); Console.WriteLine($"1st call: Picture Data"); Console.WriteLine($"Image: {roomPicture.PictureData}"); Console.WriteLine($"2nd call: Picture Data"); Console.WriteLine($"Image: {roomPicture.PictureData}"); #endregion #region Command Sample Console.WriteLine(""); Console.WriteLine("Command Sample"); var package = new Package("Shopping in New York"); var likeCommand = new LikeCmd(package); var dislikeCommand = new DislikeCmd(package); var loveCommand = new LoveCmd(package); var commandInvoker = new CommandInvoker(); var keepAsking = true; while (keepAsking) { Console.WriteLine($"Your oppinion about {package.Name}:"); Console.WriteLine("1 - Like"); Console.WriteLine("2 - Dislike"); Console.WriteLine("3 - Love"); Console.WriteLine("4 - Undo last command"); Console.WriteLine("Any other key - Exit"); var key = Console.ReadKey(); Console.WriteLine(""); switch (key.Key) { case ConsoleKey.NumPad1: case ConsoleKey.D1: commandInvoker.Command = likeCommand; break; case ConsoleKey.NumPad2: case ConsoleKey.D2: commandInvoker.Command = dislikeCommand; break; case ConsoleKey.NumPad3: case ConsoleKey.D3: commandInvoker.Command = loveCommand; break; case ConsoleKey.NumPad4: case ConsoleKey.D4: if (commandInvoker.Command != null) { commandInvoker.Undo(); commandInvoker.Command = null; } else { Console.WriteLine("There is no Command to Undo!"); } break; default: keepAsking = false; break; } if ((keepAsking) && (commandInvoker.Command != null)) { commandInvoker.Invoke(); } } #endregion #region Dependency Injection Sample var userAddress = new UserAddress { City = "São Paulo", Country = "Brazil", ZipCode = "01001-001" }; var destinationAddress = new UserAddress { City = "Rio de Janeiro", Country = "Brazil", ZipCode = "22460-050" }; var distanceCalculator = new DistanceCalculator(userAddress, destinationAddress); distanceCalculator.Calculate(); #endregion Console.ReadKey(); }
public async Task <IActionResult> Get(string address) { var resultTask = Task <RouteSettings> .Factory.StartNew( () => { // get stores var stores = this.storeFinder.GetStoresToServe().ToList(); var drones = this.droneService.GetAvailableDrones().ToList(); var clientAddress = this.locationFinder.GetAddressCoordinates(address); if (!stores.AnySafe() || !drones.AnySafe() || clientAddress == null) { return(null); } var calc = new DistanceCalculator(); var storeClientDistance = new List <RouteDistance>(); foreach (var store in stores) { storeClientDistance.Add(new RouteDistance { LocationFrom = store.AddressLine, LocationFromAddress = store, LocationTo = clientAddress.AddressLine, LocationToAddress = clientAddress, Distance = calc.Calculate(store.Coordinates, clientAddress.Coordinates) }); } var nearestStore = storeClientDistance.OrderBy(x => x.Distance).FirstOrDefault(); var droneStoreDistance = new List <RouteDistance>(); foreach (var fleet in drones) { foreach (var store in stores) { if (store.AddressLine.Equals(nearestStore.LocationFrom, StringComparison.InvariantCultureIgnoreCase)) { droneStoreDistance.Add( new RouteDistance { LocationFrom = fleet.AddressLine, LocationFromAddress = fleet, LocationTo = store.AddressLine, LocationToAddress = store, Distance = calc.Calculate(fleet.Coordinates, store.Coordinates) }); break; } } } var nearestFleet = droneStoreDistance .Where(x => x.LocationTo.Equals(nearestStore.LocationFrom, StringComparison.CurrentCultureIgnoreCase)) .OrderBy(x => x.Distance) .FirstOrDefault(); return(BuildRouteHelper.BuildRouteSettings(calc, nearestFleet, nearestStore)); }); return(this.Ok(await resultTask)); }
public async Task <IActionResult> GetForAll() { var resultTask = Task <List <RouteSettings> > .Factory.StartNew(() => { // get stores var stores = this.storeFinder.GetStoresToServe().ToList(); var fleets = this.droneService.GetDroneFleets().ToList(); var clientAddresses = clientLocations.Value; var result = new List <RouteSettings>(); if (!stores.AnySafe() || !fleets.AnySafe() || !clientAddresses.AnySafe()) { return(result); } var calc = new DistanceCalculator(); var fleetStoreDistance = new List <RouteDistance>(); foreach (var fleet in fleets) { foreach (var store in stores) { fleetStoreDistance.Add(new RouteDistance { LocationFrom = fleet.AddressLine, LocationFromAddress = fleet, LocationTo = store.AddressLine, LocationToAddress = store, Distance = calc.Calculate(fleet.Coordinates, store.Coordinates) }); } } // get distance from client to store var storeToClientDistances = new LinkedList <RouteDistance>(); foreach (var client in clientAddresses) { foreach (var store in stores) { storeToClientDistances.AddLast( new RouteDistance { LocationFrom = store.AddressLine, LocationFromAddress = new Address { AddressLine = store.AddressLine, Coordinates = store.Coordinates }, LocationTo = client.AddressLine, LocationToAddress = new Address { AddressLine = client.AddressLine, Coordinates = client.Coordinates }, Distance = calc.Calculate(client.Coordinates, store.Coordinates) }); } var availableDrones = this.droneService.GetAvailableDrones(); var nearestStore = storeToClientDistances.OrderBy(x => x.Distance).FirstOrDefault(); var nearestFleet = fleetStoreDistance .Where(x => x.LocationTo.Equals(nearestStore.LocationFrom, StringComparison.InvariantCultureIgnoreCase)) .OrderBy(x => x.Distance) .FirstOrDefault(); var availableDroneNearby = availableDrones.FirstOrDefault(x => x.AddressLine.Equals( nearestFleet.LocationFrom, StringComparison.InvariantCultureIgnoreCase)); if (availableDroneNearby == null) { var availableDronesDistance = fleetStoreDistance .Where(x => !x.LocationFrom.Equals(nearestFleet.LocationFrom, StringComparison.InvariantCultureIgnoreCase)) .ToList(); nearestFleet = availableDronesDistance .OrderBy(x => x.Distance) .FirstOrDefault(); } result.Add(BuildRouteHelper.BuildRouteSettings(calc, nearestFleet, nearestStore)); storeToClientDistances.Clear(); } return(result); }); return(this.Ok(await resultTask)); }
/// <summary> /// Обновление навигационных данных /// </summary> /// <param name="data"></param> /// <param name="date"></param> private void BuildHistoryRow(List <CarStateModel> data, DateTime date) { var r = new LoadedHistoryRows { Date = date, Data = data }; var slowTask = new Task(delegate { try { var dc = new DistanceCalculator(); for (var i = 0; i < data.Count() - 1; i++) { r.Mileage += dc.Calculate(data[i], data[i + 1]); } } catch { } if (!data.Any()) { return; } try { r.MiddleSpeed = data.Sum(p => p.Spd) / 10 / data.Count(); var moving = data.Where(p => p.Spd > 10).ToList(); if (!moving.Any()) { return; } var hStart = moving.Min(p => p.hh); var minStart = moving.Where(p => p.hh == hStart).Min(p => p.mm); var hStop = moving.Max(p => p.hh); var mStop = moving.Where(p => p.hh == hStop).Max(p => p.mm); r.Start = hStart + ":" + minStart; r.Stop = hStop + ":" + mStop; } catch { } }); slowTask.ContinueWith(delegate { if (_dispatcher != null) { _dispatcher.BeginInvoke(new Action(() => { var item = HistoryRows.OrderBy(s => s.Date) .LastOrDefault(o => o.StringDate.Equals(r.StringDate) || o.Date < r.Date); if (item != null) { var indx = HistoryRows.IndexOf(item); _foundselected = HistoryRows[indx].Equals(SelectedHistoryRow); DistanceAll -= HistoryRows[indx].Mileage; HistoryRows[indx] = r; if (_foundselected) { SelectedHistoryRow = r; } _foundselected = false; DistanceAll += r.Mileage; } else { HistoryRows.Add(r); DistanceAll += r.Mileage; } })); } }); slowTask.Start(); }
public void Invalid_Distance_Should_Thorw_exception(string path) { var distanceCalculator = new DistanceCalculator(Map); var actual = distanceCalculator.Calculate(path); }