/// <summary> /// Parses json information to a list of forecasts /// </summary> /// <param name="json"></param> /// <returns></returns> List <ForecastModel> ToForecasts(JObject json) { if (json != null) { var ok = json.Value <short>("cod"); if (ok == 200) { var forecasts = new List <ForecastModel>(); var list = json["list"].Take(3); foreach (var item in list) { var m = item["main"]; var w = item["weather"][0]; var fc = new ForecastModel { Timestamp = item.Value <DateTime>("dt_txt"), WeatherCondition = WeatherCondition(w.Value <string>("icon")), Temperature = m.Value <int>("temp"), MinimumTemperature = m.Value <int>("temp_min"), MaximumTemperature = m.Value <int>("temp_max"), IsNight = w.Value <string>("icon").EndsWith("n"), }; forecasts.Add(fc); } return(forecasts); } } return(null); }
public List <ForecastModel> getForecast(List <double> latAndLong) { var client = new RestClient("https://community-open-weather-map.p.rapidapi.com/forecast?lat=" + System.Math.Round(latAndLong[0], 4) + "&lon=" + System.Math.Round(latAndLong[1], 4)); var request = new RestRequest(Method.GET); request.AddHeader("x-rapidapi-host", "community-open-weather-map.p.rapidapi.com"); request.AddHeader("x-rapidapi-key", "109daa0c4fmsh59fa8ac8dd612e0p101d84jsn0d5858161f0b"); var response = client.Execute(request).Content; var jsonForcast = JObject.Parse(response)["list"]; var recordlist = new List <ForecastModel>(); foreach (var record in jsonForcast) { var current = new ForecastModel(); current.Temp = record["main"]["temp"].ToObject <double>(); current.Humidity = record["main"]["humidity"].ToObject <double>(); current.Pressure = record["main"]["pressure"].ToObject <double>(); current.Type = record["weather"][0]["main"].ToObject <string>(); current.Description = record["weather"][0]["description"].ToObject <string>(); var Datetime = record["dt_txt"].ToString(); var DateAndTime = Datetime.Split(' '); current.Date = DateAndTime[0]; current.Time = DateAndTime[1]; current.Speed = record["wind"]["speed"].ToObject <double>(); current.Deg = record["wind"]["deg"].ToObject <double>(); recordlist.Add(current); } return(recordlist); }
/// <Summary> /// 添加记录 /// </Summary> /// <param name="fm"></param> private static void addForecastData(List <string> lt_names, List <CurrentTendencyModel> lt_ctm1, List <CurrentTendencyModel> lt_ctm2, List <ForecastModel> lt) { ForecastModel fm; CurrentTendencyModel ctm; for (int i = 0; i < lt_names.Count; i++) { ctm = lt_ctm1[i]; fm = new ForecastModel(); int sum = ctm.Value * 4; for (int j = 0; j < lt_ctm2.Count; j++) { sum += lt_ctm2[j].Value;//求和 } int diff = 0; for (int j = 0; j < lt_ctm2.Count; j++) { diff += Math.Abs(ctm.Value - lt_ctm2[j].Value);//求差 } fm.UnitName = ctm.UnitName; fm.Sum = sum; fm.Diff = diff; fm.Current = ctm.Value; lt.Add(fm); } ///解析 // UnitName = "大大", // Sum = fm.Big * 4 + fm.Odd + fm.OddPair + fm.PairOdd + fm.Pair, // Diff = Math.Abs(fm.Big - fm.Odd) + Math.Abs(fm.Big - fm.OddPair) + Math.Abs(fm.Big - fm.PairOdd) + Math.Abs(fm.Big - fm.Pair), // Current = fm.Big }
//Call IPService //Call GeoService with _ipaddress.IP //Call NWSEndpointService with _usergeo.latitude.ToString(), _usergeo.longitude.ToString(); //Call ForecastService with _nwsemodel.Properties.forecast public async Task <ForecastModel> GetWeatherAsync() { ForecastModel _forecast = new ForecastModel(); ForecastService _forecastservice = new ForecastService(); NWSEndpointModel _nwsemodel = new NWSEndpointModel(); NWSEndpointService _nwseservice = new NWSEndpointService(); IPAddressModel _ipaddress = new IPAddressModel(); IPService _ipservice = new IPService(); UserGeolocationModel _usergeo = new UserGeolocationModel(); GeoService _geoservice = new GeoService(); //Call IPService //Call GeoService with _ipaddress.IP //Call NWSEndpointService with _usergeo.latitude.ToString(), _usergeo.longitude.ToString(); //Call ForecastService with _nwsemodel.Properties.forecast _ipaddress = await _ipservice.GetIPAsync(); _usergeo = await _geoservice.GetLocationAsync(_ipaddress.IP); _nwsemodel = await _nwseservice.GetAPIEndpointAsync(_usergeo.latitude.ToString(), _usergeo.longitude.ToString()); _forecast = await _forecastservice.GetForecastAsync(_nwsemodel.properties.forecast); return(_forecast); }
public ActionResult Forecast(WeatherApp.Models.ForecastModel model) { //if (ModelState.IsValid) //{ Program prog = new Program(); string location = model.Location; string url = prog.retrieveXML(location); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(url); //get string form for reference WebClient web = new WebClient(); string stringForm = web.DownloadString(url); //Console.WriteLine(stringForm); ForecastModel forecast = prog.findAllAttributes(xmlDoc, location); //} if (Request.Browser.IsMobileDevice) { return(View("MobileForecast", forecast)); } else { return(View(forecast)); } }
// GET: Forecast public async Task <ActionResult> FiveDayForecast(string txtCity) { _apikey = ConfigurationValues.APIKEY; HttpResponseMessage httpResponse = null; using (var Client = new HttpClient()) { try { Client.BaseAddress = new Uri("http://api.openweathermap.org"); if (txtCity != null && txtCity != "") { httpResponse = await Client.GetAsync($"/data/2.5/forecast?q={txtCity}&appid={_apikey}&units=metric"); //http://api.openweathermap.org/data/2.5/forecast/daily?q=Melbourne,AU&cnt=5&&appid=2e0bfcd75d67a0452c6890c445c51030&units=metric } else { httpResponse = await Client.GetAsync($"/data/2.5/forecast?q=Melbourne,AU&appid={_apikey}&units=metric"); } httpResponse.EnsureSuccessStatusCode(); var stringResult = await httpResponse.Content.ReadAsStringAsync(); ForecastModel rawWeather = new ForecastModel(); rawWeather = JsonConvert.DeserializeObject <ForecastModel>(stringResult); return(View(rawWeather)); } catch (HttpRequestException httpRequestException) { return(View($"Error getting weather from OpenWeather: {httpRequestException.Message}")); } } }
public ActionResult Index(ForecastModel model) { try { ViewBag.Branches = new SelectList(db.Branches, "BranchID", "BranchName"); ViewBag.Products = new SelectList(db.Products, "ProductID", "ProductName"); ViewBag.ForecastMethods = new SelectList(db.Forecast_Methods, "ForecastIdentifier", "ForecastMethod"); ViewBag.DateTypes = new SelectList(db.Forecast_DatePeriods, "DatePeriod", "DatePeriod"); ForecastBusinessManger fcastManager = new ForecastBusinessManger(); ForecastSearchCriteria fcastSearchCriteria = new ForecastSearchCriteria(); fcastSearchCriteria.BranchId = model.ForecastSearchCriteria.BranchId; fcastSearchCriteria.ProductId = model.ForecastSearchCriteria.ProductId; fcastSearchCriteria.Method = new Forecast_Methods() { ForecastIdentifier = model.ForecastSearchCriteria.Method.ForecastIdentifier }; fcastSearchCriteria.DatePeriod = new Forecast_DatePeriods() { DatePeriod = model.ForecastSearchCriteria.DatePeriod.DatePeriod }; fcastSearchCriteria.ForecastPeriod = model.ForecastSearchCriteria.ForecastPeriod; var result = fcastManager.GetForecastResults(fcastSearchCriteria); model.ForecastResult = result; return(View("Index", model)); } catch { return(View()); } }
public List <ForecastModel> GetForecasts(string parkCode) { List <ForecastModel> forecasts = new List <ForecastModel>(); try { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand("SELECT * FROM weather WHERE parkCode = @parkCode; ", conn); cmd.Parameters.AddWithValue("@parkCode", parkCode); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { ForecastModel forecast = new ForecastModel(); forecast.ParkCode = Convert.ToString(reader["parkCode"]); forecast.FiveDayForecastValue = Convert.ToInt32(reader["fiveDayForecastValue"]); forecast.Low = Convert.ToInt32(reader["low"]); forecast.High = Convert.ToInt32(reader["high"]); forecast.Forecast = Convert.ToString(reader["forecast"]); forecasts.Add(forecast); } } } catch (SqlException ex) { throw ex; } return(forecasts); }
public async Task <ForecastModel> GetWeather(string city, DateTime?date) { if (string.IsNullOrEmpty(city)) // todo: think about it { city = DefaultCity; } if (date.Equals(null)) // todo: think about it { date = DateTime.UtcNow; } var address = GetAddressFromString(city); var forecastOptions = new DarkSkyService.OptionalParameters { MeasurementUnits = "si", ForecastDateTime = date }; var response = await _client.GetForecast(address.Coordinates.Latitude, address.Coordinates.Longitude, forecastOptions); var forecastResult = response.Response; var forecast = new ForecastModel { Temperature = forecastResult.Currently.Temperature.ToString(), WindSpeed = forecastResult.Currently.WindSpeed.ToString(), Summary = forecastResult.Currently.Summary, Location = address.ToString(), }; return(await Task.FromResult(forecast)); }
private void BindModel(ForecastModel model, List <ListResultForecast> resultquery) { model.TotalForecast = Convert.ToDecimal(resultquery[0].Columna1); model.Forecast = Convert.ToDecimal(resultquery[0].Columna2); model.TotalClient = Convert.ToDecimal(resultquery[1].Columna1); model.Client = Convert.ToDecimal(resultquery[1].Columna2); }
public void GetDataForecastPessimisticTest() { IForecastModel forecastModel = new ForecastModel(_data, 12, 12, Scheme.Period.Month); var data = forecastModel.GetData().GetOnlyForecastPessimistic(3).Sum(_ => _.Value); data.Should().Be(277737); }
public IActionResult Forecast(Double lng, Double lat) { double ln = Math.Floor(Convert.ToDouble(lng) * 1000000) / 1000000; double la = Math.Floor(Convert.ToDouble(lat) * 1000000) / 1000000; ForecastModel result = GetForecast(ln, la).Result; return(PartialView("PartialForecast", result)); }
public static ForecastModel CreateForecastModel(string dataAreaId, string modelId) { ForecastModel forecastModel = new ForecastModel(); forecastModel.dataAreaId = dataAreaId; forecastModel.ModelId = modelId; return(forecastModel); }
public void GetDataHistoricTest() { IForecastModel forecastModel = new ForecastModel(_data, 12, 12, Scheme.Period.Month); var data = forecastModel.GetData().GetOnlyHistoric(3).Sum(_ => _.Value); data.Should().Be(292594); }
public void GetForecastTest() { ForecastService forecastService = new ForecastService(); string location = "Stuttgart"; ForecastModel forecastModel = new ForecastModel(); forecastModel = forecastService.GetForecast(location); Assert.NotNull(forecastModel); }
private string BuildResponse(ForecastModel model, PhraseResult phraseResult, string userName) { var result = $"Hey, {userName} {Environment.NewLine}" + $"Weather in {model.Location} {Environment.NewLine}" + $"Date: {phraseResult.Date:dd.MM.yyyy} {Environment.NewLine}" + $"Temperature: {model.Temperature} °C{Environment.NewLine}" + $"Wind speed: {model.WindSpeed} mph{Environment.NewLine} Summary: {model.Summary}"; return(result); }
private async void FormShowWeather_LoadAsync(object sender, EventArgs e) { SplashScreenManager.ShowForm(this, typeof(WaitForm1), true, true, false); var wandf = await weatherAndForecast.GetData("Perth,AU"); weather = weatherAndForecast.Weather; forecast = weatherAndForecast.Forecast; SetLabels(); SplashScreenManager.CloseForm(); SetLabelsVisible(); }
private void GetCurrentProbabilityTable(ForecastModel forecastModel) { for (int i = 0; i < forecastModel.DataModels.Count(); i++) { TextBlock rootTextBlock = new TextBlock(); rootTextBlock.Name = $"textViewCurrentData{i}"; rootTextBlock.FontSize = 16; rootTextBlock.Text = $"Score: {forecastModel.DataModels[i].Score}; P: {forecastModel.DataModels[i].Probability.ToString()}"; stackPanelProbabilityAssessment.Children.Add(rootTextBlock); } }
public async Task <Forecast.Domain.Entity.Forecast> Load() { try { ForecastModel forecastModel = await _repository.FetchCurrentForecast(); ITarget target = new ForecastAdapter(forecastModel); return(target.GetForecast()); } catch (Exception e) { throw new ServiceUnavailable(String.Format("Não foi possível capturar resultado forecast: [{0}]", e.Message)); } }
public JsonResult ObtainListResult() { var table = ReadExcel(7, 8, 52, 53, 3); var resultquery = (from co in table.AsEnumerable() select new ListResultForecast() { Columna1 = co.Field <string>("colunmn1"), Columna2 = co.Field <string>("colunmn3") }).ToList(); var model = new ForecastModel(); BindModel(model, resultquery); var result = new { data = model }; return(Json(result, JsonRequestBehavior.AllowGet)); }
public void Add(ForecastModel model) { var player = new Player { Phone = model.Phone, Name = model.PlayerName }; var forecast = new Forecast { Degree = model.Degree, Player = player, DateTime = DateTime.Now }; _dbContext.Forecasts.Add(forecast); _dbContext.SaveChanges(); }
public ForecastController(IHouseDetailes houseDetailes, IPlantDetailes plantDetailes) { this.houseDetailes = houseDetailes; this.plantDetailes = plantDetailes; consH = new Dictionary <int, double>(); consP = new Dictionary <int, double>(); consuptions = new List <double>(); consuptionsLimit = new List <double>(); foreach (HouseDetail h in houseDetailes.getHouseDetails) { if (!consH.ContainsKey(h.daysNumber)) { consH.Add(h.daysNumber, h.consumptionHouse); } else { consH[h.daysNumber] = consH[h.daysNumber] + h.consumptionHouse; } } foreach (PlantDetail p in plantDetailes.getPlantDetails) { if (!consP.ContainsKey(p.daysNumber)) { consP.Add(p.daysNumber, p.consumptionPlant); } else { consP[p.daysNumber] = consP[p.daysNumber] + p.consumptionPlant; } } foreach (KeyValuePair <int, double> pair in consH) { consuptions.Add(pair.Value + consP[pair.Key]); } forecastModel = new ForecastModel(); if (consuptions.Count >= 7) { for (int i = consuptions.Count - 7; i < consuptions.Count; i++) //last 7 days { consuptionsLimit.Add(consuptions[i]); } forecastModel.consuption = consuptionsLimit.ToArray(); forecastModel.forecast = new MNK().calc(consuptionsLimit.ToArray(), 3); forecastModel.date = DateTemp.zeroCountDateTime.AddDays(plantDetailes.getPlantDetails.Last().daysNumber + 1); } }
public JsonResult ObtainListResultGoogle() { //var table = DataTable(7, 8, 52, 54, ReadExcelGoogle("Up-to-date Forecast!G52:H53")); var table = DataTable(7, 8, 52, 54, ReadExcelGoogle("Up-to-date Forecast!H3:I4")); var resultquery = (from co in table.AsEnumerable() select new ListResultForecast() { Columna1 = co.Field <string>("colunmn1"), Columna2 = co.Field <string>("colunmn3") }).ToList(); var model = new ForecastModel(); BindModel(model, resultquery); var result = new { data = model }; return(Json(result, JsonRequestBehavior.AllowGet)); }
public ServiceResultSet GetTimeSeriesForcastResult(ForecastModel model) { var composed = ExportToService <ForecastModel, TimeSeriDto>(model, GetUrl(Enums.PredictionModelFuncTypes.Forecast)); composed.Wait(); if (composed == null) { return(ServiceResultSet.GetUnSuccessful("با این شرایط امکان تخمین وجود ندارد!")); } TimeSeriDto composedResult = composed.Result; if (composedResult == null) { return(ServiceResultSet.GetUnSuccessful("با این شرایط امکان تخمین وجود ندارد!")); } return(ServiceResultSet.GetSuccessful("done!", composedResult)); }
public async Task <IActionResult> ForecastData([FromBody] ForecastModel model) { var options = _mapper.Map <ForecastingOptions>(model); var minimumCount = (options.SeriesLength / options.WindowSize) * 2; // calculate minimum data required to run forecasting var recordsCount = await _context.Recordings.Where(x => x.SensorId == model.SensorId) .Where(x => x.Timestamp >= model.StartDate && x.Timestamp <= model.EndDate) .LongCountAsync(); if (recordsCount < minimumCount) { return(Conflict(new { message = $"Not enough data to run forecasting with provided parameters. Filtered data count: {recordsCount}." })); } // calculate minimum data required to run forecasting after aggregation var records = await _context.Recordings.Where(x => x.SensorId == model.SensorId) .Where(x => x.Timestamp >= model.StartDate && x.Timestamp <= model.EndDate) .ToListAsync(); var data = records.GroupBy(x => new DateTime(x.Timestamp.Date.Year, x.Timestamp.Date.Month, x.Timestamp.Date.Day)) .Select(x => new ModelInput { RecordTime = x.Key, Value = (float)x.Average(x => x.Value) }).ToList(); if (data.Count < minimumCount) { return(Conflict(new { message = $"Not enough data to run forecasting with provided parameters after aggregation. Aggregated data count: {data.Count}." })); } // run predictions var result = _forecastingService.RunPredictions(data, options); var predictedCount = result.ForecastedValues.Length; return(Json(new { intervals = Enumerable.Range(1, predictedCount * 3), forecasted = data.Skip(data.Count - 2 * predictedCount).Select(x => x.Value).Concat(result.ForecastedValues), upperBound = data.Skip(data.Count - 2 * predictedCount).Select(x => x.Value).Concat(result.UpperBounds), lowerBound = data.Skip(data.Count - 2 * predictedCount).Select(x => x.Value).Concat(result.LowerBounds), mae = result.MAE, rmse = result.RMSE })); }
public async Task <ActionResult <ForecastModel> > Forecast([FromQuery, StringLength(100)] string city , [FromQuery, RegularExpression(@"(?!01000|99999)(0[1-9]\d{3}|[1-9]\d{4})")] string zipCode) { ForecastModel response = null; if (!ModelState.IsValid) { return(BadRequest(ModelState)); } response = await _queries.GetForecast(city, zipCode); if (response != null) { return(Ok(response)); } return(NotFound()); }
public ForecastModel Map(WeatherDashboardModel model) { var forecastModel = new ForecastModel(); forecastModel.CurrentCelsius = model.CurrentCelsius; forecastModel.CurrentFahrenheit = model.CurrentFahrenheit; forecastModel.CurrentSummary = model.CurrentSummary; forecastModel.Icon = model.Icon; if (string.IsNullOrWhiteSpace(model.IconUrl)) { forecastModel.IconUrl = "./images/" + model.Icon + ".png"; } else { forecastModel.IconUrl = model.IconUrl; } forecastModel.Forecast = new List <ForecastDayDashboard>(); foreach (var modelDay in model.Forecast) { var forecastDay = new ForecastDayDashboard(); forecastDay.Summary = modelDay.Summary; forecastDay.LowCelsius = modelDay.LowCelsius; forecastDay.LowFahrenheit = modelDay.LowFahrenheit; forecastDay.HighCelsius = modelDay.HighCelsius; forecastDay.HighFahrenheit = modelDay.HighFahrenheit; forecastDay.Icon = modelDay.Icon; if (string.IsNullOrWhiteSpace(modelDay.IconUrl)) { forecastDay.IconUrl = "./images/" + modelDay.Icon + ".png"; } else { forecastDay.IconUrl = modelDay.IconUrl; } forecastDay.Date = modelDay.Date; forecastModel.Forecast.Add(forecastDay); } return(forecastModel); }
//[SwaggerResponseExample(HttpStatusCode.OK, typeof(DashboardDataExample))] public async Task <IHttpActionResult> GetByReportId(string id) { try { var dashboardDtos = await _Dashboardservice.GetByReportIdAsync(id); if (!dashboardDtos.Any()) { return(NotFound()); } var Dashboardshorts = _mapper.Map <IEnumerable <DashboardData> >(dashboardDtos); var dataTempDtos = await _Dashboardservice.GetAnalyticDataAsync(); var dataDtos = dataTempDtos.ToArray().OrderBy(_ => _.Date).ToArray(); foreach (var item in dataDtos) { item.Value = item.KursDollarValue; } var dataForecastData = _mapper.Map <IEnumerable <Data> >(dataDtos); IForecastModel forecastModel = new ForecastModel(dataForecastData, 12, 40, Scheme.Period.Day); var dashboard = Dashboardshorts.FirstOrDefault(); var data = forecastModel.GetData().ToArray(); //var dataCount = dat.Length - 15; //var data = dat.Skip(dataCount); var dataForecast = data.GetOnlyForecastPessimistic(40).ToArray(); //var dataCount = dat.Length - 15; //var data = dat.Skip(dataCount); dashboard.Dates = dataForecast.Select(_ => _.Date.ToString("d")); dashboard.Values = dataForecast.Select(_ => _.Value); DashboardData[] dashboardDatas = new[] { dashboard }; return(Ok(dashboardDatas)); } catch (InvalidOperationException ioe) { return(InternalServerError(ioe)); } }
public async Task <ForecastModel> FetchCurrentForecast() { ForecastModel forecastModel = null; HttpClient httpClient = new HttpClient(); httpClient.Timeout = TimeSpan.FromSeconds(30); using (HttpResponseMessage response = await httpClient.GetAsync("http://api.weatherstack.com/current?access_key={seu token aqui}&query=Curitiba")) { if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); forecastModel = JsonSerializer.Deserialize <ForecastModel>(content); } } return(forecastModel); }
public void MajdEgyApiResultPeldanytTranszformalokForecastModelTipusra() { var result = new ApiResult <ApiResponse> { ForecastApiCalls = 11, HasSuccess = true, Data = new ApiResponse { currently = CurrentlyDataPointFactory(), daily = new DailyDataBlock { data = DailyDataPointListFactory(), summary = "bumm bumm", icon = "bamm bamm" } } }; apiResult = mapper.Map <ForecastModel>(result); }