Example #1
0
        private static StudyPlan scheduleRemaning(IEnumerable <PlannedUnit> remainingUnits, StudyPlan plannedUnits)
        {
            try
            {
                if (!remainingUnits.Any())
                {
                    return(plannedUnits);
                }

                PlannedUnit schedulableUnit =
                    remainingUnits.First(
                        unit => unit.possibleSemesters.Where(
                            sem => StudyPlannerModel.isEnrollableIn(unit.code, sem, plannedUnits)
                            ).Any()
                        );

                foreach (var sem in schedulableUnit.possibleSemesters)
                {
                    if (StudyPlannerModel.isEnrollableIn(schedulableUnit.code, sem, plannedUnits))
                    {
                        UnitInPlan newUnitPlan     = new UnitInPlan(schedulableUnit.code, schedulableUnit.studyArea, sem);
                        StudyPlan  scheduleEachSem = scheduleRemaning(remainingUnits.Where(unit => unit.code != schedulableUnit.code), plannedUnits.Concat(new UnitInPlan[] { newUnitPlan }));
                        if (scheduleEachSem != null)
                        {
                            return(scheduleEachSem);
                        }
                    }
                }
            }catch (Exception ex) //if can't find any schedulable unit while there are still units needed to add to the plan
            {
                return(null);
            }

            return(null); //if can't add all the remaining units
        }
Example #2
0
        private static Semester bestAchievable(StudyPlan plan)
        {
            int      totalUnits   = plan.Count();
            Offering nextOffering = getNextOffering(totalUnits, currentSemester.offering);

            return(new Semester(currentSemester.year + (totalUnits - 1) / 8, nextOffering));
        }
Example #3
0
        /// <summary>
        /// 插入新计划
        /// </summary>
        /// <param name="plan">学习计划</param>
        /// <param name="courses">学习计划关联的课程</param>
        /// <param name="usersPlan">用户的学习计划</param>
        /// <returns></returns>
        public static bool Insert(StudyPlan plan, IEnumerable <StudyPlanCourse> courses, IEnumerable <UserStudyPlan> usersPlan)
        {
            if (plan == null)
            {
                return(false);
            }

            if (courses == null || courses.Count() < 1)
            {
                return(false);
            }

            if (usersPlan == null || usersPlan.Count() < 1)
            {
                return(false);
            }

            using (var db = new DataContext())
            {
                db.StudyPlan.Add(plan);
                db.StudyPlanCourse.AddRange(courses);
                db.UserStudyPlan.AddRange(usersPlan);

                return(db.SaveChanges() > 0);
            }
        }
Example #4
0
        public ActionResult AddPlanToStudent(String registernumber, String documentid,
                                             String plancode)
        {
            if (String.IsNullOrEmpty(registernumber) || String.IsNullOrEmpty(documentid) || String.IsNullOrEmpty(plancode))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Error, vuelva a intentarlo de nuevo "));
            }

            //Validate StudyPlan Exit
            StudyPlan sp = this._studyPlanService.Find(sp1 => sp1.Code.Equals(plancode));

            Student st = this._studentService.Find(s => s.RegisterNumber.Equals(registernumber) && s.DocumentID.Equals(documentid));

            if (st != null && sp != null)
            {
                st.StudentPlans.Add(new StudentPlan()
                {
                    Created     = DateTime.Now,
                    StudyPlanFK = sp.Code,
                });

                _studentService.Update(st);
                var data = new { Message = "Plan Asociado satisfactoriamente", status = "OK" };

                return(Json(JsonConvert.SerializeObject(data, Formatting.Indented, new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                }
                                                        )));
            }
            else
            {
                return(new HttpStatusCodeResult(HttpStatusCode.NotFound, "Error, vuelva a intentarlo de nuevo "));
            }
        }
        public static Semester bestPossible(StudyPlan plan, Semester firstSem)
        {
            if (plan is null)
            {
                return(null);
            }

            int subjects  = plan.Count();
            int semesters = (int)Math.Ceiling(subjects / 4.0); // total semesters = ceiling of # of subjects / 4
            int years     = semesters / 2;

            if (firstSem.offering.IsSemester1)
            {
                if (semesters % 2 == 1) // semester stays the same
                {
                    return(new Semester(firstSem.year + years, Offering.Semester1));
                }

                // change semesters as well
                return(new Semester(firstSem.year + years - 1, Offering.Semester2)); // years = current year + years - 1
            }
            else
            {
                if (semesters % 2 == 1)
                {
                    return(new Semester(firstSem.year + years, Offering.Semester2));;
                }
                return(new Semester(firstSem.year + years, Offering.Semester1));
            }
        }
