Пример #1
0
        /// <summary>
        /// Realizacja algorytmu MIS (wybór zbioru niezależnego)
        /// </summary>
        /// <returns>Status po zakonczeniu wyborów </returns>
        private async Task <ElectionStatus> MIS()
        {
            byte           v;
            ElectionStatus status = ElectionStatus.None;

            for (int i = 0; i < jankielManager.FirstMISForLength * 5; i++)
            {
                double probabilityOfChoose = 1.0 / Math.Pow(2, jankielManager.FirstMISForLength - i);
                for (int j = 0; j < jankielManager.SecondMISForLength; j++)
                {
                    v = 0;
                    if (random.NextDouble() < probabilityOfChoose)
                    {
                        v = 1;
                    }
                    //------Gwarancja że jesli ktos juz wie, że będzie grał------
                    //to jego status się nie zmieni
                    if (status == ElectionStatus.Selected)
                    {
                        v = 1;
                    }
                    if (status == ElectionStatus.Lose)
                    {
                        v = 0;
                    }
                    //---------------------------------------------------------
                    // Wyslanie wiadomosci do sąsiadów z informacją o swoim "głosie" ( w wyborach )
                    await jankielManager.SendMsg(new VoteMessage(Name, v));

                    // Czekanie na głosy sąsiadów, oraz sprawdzenie czy któryś z nich nie nie wysłał 1 w wiadomosci
                    bool isBRecived = jankielManager.RecivedB();
                    if (isBRecived)
                    {
                        v = 0;
                    }

                    // nikt nikt z sąsiadów nie wysłał 1, oznacza to że bierzący proces został wybrany
                    if (v == 1)
                    {
                        status = ElectionStatus.Selected;
                    }
                    //----------------------------------------------------------
                    //druga wymiana wiadomosci
                    // ponowne wysłanie v do sąsiadów by poinformować czy wartość v zmieniła się po otrzymaniu od nich wiadomosci
                    await jankielManager.SendMsg(new VoteMessage(Name, v));

                    isBRecived = jankielManager.RecivedB();
                    // jesli v jest 0 oraz otrzymalismy od jakiegos sąsiada 1 to proces ten przegrywa wybory w przeciwnym przypadku
                    //jesli v = 0 oraz nie otrzymalismy zadnej jedynki od sąsiadów status nadal jest nieznany
                    if (v == 0 && isBRecived)
                    {
                        status = ElectionStatus.Lose;
                    }
                }
            }
            return(status);
        }
Пример #2
0
        public async Task <ActionResult> SelectElectionCource(int?id)
        {
            if (id == null)
            {
                return(Content(null));
            }
            string            resultmsg = id.Value.ToString();
            string            userName  = HttpContext.User.Identity.Name;
            Term              term      = _SettingService.GetOptionsForEdit().Term;
            Student           stu       = _StudentService.GetByUserId(_UserService.GetUserByUserName(userName).Id);
            PeresentedCourses pc        = _PeresentedCoursesService.GetById(id.Value);

            ElectionStatus status = _ElectionService.Choosen(stu.Id, pc.Id);

            switch (status)
            {
            case ElectionStatus.Success:
            {
                var adv = new Election
                {
                    Student          = _StudentService.GetById(stu.Id),
                    PeresentedCource = pc
                };
                _ElectionService.Insert(adv);

                _PeresentedCoursesService.Decrease_Capacity_Remained(pc.Id);
                await _unitOfWork.SaveAllChangesAsync(false);

                resultmsg = "Success";
            }
            break;

            case ElectionStatus.CannotSelectCapacityFull:
                resultmsg = "Cannot Select Beacuse Capacity of Class is Full";
                break;

            case ElectionStatus.CannotSelectOutOfUnit:
                resultmsg = "Cannot Select Beacuse Out Of Your Max Unit Allowed";
                break;

            case ElectionStatus.CannotSelectPrevSelected:
                resultmsg = "Cannot Select Beacuse You Pereviouse Choose This Class";
                break;
            }

            await _unitOfWork.SaveChangesAsync();

            CacheManager.InvalidateChildActionsCache();
            return(Json(new { msg = resultmsg }, JsonRequestBehavior.AllowGet));
        }
        private async void DoStart()
        {
            bool result = false;

            //var testAny = _context.PartyLists.Any();
            //if (testAny)
            //{
            await DialogHost.Show(new OkCancelMessageDialog()
            {
                DataContext = "Do you want to start the election?"
            },
                                  "RootDialog", delegate(object sender, DialogClosingEventArgs args)
            {
                if (Equals(args.Parameter, "Ok"))
                {
                    //args.Cancel();
                    try
                    {
                        var es = new ElectionStatus()
                        {
                            Start = true,
                            End   = false
                        };
                        _context.ElectionStatus.Add(es);
                        _context.SaveChanges();
                        result = true;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        result = false;
                    }
                    args.Session.UpdateContent(new OkMessageDialog()
                    {
                        DataContext = result ? "Election Started" : "Failed to start"
                    });
                }
            });

            //}
            //await DialogHost.Show(new OkMessageDialog() {DataContext = "No Candidates for Election"}, "RootDialog");
        }
