Ejemplo n.º 1
0
        /// <summary>
        /// Simulate a day in the market.
        /// </summary>
        public void Simulate()
        {
            if (CurrentDate != EndDate)
            {
                CurrentDate = CurrentDate.AddDays(1);
                StockDay    = DataManager.IsStockDay(CurrentDate);

                // before we even bother with any calculations, we need to
                // make sure the stock market was open on this given day
                if (StockDay)
                {
                    UpdateMarketState();
                    StockDays.Add(CurrentDate);
                    Log("Stockday on " + CurrentDate + ", proceeding...");

                    // how has our equity changed over postmarket and premarket
                    for (int i = 0; i < Positions.Count; i++)
                    {
                        List <BarData> history = MarketState.FirstOrDefault(x => x.Key == Positions[i].Symbol).Value;

                        // how much has the stock changed in value overnight?
                        double change = history.Last().Open - history[history.Count - 2].Close;

                        // change our equity!
                        Equity += change * Positions[i].Shares;
                    }

                    // process orders
                    ProcessAllOrders();

                    // with our new positions, how will our equity change today?
                    for (int i = 0; i < Positions.Count; i++)
                    {
                        List <BarData> history = MarketState.FirstOrDefault(x => x.Key == Positions[i].Symbol).Value;

                        // how much has the stock changed in value overnight?
                        double change = history.Last().Close - history.Last().Open;

                        // change our equity!
                        Equity += change * Positions[i].Shares;

                        // update the position value
                        Positions[i].PriceHistory.Add(new Tuple <DateTime, double, double>(CurrentDate, history.Last().Close, change));
                    }

                    // allow the strategy to make calls for the next day
                    Strategy.Update(this);

                    // process all logs for the day
                    ProcessLogs();
                }

                EquityHistory.Add(new Tuple <DateTime, double>(CurrentDate, Equity));
                BuyingPowerHistory.Add(new Tuple <DateTime, double>(CurrentDate, BuyingPower));
            }
            else
            {
                throw new Exception("Simulation is already complete.");
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Init the universe for a new run.
        /// </summary>
        public void Init(SiteItem site, ManagementItem management)
        {
            Weather_            = new Weather(this);
            Crop_               = new Crop(this);
            Soil_               = new Soil(this);
            thermalTimeWrapper_ = new ThermalTimeBiomaWrapper(this);
            ShootTemperature_   = new ShootTemperature(this);

            meteorologyWrapper_ = new MeteoBiomaWrapper(this);

            Weather_.Init(site, management);
            CurrentDate = management.FinalSowingDate.AddDays(-1);
            Soil_.Init(Weather_.MinTemp(CurrentDate), Weather_.MaxTemp(CurrentDate), Weather_.GetMeanTemperatureBeforeSowing());
            Crop_.Init(thermalTimeWrapper_.CumulTT, CurrentDate.AddDays(1));

            CalcChangeinNFertilisation();
            GrowthDay                  = 0;
            CumAirTempFromSowing       = 0;
            CumMaxCanopyTempFromSowing = 0;
            CumMaxAirTempFromSowing    = 0;
            if (management.Species == "Maize")
            {
                switchMaize = true;
            }
            else
            {
                switchMaize = false;
            }
        }
Ejemplo n.º 3
0
        private async Task OnChevronTapCommand(object s)
        {
            if ((string)s == "Left")
            {
                await Load(CurrentDate.AddDays(-1));
            }
            else
            {
                await Load(CurrentDate.AddDays(1));
            }

            _messagingService.Send(this, Messages.WorkoutsReloaded);
        }
Ejemplo n.º 4
0
 protected override void OnPreviewKeyDown(KeyEventArgs e)
 {
     if (e.Key == Key.Add)
     {
         CurrentDate = CurrentDate.AddDays(1);
         e.Handled   = true;
     }
     else if (e.Key == Key.Subtract)
     {
         CurrentDate = CurrentDate.AddDays(-1);
         e.Handled   = true;
     }
     base.OnPreviewKeyDown(e);
 }
Ejemplo n.º 5
0
        public SchedulerViewModel()
        {
            MachineInfo = new MachineInfo();

            MachineInfoList = new List <MachineInfo>();

            MachineProcessList = new List <Machine>();

            CurrentDate = DateTime.Now;

            MondayDate = CurrentDate.AddDays(-((CurrentDate.DayOfWeek - System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 7) % 7)).Date;; // (DayOfWeek.Monday);

            SundayDate = CurrentDate.AddDays(-((CurrentDate.DayOfWeek - System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek - 6) % 7)).Date;; // (DayOfWeek.Monday);
        }
Ejemplo n.º 6
0
        public CompanyChartData MovePrev()
        {
            CurrentDate = CurrentDate.AddDays(-1);
            while (IsEmpty(CurrentDate))
            {
                CurrentDate = CurrentDate.AddDays(-1);
            }

            if (CurrentDate > InitialDate)
            {
                Initialize();
            }

            return(CalculateCompanyChartData());
        }
Ejemplo n.º 7
0
        public CompanyChartData MoveNext()
        {
            CurrentDate = CurrentDate.AddDays(1);
            while (IsEmpty(CurrentDate))
            {
                CurrentDate = CurrentDate.AddDays(1);
            }

            if (CurrentDate < _configuration.Quotes.First().Date)
            {
                Initialize();
            }

            return(CalculateCompanyChartData());
        }
Ejemplo n.º 8
0
    IEnumerator PerDayTick()
    {
        while (Application.isPlaying)
        {
            while (!paused)
            {
                int old_week  = Week;
                int old_month = Month;
                int old_year  = Year;

                CurrentDate = CurrentDate.AddDays(1.0);

                //daily tick
                PerDayEvent.Invoke();

                if (Year > old_year)
                {
                    PerYearEvent.Invoke();
                    old_week  = 0;
                    old_month = 0;
                }

                if (Week > old_week)
                {
                    PerWeekEvent.Invoke();
                }
                if (Month > old_month)
                {
                    PerMonthEvent.Invoke();
                }

                yield return(new WaitForSeconds(1.0f));
            }

            yield return(null);
        }
    }
Ejemplo n.º 9
0
        /// <summary>
        /// Draws vertical net lines
        /// </summary>
        private void DrawVertLines(Graphics graphics, int xCoord, int yCoord)
        {
            int lineWidth = 1;

            for (int i = 0; i < _dayCount; i++)
            {
                var OldXCoord = xCoord - lineWidth;
                //Vertical lines coordinates
                Point p1 = new Point(xCoord, 1);
                Point p2 = new Point(xCoord, yCoord);

                Point p3 = new Point(xCoord + smallWhiteRectWidth, 1);
                Point p4 = new Point(xCoord + smallWhiteRectWidth, yCoord);

                using (Pen pen = new Pen(Color.Black, lineWidth))
                {
                    //Draws vertical lines
                    graphics.DrawLine(pen, p1, p2);
                    graphics.DrawLine(pen, p3, p4);

                    //Draws vertical white rectangles
                    using (var backBrush = new SolidBrush(smallRectColor))
                        graphics.FillRectangle(backBrush, xCoord, 1, smallWhiteRectWidth, yCoord);
                }
                if (i == _dayCount - 1 && VerticalScroll.Visible)
                {
                    xCoord += VerticalStep - SystemInformation.VerticalScrollBarWidth;
                }
                else
                {
                    xCoord += VerticalStep;
                }

                //Adds number of column with coordinates to list
                ColumnCoord.Add(new CoordColumn(i, OldXCoord, xCoord, CurrentDate.AddDays(i)));
            }
        }
        public void CreateCalendarData()
        {
            CalendarItemData data;
            DateTime         firstDay = CurrentDate.AddDays(1 - CurrentDate.Day);
            Events           events;

            ItemList.Clear();

            for (int i = 1; i <= DateTime.DaysInMonth(CurrentDate.Year, CurrentDate.Month); i++)
            {
                data = new CalendarItemData(i);
                ItemList.Add(data);
            }

            OnPropertyChanged("CurrentDate");

            events = _calendarDataService.GetEvent(firstDay, firstDay.AddDays(DateTime.DaysInMonth(firstDay.Year, firstDay.Month)));
            if (events == null)
            {
                return;
            }

            foreach (Event e in events.Items)
            {
                if (e.Start.DateTime != null)
                {
                    int index = ((DateTime)e.Start.DateTime).Day;

                    data = ItemList.Find(x => x.Index == index);
                    if (data != null)
                    {
                        data.EventList.Add(e);
                    }
                }
                else
                {
                    DateTime start = Convert.ToDateTime(e.Start.Date);
                    DateTime end   = Convert.ToDateTime(e.End.Date);
                    int      d_s   = 1;
                    int      d_e   = DateTime.DaysInMonth(CurrentDate.Year, CurrentDate.Month) + 1;

                    if (start.Year == CurrentDate.Year && start.Month == CurrentDate.Month)
                    {
                        d_s = start.Day;
                    }

                    if (end.Year == CurrentDate.Year && end.Month == CurrentDate.Month)
                    {
                        d_e = end.Day;
                    }

                    for (int i = d_s; i < d_e; i++)
                    {
                        data = ItemList.Find(x => x.Index == i);
                        if (data != null)
                        {
                            data.EventList.Add(e);
                        }
                    }
                }
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Draws calendar item according to dates
        /// </summary>
        private void DrawItems(Graphics graphics)
        {
            foreach (var row in listRows)
            {
                if (row.IsVisible)
                {
                    foreach (var item in row.Items)
                    {
                        var isSelected = item == _selectedItem;
                        var level      = listRows.IndexOf(row);


                        DateTime dStart = item.StartDate.Date;
                        DateTime dEnd   = item.EndDate.Date;

                        // Looks for the left x coord according to date
                        var x1 = ColumnCoord.Where(d => d.DateValue.Date == dStart).SingleOrDefault();
                        // Gets y coord according to row
                        var yCoord = RowCoord.Where(d => d.RowIndex == level).SingleOrDefault();
                        // Looks for the right x coord according to date
                        var x2 = ColumnCoord.Where(d => d.DateValue.Date == dEnd).SingleOrDefault();

                        int y = yCoord.FirstCoord + item.Layer * (ItemHeight + shadowItemRect);

                        int       width;
                        Rectangle rect;
                        // if Start Date and End Date in the week interval
                        if (dStart >= CurrentDate && dEnd <= CurrentDate.AddDays(_dayCount - 1))
                        {
                            width = x2.SecondCoord - x1.FirstCoord - 2 * smallWhiteRectWidth;

                            if (item.Rectangle.Width == 0 && item.Rectangle.Height == 0)
                            {
                                rect           = new Rectangle(x1.FirstCoord + smallWhiteRectWidth, y, width, ItemHeight);
                                item.Rectangle = rect;
                            }
                            else
                            {
                                rect = item.Rectangle;
                            }

                            DrawItemRect(graphics, item.Subject, rect.X, rect.Y, rect.Width, rect.Height, true, true,
                                         item.BackColor, isSelected);
                        }

                        // if End Date is not in the week interval
                        if (dStart >= CurrentDate && dEnd > CurrentDate.AddDays(_dayCount - 1) && x1 != null)
                        {
                            width = Width - x1.FirstCoord;
                            if (item.Rectangle.Width == 0 && item.Rectangle.Height == 0)
                            {
                                rect           = new Rectangle(x1.FirstCoord + smallWhiteRectWidth, y, width, ItemHeight);
                                item.Rectangle = rect;
                            }
                            else
                            {
                                rect = item.Rectangle;
                            }


                            DrawItemRect(graphics, item.Subject, rect.X, rect.Y, rect.Width, rect.Height, true, false,
                                         item.BackColor, isSelected);
                        }

                        // if Start Date is not in the week interval
                        if (dStart < CurrentDate && dEnd <= CurrentDate.AddDays(_dayCount - 1) && x2 != null)
                        {
                            width = x2.SecondCoord - LeftMargin - smallWhiteRectWidth;
                            if (item.Rectangle.Width == 0 && item.Rectangle.Height == 0)
                            {
                                rect           = new Rectangle(LeftMargin, y, width, ItemHeight);
                                item.Rectangle = rect;
                            }
                            else
                            {
                                rect = item.Rectangle;
                            }

                            DrawItemRect(graphics, item.Subject, rect.X, rect.Y, rect.Width, rect.Height, false, true,
                                         item.BackColor, isSelected);
                        }

                        // if Start Date is not in the week interval
                        if (dStart < CurrentDate && dEnd > CurrentDate.AddDays(_dayCount - 1))
                        {
                            width = Width - LeftMargin;
                            if (item.Rectangle.Width == 0 && item.Rectangle.Height == 0)
                            {
                                rect           = new Rectangle(LeftMargin, y, width, ItemHeight);
                                item.Rectangle = rect;
                            }
                            else
                            {
                                rect = item.Rectangle;
                            }

                            DrawItemRect(graphics, item.Subject, rect.X, rect.Y, rect.Width, rect.Height, false, true,
                                         item.BackColor, isSelected);
                        }
                    }
                }
            }
        }
Ejemplo n.º 12
0
        protected override void OnMouseDown(MouseEventArgs e)
        {
            mouseClickPosition       = new Point(e.X, e.Y);
            mouseClickScrollPosition = mouseClickPosition - new Size(AutoScrollPosition);

            if (!Focused)
            {
                Focus();
            }

            var row = RowCoord.Where(d => (isNumberInRange(mouseClickScrollPosition.Y, d.FirstCoord, d.SecondCoord))).SingleOrDefault();

            _selectedRow = row != null ? row.RowIndex : -1;

            var column =
                ColumnCoord.Where(d => (isNumberInRange(mouseClickScrollPosition.X, d.FirstCoord, d.SecondCoord))).SingleOrDefault();


            if (column != null)
            {
                _selectedColumn   = column.Column;
                _selectedCellDate = CurrentDate.AddDays(SelectedColumn);
            }

            if (listRows.Count > 0 && _selectedRow != -1)
            {
                var plannerRow = listRows.ElementAt(_selectedRow);
                _selectedItem = GetItemAt(mouseClickScrollPosition, plannerRow.Items);
            }

            switch (State)
            {
            case PlannerState.Idle:
                if (_selectedItem != null)
                {
                    itemOnState        = _selectedItem;
                    itemOnStateChanged = false;

                    durationStart = itemOnState.StartDate.Date.Subtract(column.DateValue.Date);
                    durationEnd   = itemOnState.EndDate.Date.Subtract(column.DateValue.Date);
                    if (itemOnState.ResizeStartDateZone(mouseClickScrollPosition))
                    {
                        SetState(PlannerState.ResizingItem);
                        itemOnState.SetIsResizingStartDate(true);
                    }
                    else if (itemOnState.ResizeEndDateZone(mouseClickScrollPosition))
                    {
                        SetState(PlannerState.ResizingItem);
                        itemOnState.SetIsResizingEndDate(true);
                    }
                    else
                    {
                        rowNumer = _selectedRow;
                        SetState(PlannerState.DraggingItem);
                    }
                }
                break;

            case PlannerState.DraggingItem:
                break;

            case PlannerState.ResizingItem:
                break;

            case PlannerState.EditingItemText:
                break;
            }


            if (row != null && column != null && listRows.Count > 0)
            {
                var rowClicked = listRows.ElementAt(_selectedRow);
                planner.OnRowClick(new RowEventArgs(rowClicked));
                Invalidate();
            }

            if (mouseClickScrollPosition.X < LeftMargin)
            {
                try
                {
                    var rowClicked = listRows.ElementAt(_selectedRow);
                    if (e.Button == MouseButtons.Left)
                    {
                        rowClicked.IsExpanded = !rowClicked.IsExpanded;
                    }
                    planner.OnRowLeftColumnClick(new RowClickEventArgs(rowClicked, e.Button), listRows.IndexOf(rowClicked));
                    rowClicked.LeftMarginBackColor = rowClicked.LeftMarginOldBackColor;
                }
                catch (System.ArgumentOutOfRangeException)
                {
                    Debug.WriteLine("It happened");
                }
            }

            base.OnMouseDown(e);
        }
Ejemplo n.º 13
0
 private void SubtractSevenDays()
 {
     CurrentDate = CurrentDate.AddDays(-7);
     CurrentWeek = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(CurrentDate, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
     FillSchedule();
 }
Ejemplo n.º 14
0
        public void BuildGrid()
        {
            DateTime previousMonth       = _currentMonth.AddMonths(-1);
            var      daysInPreviousMonth = DateTime.DaysInMonth(previousMonth.Year, previousMonth.Month);
            var      daysInMonth         = DateTime.DaysInMonth(_currentMonth.Year, _currentMonth.Month);

            weekdayOfFirst = (int)_currentMonth.DayOfWeek;
            var lead = daysInPreviousMonth - (weekdayOfFirst - 1);

            // build last month's days
            for (int i = 1; i <= weekdayOfFirst; i++)
            {
                var viewDay = new DateTime(_currentMonth.Year, _currentMonth.Month, i);
                var dayView = new CalendarDayView();
                dayView.Frame = new RectangleF((i - 1) * 46 - 1, 0, 47, 45);
                dayView.Date  = viewDay;
                dayView.Text  = lead.ToString();
                AddSubview(dayView);
                _dayTiles.Add(dayView);
                lead++;
            }

            var position = weekdayOfFirst + 1;
            var line     = 0;

            // current month
            for (int i = 1; i <= daysInMonth; i++)
            {
                var viewDay = new DateTime(_currentMonth.Year, _currentMonth.Month, i);
                var dayView = new CalendarDayView
                {
                    Frame    = new RectangleF((position - 1) * 46 - 1, line * 44, 47, 45),
                    Today    = (CurrentDate.Date == viewDay.Date),
                    Text     = i.ToString(),
                    m_phase  = _calendarMonthView.stageForDayDelegate == null ? 0 : _calendarMonthView.stageForDayDelegate((DateTime)viewDay),
                    Active   = true,
                    Tag      = i,
                    Selected = (i == CurrentDate.AddDays(1).Day)
                };
                dayView.Date = viewDay;
                updateDayView(dayView);

                if (dayView.Selected)
                {
                    SelectedDayView = dayView;
                }

                AddSubview(dayView);
                _dayTiles.Add(dayView);

                position++;
                if (position > 7)
                {
                    position = 1;
                    line++;
                }
            }

            //next month
            if (position != 1)
            {
                int dayCounter = 1;
                for (int i = position; i < 8; i++)
                {
                    var viewDay = new DateTime(_currentMonth.Year, _currentMonth.Month, i);
                    var dayView = new CalendarDayView
                    {
                        Frame = new RectangleF((i - 1) * 46 - 1, line * 44, 47, 45),
                        Text  = dayCounter.ToString(),
                    };
                    dayView.Date = viewDay;
                    updateDayView(dayView);

                    AddSubview(dayView);
                    _dayTiles.Add(dayView);
                    dayCounter++;
                }
            }

            Frame = new RectangleF(Frame.Location, new SizeF(Frame.Width, (line + 1) * 44));

            Lines = (position == 1 ? line - 1 : line);

            if (SelectedDayView != null)
            {
                this.BringSubviewToFront(SelectedDayView);
            }
        }
Ejemplo n.º 15
0
        public async Task <CommandResponse <Domain.Models.Vote> > SaveVote(Domain.Models.Vote vote)
        {
            DemandAuthentication();

            var newDataModel = VoteDomainMaps.Map(vote);
            var domainModel  = vote;

            //UPDATE
            if (newDataModel.ID > 0)
            {
                var existingDataModel = await GetVoteDataModel(newDataModel.ID);

                //Check some basics
                if (existingDataModel == null)
                {
                    return(CommandResponse.FromStatus <Domain.Models.Vote>(null, Status.Error, "Vote can not be found"));
                }
                if (!existingDataModel.CreatedBy.IsEqual(User.Identity.Name) && !User.IsInAnyRole(new[] { UserRole.GlobalAdmin, UserRole.Admin }))
                {
                    return(CommandResponse.FromStatus <Domain.Models.Vote>(null, Status.Error, "Vote can not be edited by current user"));
                }
                if (existingDataModel.StartDate <= CurrentDate)
                {
                    return(CommandResponse.FromStatus <Domain.Models.Vote>(null, Status.Error, "Vote can not be edited once voting has begun"));
                }

                //TODO: Verify incoming model ids all belong to this vote
                var restrictionsAreBelongToUs = newDataModel.VoteRestrictions.Where(x => x.ID > 0).All(x => existingDataModel.VoteRestrictions.Any(e => e.ID == x.ID));
                if (!restrictionsAreBelongToUs)
                {
                    return(CommandResponse.FromStatus <Domain.Models.Vote>(null, Status.Error, "Message integrity violated (Restrictions)"));
                }
                var optionsAreBelongToUs = newDataModel.VoteOptions.Where(x => x.ID > 0).All(x => existingDataModel.VoteOptions.Any(e => e.ID == x.ID));
                if (!optionsAreBelongToUs)
                {
                    return(CommandResponse.FromStatus <Domain.Models.Vote>(null, Status.Error, "Message integrity violated (Options)"));
                }
                var outcomesAreBelongToUs = newDataModel.VoteOptions.Where(x => x.ID > 0).SelectMany(x => x.VoteOutcomes.Where(o => o.ID > 0)).All(x => existingDataModel.VoteOptions.SelectMany(y => y.VoteOutcomes).Any(e => e.ID == x.ID));
                if (!outcomesAreBelongToUs)
                {
                    return(CommandResponse.FromStatus <Domain.Models.Vote>(null, Status.Error, "Message integrity violated (Outcomes)"));
                }



                existingDataModel.LastEditDate     = CurrentDate;
                existingDataModel.Title            = newDataModel.Title;
                existingDataModel.Content          = newDataModel.Content;
                existingDataModel.FormattedContent = newDataModel.FormattedContent;

                newDataModel.VoteOptions.ForEachIndex((option, index) =>
                {
                    //TODO: Ensure ID belongs to proper vote (aka fuzzy will exploit this)
                    if (option.ID > 0)
                    {
                        //Update Existing
                        var existingOption              = existingDataModel.VoteOptions.FirstOrDefault(x => x.ID == option.ID);
                        existingOption.Title            = option.Title;
                        existingOption.Content          = option.Content;
                        existingOption.FormattedContent = option.FormattedContent;
                        existingOption.SortOrder        = index;

                        option.VoteOutcomes.ForEachIndex((outcome, oIndex) =>
                        {
                            if (outcome.ID > 0)
                            {
                                var existingOutcome  = existingDataModel.VoteOptions[index].VoteOutcomes.FirstOrDefault(x => x.ID == outcome.ID);
                                existingOutcome.Type = outcome.Type;
                                existingOutcome.Data = outcome.Data;
                            }
                            else
                            {
                                var newOutcome  = new VoteOutcome();
                                newOutcome.Type = outcome.Type;
                                newOutcome.Data = outcome.Data;
                                existingOption.VoteOutcomes.Add(newOutcome);
                            }
                        });
                        //Remove deleted outcomes
                        var deletedOutcomes = existingOption.VoteOutcomes.Where(c => !option.VoteOutcomes.Any(n => c.ID == n.ID)).ToList();
                        deletedOutcomes.ForEach(x => existingOption.VoteOutcomes.Remove(x));
                    }
                    else
                    {
                        //Add new
                        var newOption              = new Data.Models.VoteOption();
                        newOption.Title            = option.Title;
                        newOption.Content          = option.Content;
                        newOption.FormattedContent = option.FormattedContent;
                        newOption.SortOrder        = index;
                        existingDataModel.VoteOptions.Add(newOption);

                        option.VoteOutcomes.ForEachIndex((outcome, oIndex) =>
                        {
                            var newOutcome  = new VoteOutcome();
                            newOutcome.Type = outcome.Type;
                            newOutcome.Data = outcome.Data;
                            newOption.VoteOutcomes.Add(newOutcome);
                        });
                    }
                });
                //Remove deleted options
                var deletedOptions = existingDataModel.VoteOptions.Where(c => !newDataModel.VoteOptions.Any(n => c.ID == n.ID)).ToList();
                deletedOptions.ForEach(x => existingDataModel.VoteOptions.Remove(x));

                //handle restrictions
                newDataModel.VoteRestrictions.ForEachIndex((restriction, index) =>
                {
                    if (restriction.ID > 0)
                    {
                        //Update Existing
                        var existingRestriction  = existingDataModel.VoteRestrictions.FirstOrDefault(x => x.ID == restriction.ID);
                        existingRestriction.Type = restriction.Type;
                        existingRestriction.Data = restriction.Data;
                    }
                    else
                    {
                        //Add new
                        var newRestriction  = new Data.Models.VoteRestriction();
                        newRestriction.Type = restriction.Type;
                        newRestriction.Data = restriction.Data;
                        existingDataModel.VoteRestrictions.Add(newRestriction);
                    }
                });
                //Remove deleted options
                var deletedRestrictions = existingDataModel.VoteRestrictions.Where(c => !newDataModel.VoteRestrictions.Any(n => c.ID == n.ID)).ToList();
                deletedRestrictions.ForEach(x => existingDataModel.VoteRestrictions.Remove(x));

                await _db.SaveChangesAsync();

                return(CommandResponse.FromStatus <Domain.Models.Vote>(existingDataModel.Map(), Status.Success));
            }
            //NEW
            else
            {
                newDataModel.CreatedBy    = User.Identity.Name;
                newDataModel.CreationDate = CurrentDate;

                //TODO: Set start end dates according to logic
                newDataModel.StartDate = CurrentDate.AddDays(7);
                newDataModel.EndDate   = CurrentDate.AddDays(14);

                _db.Vote.Add(newDataModel);
                await _db.SaveChangesAsync();

                domainModel = VoteDomainMaps.Map(newDataModel);

                return(CommandResponse.FromStatus <Domain.Models.Vote>(newDataModel.Map(), Status.Success));
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Element a day step on this universe.
        /// </summary>
        ///

        public void RunDayStep()
        {
            ///<Behnam (2016.01.07)>
            ///<Comment>To apply air temperature cut only on canopy temperature, instead of air temperature.
            ///Old setting will be preserved, just in case in the future it is required to work on air temperature.
            ///But the Boolean flag is now applied on canopy temperature.
            ///Weather_.isUnlimitedTemperature = isUnlimitedTemperature;
            Weather_.isUnlimitedTemperature = false;
            ///</Behnam>
            Soil_.isUnlimitedWater       = Crop_.isUnlimitedWater = isUnlimitedWater;
            Soil_.isUnlimitedNitrogen    = Crop_.isUnlimitedNitrogen = isUnlimitedNitrogen;
            Soil_.isUnlimitedTemperature = Crop_.isUnlimitedTemperature = isUnlimitedTemperature;

            ///<Comment>Cumulative air temperature from sowing (to calculate mean air temperature for different periods)</Comment>
            if (GrowthDay > 0)
            {
                CumAirTempFromSowing = GrowthDay * Weather_.MeanTemp(CurrentDate, GrowthDay);
            }
            ///</Behnam>
            ///Loic, Cumulative maximum air temperature from sowing
            if (GrowthDay > 0)
            {
                CumMaxAirTempFromSowing += Weather_.MaxTemp(CurrentDate);
            }
            ///Loic, Cumulative maximum canopy temperature from sowing
            if (GrowthDay > 0)
            {
                CumMaxCanopyTempFromSowing += Soil_.MaximumCanopyTemperature;
            }

            Soil_.InitDayStep(Crop_.RootLength);
            Soil_.MeanAirTemperature = Weather_.MeanTemp(CurrentDate);

            ///<Behnam (2016.01.19)>
            ///<Comment>Trying to organize the Universe class, contents were moved to two new methods
            ///With each application of N, WaterAppWithNApp mm of water is added, if needed</Comment>
            double TotalWApplied = 0;

            Soil_.Irrigate(Weather_.Rain(CurrentDate));
            TotalWApplied = Weather_.Rain(CurrentDate);

            NAdded = 0;

            double TotalNApplied = 0;

            TotalNApplied = ApplyResources_ByDate(TotalNApplied, ref TotalWApplied);
            TotalNApplied = ApplyResources_ByGrowthStage(TotalNApplied, ref TotalWApplied);

            ///</Behnam>

            Crop_.InitDayStep(thermalTimeWrapper_.getDeltaTT(Delta.Remobilization));

            double vp;

            if (!Weather_.IsWindAndVpDefined())
            {
                // from the formulation of Murray 1967, Journal of Aplplied Meteorology 1:203-204
                // The minimum air temperature is used as a proxy for dew temperature
                vp = (0.6108 * Math.Exp((17.27 * Weather_.MinTemp(CurrentDate)) / (Weather_.MinTemp(CurrentDate) + 237.3))) * 10; // multiplied by 10 to convert kPa to hPa
            }
            else
            {
                vp = Weather_.Vp(CurrentDate);
            }


            // Energy Balance
            // Boundary layer conductance
            // OUTPUT UNIT: m d-1
            double wind;

            if (Weather_.IsWindAndVpDefined() == false)
            {
                wind = 240 * 1000;                          // Assumes wind = 240 km/day converted to m/day
            }
            else
            {
                const double minWind = 100.0;
                wind = Math.Max(Weather_.Wind(CurrentDate), minWind) * 1000;
            }
            //

            meteorologyWrapper_.EstimateMeteo(Weather_.MeanTemp(CurrentDate), Weather_.MinTemp(CurrentDate), Weather_.MinTemp(CurrentDate.AddDays(1)), Weather_.MaxTemp(CurrentDate), Weather_.MinTemp(CurrentDate.AddDays(-1)), ShootTemperature_.MinShootTemperature, ShootTemperature_.MaxShootTemperature, vp, Weather_.Rad(CurrentDate), wind);

            Soil_.RunDayStep(meteorologyWrapper_.RadTopAtm,
                             Weather_.IsWindAndVpDefined(),
                             vp,
                             Weather_.Rad(CurrentDate),
                             Weather_.MinTemp(CurrentDate),
                             Weather_.MaxTemp(CurrentDate),
                             Weather_.MeanTemp(CurrentDate),
                             meteorologyWrapper_.HourlyAirTemperature,
                             wind,
                             Weather_.WeekTemp(CurrentDate),
                             meteorologyWrapper_.HSlope,
                             meteorologyWrapper_.VPDair,
                             Crop_.Tau,
                             Crop_.SumInternodesLength,
                             Crop_.PotentialWaterOnLeaves,
                             Crop_.RootLength,
                             Crop_.LeafNumber,
                             meteorologyWrapper_.HourlyVPDAir,
                             meteorologyWrapper_.HourlyRadiation,
                             Crop_.Ntip,
                             meteorologyWrapper_.RH
                             );


            ShootTemperature_.isUnlimitedTemperature = isUnlimitedTemperature;
            ShootTemperature_.Estimate(Crop_.LeafNumber, Soil_.MinimumCanopyTemperature, Soil_.MaximumCanopyTemperature, Soil_.HourlyCanopyTemperature,
                                       Soil_.SoilMinTemperature, Soil_.SoilMaxTemperature, Soil_.HourlySoilTemperature);

            Crop_.InitDayStepRoot(thermalTimeWrapper_.getCumulTT(Delta.Remobilization), Soil_.NavForRoot);

            //Quantity of Ni to remove from soil
            double soilNinc = 0;

            ///<Behnam (2016.01.08)>
            ///<Comment>Directly using shoot temperature instead of checking leaf number
            /// and selecting between soil and canopy temperature</Comment>
            ///
            thermalTimeWrapper_.EstimateDailyThermalTime(Weather_.MinTemp(CurrentDate), Weather_.MaxTemp(CurrentDate),
                                                         Soil_.SoilMinTemperature, Soil_.SoilMaxTemperature, ShootTemperature_.MinShootTemperature,
                                                         ShootTemperature_.MaxShootTemperature, ShootTemperature_.ShootHourlyTemperature, meteorologyWrapper_.HourlyAirTemperature, Crop_.getPhaseValue());
            ///</Behnam>

            soilNinc = Crop_.Grow(meteorologyWrapper_.RadTopAtm,
                                  thermalTimeWrapper_.CumulTT,
                                  thermalTimeWrapper_.getDeltaTT(Delta.Shoot),
                                  thermalTimeWrapper_.getDeltaTT(Delta.PhenoMaize),
                                  thermalTimeWrapper_.getDeltaTT(Delta.Remobilization),
                                  thermalTimeWrapper_.getDeltaTT(Delta.LeafSenescence),
                                  ShootTemperature_.MinShootTemperature,
                                  ShootTemperature_.MaxShootTemperature,
                                  Weather_.Rad(CurrentDate),
                                  Weather_.PAR(CurrentDate),
                                  Soil_.DBF,
                                  Soil_.SoilDepth,
                                  Soil_.DEBF,
                                  Soil_.DGF,
                                  meteorologyWrapper_.DayLength,
                                  Soil_.FPAW, meteorologyWrapper_.VPDairCanopy, Soil_.HourlyCanopyTemperature, Soil_.VPDeq);

            if (!isUnlimitedNitrogen)
            {
                Soil_.RemoveN(soilNinc);
            }

            Soil_.FinishDayStep();
        }