Example #6
0
        public async Task <IActionResult> Edit(int id, [Bind("ID,Name,Content,UniversityID")] StudyPlan studyPlan)
        {
            if (id != studyPlan.ID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(studyPlan);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!StudyPlanExists(studyPlan.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["UniversityID"] = new SelectList(_context.Universities, "ID", "ID", studyPlan.UniversityID);
            return(View(studyPlan));
        }
        public async Task <IActionResult> Update(StudyPlanDto studyPlanDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            StudyPlan studyPlan = _mapper.Map <StudyPlan>(studyPlanDto);

            if (studyPlan == null)
            {
                return(NotFound());
            }


            try
            {
                await _studyPlanService.Update(studyPlan);

                return(Ok("Plan Başarıyla Güncellendi"));
            }
            catch
            {
                return(BadRequest("Plan Güncelleme İşlemi Başarısız"));
            }
        }
Example #8
0
        public Course DoGenerateCourse(Teacher teacher, Subject subject, StudyPlan studyPlan)
        {
            // Validations:
            // - Schedule of Teacher
            // - Valid StudyPlan
            // - etc.

            var studyPlanDetails = _studyPlanDetailRepository
                                   .ObtainDetailsByStudentPlanId(studyPlan.Id)
                                   .ToList();

            if (studyPlanDetails.Count == 0)
            {
                throw new Exception("No details for this StudyPlan");
            }

            var studyPlanDetail = studyPlanDetails.FirstOrDefault(x => x.Subject.Id == subject.Id);

            if (studyPlanDetail == null)
            {
                throw new Exception("No detail found for this StudyPlan and Subject.");
            }

            var course = new Course {
                Id = new Guid(), HeadTeacher = teacher, Subject = subject, StudyPlanDetail = studyPlanDetail
            };

            var courseAdded = _courseRepository.Add(course);

            return(courseAdded);
        }
Example #9
0
        public static IEnumerable <StudyPlan> TryToImproveSchedule(StudyPlan plan)
        {
            // TODO: Fixme
            Semester first        = currentSemester;
            Semester last         = FSharpSchedulingWizard.lastSemester(plan);
            Semester bestPossible = bestAchievable(plan);

            //variables for mutating to get the results using while loop
            IEnumerable <StudyPlan> bestPlans = new StudyPlan[] { };
            Semester targetGraduation         = StudyPlannerModel.previousSemester(last);

            while (targetGraduation.CompareTo(bestPossible) >= 0)
            {
                IEnumerable <PlannedUnit> bounds = BoundsOptimizer.boundUnitsInPlan(plan, first, targetGraduation);
                StudyPlan newPlan = scheduleRemaning(bounds, new UnitInPlan[] { });

                if (newPlan == null)
                {
                    break;
                }

                //append the newPlan and try to get better plan with tighter target graduation semester
                bestPlans        = bestPlans.Concat(new[] { newPlan });
                targetGraduation = StudyPlannerModel.previousSemester(FSharpSchedulingWizard.lastSemester(newPlan));
            }

            return(bestPlans);
        }
Example #10
0
        public static IEnumerable <StudyPlan> TryToImproveSchedule(StudyPlan plan)
        {
            Semester initialSemester = currentSemester;
            Semester lastSemester    = FSharpSchedulingWizard.lastSemester(plan);

            // TODO: Fixme
            yield break;
        }
Example #11
0
        public ActionResult CrearPlan()
        {
            ViewBag.Modalidades = ObtenerTodosModalidades();
            ViewBag.Sedes       = ObtenerTodosSedes();
            var model = new StudyPlan();

            return(View());
        }
Example #12
0
        public ActionResult DeleteConfirmed(int id)
        {
            StudyPlan studyPlan = db.StudyPlans.Find(id);

            db.StudyPlans.Remove(studyPlan);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        public static IEnumerable <StudyPlan> TryToImproveSchedule(StudyPlan plan)
        {
            Semester firstSem = currentSemester;
            var      lastSem  = plan.GetEnumerator();



            yield break;
        }
Example #14
0
        public StudyPlan Add(string name, int year)
        {
            var newStudyPlan = new StudyPlan()
            {
                Id = new Guid(), Name = name, Year = year
            };

            return(_studyPlanRepository.Add(newStudyPlan));
        }
Example #15
0
 public ActionResult Edit([Bind(Include = "SPID,ContentDesc,Status,Program")] StudyPlan studyPlan)
 {
     if (ModelState.IsValid)
     {
         db.Entry(studyPlan).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.Program = new SelectList(db.Programs, "PID", "Name", studyPlan.Program);
     return(View(studyPlan));
 }
Example #16
0
        public async Task <IActionResult> Create([Bind("ID,Name,Content,UniversityID")] StudyPlan studyPlan)
        {
            if (ModelState.IsValid)
            {
                _context.Add(studyPlan);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["UniversityID"] = new SelectList(_context.Universities, "ID", "ID", studyPlan.UniversityID);
            return(View(studyPlan));
        }
Example #17
0
        public async Task <bool> AddPlan(Guid courseId, StudyPlan plan)
        {
            plan.Id = Guid.NewGuid();

            FilterDefinition <StudyCourse> filter = Builders <StudyCourse> .Filter.Where(x => x.Id == courseId);

            UpdateDefinition <StudyCourse> add = Builders <StudyCourse> .Update.AddToSet(c => c.Plans, plan);

            UpdateResult result = await DbSet.UpdateOneAsync(filter, add);

            return(result.IsAcknowledged && result.MatchedCount > 0);
        }
Example #18
0
        public StudyPlan Update(StudyPlan studyPlan)
        {
            var existentStudyPlan = _studyPlanRepository.Get(studyPlan.Id);

            if (existentStudyPlan == null)
            {
                throw new Exception("There is no Study Plan with that ID");
            }

            var updatedValue = _studyPlanRepository.Update(studyPlan);

            return(updatedValue);
        }
Example #19
0
        // GET: StudyPlans/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            StudyPlan studyPlan = db.StudyPlans.Find(id);

            if (studyPlan == null)
            {
                return(HttpNotFound());
            }
            return(View(studyPlan));
        }
        public void insertStudyPlan(List <StudyPlan> studyPlan)
        {
            int count = studyPlan.Count;

            StudyPlan[] newStudyPlan = new StudyPlan[count];
            for (int i = 0; i < count; i++)
            {
                newStudyPlan[i] = studyPlan[i];
            }

            // var vsa = new VirtualAdviserContext();
            VirtualAdvisor.AddRange(newStudyPlan);
            VirtualAdvisor.SaveChanges();
        }
Example #21
0
        // GET: StudyPlans/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            StudyPlan studyPlan = db.StudyPlans.Find(id);

            if (studyPlan == null)
            {
                return(HttpNotFound());
            }
            ViewBag.Program = new SelectList(db.Programs, "PID", "Name", studyPlan.Program);
            return(View(studyPlan));
        }
        public async Task <CommandResult> Handle(SavePlansCommand request, CancellationToken cancellationToken)
        {
            if (!request.IsValid())
            {
                return(request.Result);
            }

            List <StudyPlan> existingPlans = await studyCourseRepository.GetPlans(request.Id);

            foreach (StudyPlan plan in request.Plans)
            {
                StudyPlan existing = existingPlans.FirstOrDefault(x => x.Id == plan.Id);
                if (existing == null)
                {
                    await studyCourseRepository.AddPlan(request.Id, plan);
                }
                else
                {
                    existing.Name        = plan.Name;
                    existing.Description = plan.Description;
                    existing.ScoreToPass = plan.ScoreToPass;
                    existing.Order       = plan.Order;

                    await studyCourseRepository.UpdatePlan(request.Id, existing);
                }
            }

            IEnumerable <StudyPlan> plansToDelete = existingPlans.Where(x => !request.Plans.Contains(x));

            // TODO check students with those plans and update them;

            if (plansToDelete.Any())
            {
                foreach (StudyPlan plan in plansToDelete)
                {
                    await studyCourseRepository.RemovePlan(request.Id, plan.Id);
                }
            }

            var commitResult = await Commit(unitOfWork);

            request.Result.Validation = commitResult;

            return(request.Result);
        }
        public static Semester latestSem(StudyPlan plan)
        {
            if (plan is null)
            {
                return(null);
            }

            Semester currentMax = currentSemester;

            foreach (UnitInPlan unitInPlan in plan)
            {
                if (unitInPlan.semester.CompareTo(currentMax) > 0)
                {
                    currentMax = unitInPlan.semester;
                }
            }

            return(currentMax);
        }
        static void Main(string[] args)
        {
            /*
             * Observer Pattern
             */
            var publisher = new NytimesNews();

            publisher.PublishNews("Wei is starting to dive into design pattern stuff.");
            publisher.SendStatements("This month is $5 for 30 issues.");

            /*
             * Template Method Pattern(AbstractStudyStrategy class)
             * Composite Pattern (StudyPlan class)
             */
            var studyPlan = new StudyPlan();

            studyPlan.AddSubject(new StudyEnglish());
            studyPlan.AddSubject(new StudyProgramming());
            studyPlan.ShowSubjectStrategies();

            /*
             * Merge sort in recursive call
             */
            Int32[] arr = new Int32[10] {
                9, 22, 0, 1223, 48, 5, 47, 90, 42, 10
            };
            var sort = new Sort <Int32>(arr, new MergeSort <Int32>());

            foreach (var i in sort.Ascending())
            {
                Console.Write("{0} ", i);
            }
            Console.WriteLine();

            foreach (var i in sort.Descending())
            {
                Console.Write("{0} ", i);
            }
            Console.WriteLine();

            Console.WriteLine("Hello Nanchang!");
            Console.ReadKey();
        }
Example #25
0
        public async Task <bool> UpdatePlan(Guid courseId, StudyPlan plan)
        {
            plan.LastUpdateDate = DateTime.Now;

            FilterDefinition <StudyCourse> filter = Builders <StudyCourse> .Filter.And(
                Builders <StudyCourse> .Filter.Eq(x => x.Id, courseId),
                Builders <StudyCourse> .Filter.ElemMatch(x => x.Plans, x => x.Id == plan.Id));

            UpdateDefinition <StudyCourse> update = Builders <StudyCourse> .Update
                                                    .Set(c => c.Plans[-1].Name, plan.Name)
                                                    .Set(c => c.Plans[-1].Description, plan.Description)
                                                    .Set(c => c.Plans[-1].ScoreToPass, plan.ScoreToPass)
                                                    .Set(c => c.Plans[-1].Order, plan.Order)
                                                    .Set(c => c.Plans[-1].Activities, plan.Activities);

            UpdateResult result = await DbSet.UpdateOneAsync(filter, update);

            return(result.IsAcknowledged && result.ModifiedCount > 0);
        }
        public static IEnumerable <StudyPlan> TryToImproveSchedule(StudyPlan plan)
        {
            List <StudyPlan> improvedPlans = new List <StudyPlan>();

            // earliest possible sem + first and last sem of study plan
            Semester earliestPossible = bestPossible(plan, currentSemester);
            Semester firstSem         = currentSemester; ///
            Semester lastSem          = latestSem(plan);

            // get target completion date
            Semester target = StudyPlannerModel.previousSemester(lastSem); //

            /// create new bounds with target completion to be rescheduled into a new study plan
            List <PlannedUnit> newBound = BoundsOptimizer.boundUnitsInPlan(plan, firstSem, target).ToList();
            StudyPlan          newPlan;

            while (target.CompareTo(earliestPossible) >= 0) // while target is still possible
            {
                // if bounds infeasible then can't reschedule
                if (!FSharpSchedulingWizard.allBoundsFeasible(ListModule.OfSeq(newBound)))
                {
                    return(improvedPlans); /// return sequence
                }
                // otherwise, add plan to improved plans
                newPlan = scheduleRemaining(newBound, new List <UnitInPlan>());
                if (newPlan is null)
                {
                    break; // stop trying to find better plans
                }

                improvedPlans.Add(newPlan);

                // update target semester
                target = StudyPlannerModel.previousSemester(latestSem(newPlan));

                // update new bounds for 1 sem earlier
                newBound = BoundsOptimizer.boundUnitsInPlan(newPlan, firstSem, target).ToList();
            }


            return(improvedPlans);
        }
        public async Task <IActionResult> Delete(int id)
        {
            StudyPlan studyPlan = await _studyPlanService.GetById(id);

            if (studyPlan == null)
            {
                return(NotFound());
            }

            try
            {
                await _studyPlanService.Delete(studyPlan);

                return(Ok("Plan Başarıyla Silindi"));
            }
            catch
            {
                return(BadRequest("Plan Silme İşlemi Başarısız"));
            }
        }
Example #28
0
        public Enrollment DoEnrollmentAndRegistration(Student student, StudyPlan studyPlan)
        {
            var existentEnrollment = _enrollmentRepository.GetByStudent(student.Id);

            if (existentEnrollment != null)
            {
                throw new Exception("The Student is already Enrolled in another StudyPlan");
            }

            var existentEnrollments = _enrollmentRepository.GetByStudyPlan(studyPlan.Id);

            if (existentEnrollments.Any(x => x.Student.Id == student.Id))
            {
                throw new Exception("The Student is already Enrolled in this StudyPlan");
            }

            var newEnrollment = new Enrollment()
            {
                Id = new Guid(), Student = student, StudyPlan = studyPlan
            };

            return(_enrollmentRepository.Add(newEnrollment));
        }
Example #29
0
        public async Task <bool> SavePlans(Guid courseId, List <StudyPlan> plans)
        {
            List <StudyPlan> existingPlans = studyCourseRepository.GetPlans(courseId).ToList();

            foreach (StudyPlan plan in plans)
            {
                StudyPlan existing = existingPlans.FirstOrDefault(x => x.Id == plan.Id);
                if (existing == null)
                {
                    await studyCourseRepository.AddPlan(courseId, plan);
                }
                else
                {
                    existing.Name        = plan.Name;
                    existing.Description = plan.Description;
                    existing.ScoreToPass = plan.ScoreToPass;
                    existing.Order       = plan.Order;

                    await studyCourseRepository.UpdatePlan(courseId, existing);
                }
            }

            IEnumerable <StudyPlan> plansToDelete = existingPlans.Where(x => !plans.Contains(x));

            // TODO check students with those plans and update them;

            if (plansToDelete.Any())
            {
                foreach (StudyPlan plan in plansToDelete)
                {
                    await studyCourseRepository.RemovePlan(courseId, plan.Id);
                }
            }

            return(true);
        }
        public static StudyPlan scheduleRemaining(List <PlannedUnit> boundUnits, List <UnitInPlan> plan)
        {
            if (boundUnits.Count == 0) // all units have been scheduled, so return plan
            {
                return(plan);
            }

            PlannedUnit firstUnit = boundUnits.FirstOrDefault(unit => unit.possibleSemesters
                                                              .Any(sem => StudyPlannerModel.isEnrollableIn(unit.code, sem, plan)));

            if (firstUnit is null) // we have failed in finding an enrollable unit, so cannot complete schedule
            {
                return(null);
            }

            // otherwise schedule in possible semester
            foreach (Semester sem in firstUnit.possibleSemesters)
            {
                if (StudyPlannerModel.isEnrollableIn(firstUnit.code, sem, plan))
                {
                    UnitInPlan newUnit = new UnitInPlan(firstUnit.code, firstUnit.studyArea, sem);
                    IEnumerable <UnitInPlan>  newPlan  = plan.Append(newUnit);                                      // add new unit to plan
                    IEnumerable <PlannedUnit> newBound = boundUnits.Where(subject => subject.code != newUnit.code); // remove new unit from planned units
                    StudyPlan final = scheduleRemaining(newBound.ToList(), newPlan.ToList());                       // try to schedule the rest of the planned units

                    // if we finish with a plan that is not null, then we hav succeeded and return plan
                    if (!(final is null))
                    {
                        return(final);
                    }
                }
            }

            // otherwise no possible choices
            return(null);
        }