Пример #4
0
        public async void Run()
        {
            Console.WriteLine($"Jankiel {Name} Czeka na start ...");
            jankielManager.WaitForStart();
            ElectionStatus status = ElectionStatus.None;
            int            i      = 0;

            //Dopoki nie bylismy wybrani to znaczy ze nie gralismy jeszcze koncertu
            while (status != ElectionStatus.Selected)
            {
                //informacja dla sąsiadów o gotowosci do rozpączecia rundy
                await jankielManager.SendMsg(new StartTourMessage(Name));

                //oczekiwanie na potwierdzenie od swoich sąsiadów
                jankielManager.WaitStartTour();

                Console.WriteLine($"{Name} Start rundy {++i}");

                //wybory ktory z jankieli będzie grał
                status = await MIS();

                Console.WriteLine($"Jankiel {Name} status : {status}");
                if (status == ElectionStatus.Selected)
                {
                    //jankiel został wybrany wiec może grać
                    Console.WriteLine($"Jankiel {Name} gra koncert !");
                    Thread.Sleep(2000);
                }

                //informacja dla sąsiadów ze jankiel skonczył turę, wraz z informacją czy w tej turze grał koncert
                // jesli tak to sąsiedzi w przyszył turach nie będą czekać na informacje pochodzące od tego jankiela
                await jankielManager.SendMsg(new FinishedTourMessage(Name, status == ElectionStatus.Selected));

                //czekanie na informacje od sąsiadów
                jankielManager.WaitFinishTour();
                Console.WriteLine($"{Name} koniec rundy {i}");
            }
            Console.WriteLine($"Jankiel {Name} skończył ...");
        }
Пример #5
0
        public virtual async Task <ActionResult> Create(AddElectionViewModel viewModel)
        {
            Requiredneeds(true);
            if (ModelState.IsValid)
            {
                try
                {
                    var adv = new Election
                    {
                        Student          = _StudentService.GetById(viewModel.Student_Id),
                        PeresentedCource = _PeresentedCoursesService.GetById(viewModel.PeresentedCource_Id)
                    };
                    ElectionStatus status = _ElectionService.Choosen(viewModel.Student_Id, viewModel.PeresentedCource_Id);
                    switch (status)
                    {
                    case ElectionStatus.Success:
                    {
                        _ElectionService.Insert(adv);

                        _PeresentedCoursesService.Decrease_Capacity_Remained(viewModel.PeresentedCource_Id);
                        await _unitOfWork.SaveAllChangesAsync(false);

                        return(RedirectToAction("Index", "Home"));
                    }

                    case ElectionStatus.CannotSelectCapacityFull:
                        ModelState.AddModelError("UserName", "Cannot Select Beacuse Capacity of Class is Full");
                        break;

                    case ElectionStatus.CannotSelectOutOfUnit:
                        ModelState.AddModelError("UserName", "Cannot Select Beacuse Out Of Your Max Unit Allowed");
                        break;

                    case ElectionStatus.CannotSelectPrevSelected:
                        ModelState.AddModelError("UserName", "Cannot Select Beacuse You Pereviouse Choose This Class");
                        break;
                    }

                    await _unitOfWork.SaveChangesAsync();

                    CacheManager.InvalidateChildActionsCache();
                    return(RedirectToAction("Index", "Enrolment"));
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException e)
                {
                    string s = "";
                    foreach (var eve in e.EntityValidationErrors)
                    {
                        s += String.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                           eve.Entry.Entity.GetType().Name, eve.Entry.State);
                        foreach (var ve in eve.ValidationErrors)
                        {
                            s += String.Format("- Property: \"{0}\", Error: \"{1}\"",
                                               ve.PropertyName, ve.ErrorMessage);
                        }
                    }
                    ViewBag.err = s;
                }
            }
            return(View(viewModel));
        }