示例#1
0
        public BabyExercise()
        {
            InitializeComponent();

            exercise = Session.CurrentExercise;
            list = exercise.getTextsAsArrayChar();
            this.BackColor = Color.Pink;
            this.Refresh();

            stats = new Stats();

            pictureBox1.Load("1.jpg");

            index = 0;
            difficultyProgressBar.Minimum = 0;
            difficultyProgressBar.Maximum = list.Count;
            isRuning = true;

            watch = new Stopwatch();
            watch.Start();
            panel1.Visible = true;
            exerciseType = 1;

            listOfBox.Add(Letter1);
            listOfBox.Add(Letter2);
            listOfBox.Add(Letter3);
            listOfBox.Add(Letter4);
            listOfBox.Add(Letter5);

            initBoxList();

        }
示例#2
0
    public static bool tryGetPreparedExercise(Exercise e, out List<AnimationInfo> animationInfo, float animationLength)
    {
       float TIME_ERROR = 0.1f;
       animationInfo = null;
       //TODO: Evaluar borrar esta correccion cuando se tenga claridad de todos los ejercicios
       e.Limb = Limb.Left;


       string serializedPreparedExercises = PlayerPrefs.GetString("ExerciseCache");
       if (serializedPreparedExercises == null || serializedPreparedExercises == String.Empty)
       {
           _preparedExercises = new Dictionary<Exercise, List<AnimationInfo>>();
       }
       else
       {
           _preparedExercises = (Dictionary<Exercise, List<AnimationInfo>>)JsonConvert.DeserializeObject<Dictionary<Exercise, List<AnimationInfo>>>(serializedPreparedExercises);
       }


       if (_preparedExercises.TryGetValue(e, out animationInfo))
       {

           //No sé por qué, pero debe estar comentado para que funcione.
           //if (Math.Abs(animationInfo[animationInfo.Count / 2].time - animationLength) <= TIME_ERROR)
               return true;
               DebugLifeware.Log("Encontrado el exercis saved pero no cumle con el TIME_ERROR", DebugLifeware.Developer.Marco_Rojas);
       }
       else

           DebugLifeware.Log("No encontrado el ejercicio saved.", DebugLifeware.Developer.Marco_Rojas);
       return false;
    }
    public bool createNewExercise(string exerciseName, string muscleGroups, string equipment, string videoLink, bool rep, bool weight, bool distance, bool time, bool enabled)
    {
        bool rc = false;

        using (var context = new Layer2Container())
        {
            Exercise newExercise = new Exercise();
            try
            {
                if ((context.Exercises.FirstOrDefault(exercise => exercise.name == exerciseName).name == exerciseName))
                    rc = false;
            }
            catch (NullReferenceException e)
            {
                newExercise.name = exerciseName;
                newExercise.muscleGroups = muscleGroups;
                newExercise.equipment = equipment;
                newExercise.videoLink = videoLink;
                newExercise.rep = rep;
                newExercise.weight = weight;
                newExercise.distance = distance;
                newExercise.time = time;
                newExercise.enabled = enabled;

                context.Exercises.AddObject(newExercise);
                context.SaveChanges();
                rc = true;
            }
            return rc;
        }
    }
示例#4
0
        public ExerciseUI(Exercise exercise, ExerciseResult res)
        {
            this.ID = exercise.ID;
            this.SortOrder = exercise.SortOrder;
            this.Title = exercise.Title;
            this.Description = exercise.Description;
            this.HasInteractive = exercise.Content.HasInteractive;
            this.Html = exercise.Content.Html;

            if (res != null)
            {
                this.Html = res.Html ?? this.Html;
                this.Complete = res.End != null;
                this.Points = res.Points;
                this.HasInteractive = this.HasInteractive && !this.Complete;
            }

            if (this.Complete)
            {
                this.Passed = true;

                if (exercise.Content.HasInteractive)
                {
                    this.Passed = this.Points > 0;
                }
            }
        }
示例#5
0
 public void putExercise()
 {
     Exercise exercise = new Exercise { date = DateTime.Now, mode = 5, duration = "5 mins", distance = "10km", comments = "putExercise Test" };
     Exercise newExercise = jsonRestClient.Post<Exercise>("/exercise", exercise);
     Assert.AreEqual(newExercise.id, 4);
     exercise.id = 4;
     Assert.IsTrue(exercise.Equals(newExercise) == true, "putExercise returned different Exercise than sent!");
 }
示例#6
0
        public void initBabyMode()
        {
            exercise = Session.CurrentExercise;
            list = exercise.getTextsAsArrayChar();
            this.BackColor = Color.Pink;
            this.Refresh();

        }
示例#7
0
 public VanillaOption(Exercise extype, double strike, double spot, double dividend, double riskfreerate,
     double ttm, double vol, Date date, ValuationMethod method, Type type)
     : base(extype, strike, spot, dividend, riskfreerate, ttm, vol, date)
 {
     _type = type;
     _method = method;
     _dividend = dividend;
     _npv = 0.0;
 }
        public void TheCorrectEntityIsUpdated()
        {
            var existing = new Exercise(new ExerciseDocument {Id = 12, Description = "bar", ExerciseType = ExerciseType.Cardio});
            var repo = new Mock<IExerciseRepository>();
            var command = new UpdateExerciseCommand(12, "new description", ExerciseType.Strength);
            var handler = new UpdateExerciseCommandHandler(repo.Object);

            repo.Setup(x => x.Load(12)).Returns(existing).Verifiable();
            handler.Handle(command);

            repo.VerifyAll();
        }
示例#9
0
 public static void InsertPreparedExercise(Exercise e, List<AnimationInfo> animationInfo)
 {
     //TODO: Evaluar borrar esta correccion cuando se tenga claridad de todos los ejercicios
     e.Limb = Limb.Left;
     if (!_preparedExercises.ContainsKey(e))
     {
         _preparedExercises.Add(e, animationInfo);
         DebugLifeware.Log("Saving exercise", DebugLifeware.Developer.Marco_Rojas);
         PlayerPrefs.SetString("ExerciseCache", JsonConvert.SerializeObject(_preparedExercises));
     }
     else
         throw new Exception("Exercise already exists");
 }
示例#10
0
		public async static Task<bool> DeleteExercise(Exercise exercise)
		{
			int rowCount = 0;

			var db = DependencyService.Get<ISQLite>().GetAsyncConnection();
			await db.CreateTableAsync<Exercise>();
			rowCount = await db.DeleteAsync<Exercise>(exercise.ExerciseID);
			if (rowCount > 0)
			{
				return true;
			}
			return false;
		}
示例#11
0
		public async void loadExercise() {
			Exercise exercise = new Exercise ();
			DateTime date = DateTime.Now;

			try {
				string sDate = ""+date.Date.ToString("yyyy")+"-"+date.Date.ToString("MM")+"-"+date.Date.ToString("dd");
				System.Diagnostics.Debug.WriteLine("sDate: "+sDate);
				HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (new Uri ("http://ihbiproject.azurewebsites.net/api/Exercises/1/"+sDate));
				request.ContentType = "application/json";
				request.Method = "GET";
			

				using (HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync())
				{
					if (response.StatusCode != HttpStatusCode.OK) {
						System.Diagnostics.Debug.WriteLine ("Error fetching data. Server returned status code: {0}", response.StatusDescription);
					} else {
						using (Stream stream = response.GetResponseStream ()) {

							using (StreamReader reader = new StreamReader (stream)) {
								//String result = reader.ReadToEnd ();
								JsonSerializer serializer = new JsonSerializer ();
								Exercise result = (Exercise)serializer.Deserialize (reader, typeof(Exercise));
//								System.Diagnostics.Debug.WriteLine ("===> Users: " + result.ToString ());
								exercise = result;
							}

						}
					}
				}

				ExerciseType = exercise.type;
				ExerciseMin = exercise.minutes;
				if (exercise.pelvic == 1){
					Pelvic = true;
				} else {
					Pelvic = false;
				}
				if (exercise.stretching == 1) {
					Stretching = true;
				}else {
					Stretching = false;
				}
				System.Diagnostics.Debug.WriteLine ("after setting");
			} catch (System.Net.WebException we) {
				System.Diagnostics.Debug.WriteLine ("Exception in Load Exercise: " + we);
			}

		}
示例#12
0
		public async static Task<Exercise> GetExercisesByExerciseID(int gymID, int exerciseID)
		{
			Exercise exercise = new Exercise();
			List<Exercise> exercises = new List<Exercise>();
			int exerciseCount = 0;
			var db = DependencyService.Get<ISQLite>().GetAsyncConnection();
			await db.CreateTableAsync<Exercise>();
			exercises = await db.Table<Exercise>().Where(row => row.ExerciseID == exerciseID && row.GymID == gymID).ToListAsync();
			exerciseCount = exercises.Count;
			if (exerciseCount > 0)
			{
				exercise = exercises.First();
			}
			return exercise;
		}
        public void TheChangesAreApplied()
        {
            var document = new ExerciseDocument {Id = 99, Description = "bar", ExerciseType = ExerciseType.Cardio};
            var existing = new Exercise(document);

            var repo = new Mock<IExerciseRepository>();
            repo.Setup(x => x.Load(99)).Returns(existing);

            var command = new UpdateExerciseCommand(99, "new description", ExerciseType.Strength);
            var handler = new UpdateExerciseCommandHandler(repo.Object);

            handler.Handle(command);

            document.Description.ShouldEqual("new description");
            document.ExerciseType.ShouldEqual(ExerciseType.Strength);
        }
示例#14
0
文件: ExerciseForm.cs 项目: mcLyu/LIO
        public ExerciseForm()
        {
            InitializeComponent();
            exercise = Session.CurrentExercise;
            list = exercise.getTextsAsArrayChar();

            stats = new Stats();

            pictureBox1.Load("1.jpg");

            index = 0;
            difficultyProgressBar.Minimum = 0;
            difficultyProgressBar.Maximum = list.Count;
            isRuning = true;

            watch = new Stopwatch();
            watch.Start();
        }
示例#15
0
        public void initStandartMode()
        {
            exercise = Session.CurrentExercise;
            list = exercise.getTextsAsArrayChar();
            this.BackColor = Color.AliceBlue;

            this.Refresh();

            stats = new Stats();

            pictureBox1.Load("1.jpg");

            index = 0;
            difficultyProgressBar.Minimum = 0;
            difficultyProgressBar.Maximum = list.Count;
            isRuning = true;

            watch = new Stopwatch();
            watch.Start();
            listBox1.Visible = true;
            exerciseType = 0;
示例#16
0
 public ExerciseModel CreateViewModel(Exercise datamodel)
 {
     if (datamodel == null) { throw new ArgumentNullException("datamodel"); }
     var result = new ExerciseModel()
     {
         Id = datamodel.Id,
         Description = datamodel.Description,
         Name = datamodel.Name,
         Url = _UrlHelper.Link("GetExerciseById", new { id = datamodel.Id })
     };
     if (datamodel.Schedules != null && datamodel.Schedules.Any())
     {
         result.Schedules = datamodel.Schedules.Select(x => new EntryModel<int>()
         {
             Id = x.Id,
             Name = x.Name,
             Url = _UrlHelper.Link("GetScheduleById", new { id = x.Id })
         });
     }
     return result;
 }
    protected void btnRemove_Click(object sender, EventArgs e)
    {
        if (lbSelected.SelectedIndex > -1)
        {
            Exercise exerciseItem = new Exercise();
            exercises = Session["exercises"] != null ? (List<Exercise>)Session["exercises"] : null;
            if (exercises != null)
            {
                exerciseItem = sysManager.getExercise(lbSelected.SelectedItem.Text);
                if (exercises.Contains(exerciseItem))
                    exercises.Remove(exerciseItem);
            }
            while (lbSelected.SelectedItem != null)
            {
                lbSelected.Items.Remove(lbSelected.SelectedItem);
            }
            btnConfirm.Enabled = lbSelected.Items.Count != 1 ? true : false;

            Session["exercises"] = exercises;
        }
    }
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            string addname = name.Text;
            string addweight = weight.Text;
            string addreps = reps.Text;
            string addsets = sets.Text;
            string url = "http://jannehuo.fi/service/exercisecreate.php";

            Exercise ex = new Exercise
            {
                name = addname,
                weight = addweight,
                reps = addreps,
                sets = addsets
            };

            string json = JsonConvert.SerializeObject(ex);
            MessageBox.Show(json);
            WebClient wc = new WebClient();
            wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
            wc.UploadStringAsync(new Uri(url), "POST", json);
        }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        var selectedItems = from item in lbExerciseList.Items.OfType<ListItem>()
                            where item.Selected
                            select item;
        Exercise exerciseItem = new Exercise();
        foreach (ListItem li in selectedItems)
        {
            if (!lbSelected.Items.Contains(li))
            {
                lbSelected.Items.Add(li);
                btnConfirm.Enabled = lbSelected.Items.Count != 0 ? true : false;
                exerciseItem = sysManager.getExercise(li.Text);
                if (exerciseItem != null)
                    AddExercise(exerciseItem);
            }
        }

        for (int i = 0; i < lbSelected.Items.Count; i++)
        {
            lbSelected.Items[i].Selected = false;
        }
    }
示例#20
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.WorkoutLayout);
            var ex1  = FindViewById <TextView>(Resource.Id.Exercise1);
            var w1   = FindViewById <TextView>(Resource.Id.weight1);
            var w2   = FindViewById <TextView>(Resource.Id.weight2);
            var w3   = FindViewById <TextView>(Resource.Id.weight3);
            var w4   = FindViewById <TextView>(Resource.Id.weight4);
            var w5   = FindViewById <TextView>(Resource.Id.weight5);
            var done = FindViewById <TextView>(Resource.Id.done);

            var reps1 = FindViewById <TextView>(Resource.Id.reps1);
            var reps2 = FindViewById <TextView>(Resource.Id.reps2);
            var reps3 = FindViewById <TextView>(Resource.Id.reps3);
            var reps4 = FindViewById <EditText>(Resource.Id.reps4);
            var reps5 = FindViewById <EditText>(Resource.Id.reps5);

            var set1 = FindViewById <TextView>(Resource.Id.set1);
            var set2 = FindViewById <TextView>(Resource.Id.set2);
            var set3 = FindViewById <TextView>(Resource.Id.set3);
            var set4 = FindViewById <TextView>(Resource.Id.set4);
            var set5 = FindViewById <TextView>(Resource.Id.set5);

            //Create Database
            db = new Database();
            db.createDatabasePull2();

            //Load Data
            LoadData();

            var exercise1 = listSource[1].Name;
            var sets      = listSource[1].Sets;
            var reps      = listSource[1].Reps;
            var weight    = listSource[1].Weight;

            ex1.Text = exercise1 + ", " + sets + " sets of " + reps;
            w1.Text  = weight;
            w2.Text  = weight;
            w3.Text  = weight;
            w4.Text  = weight;
            w5.Text  = weight;

            reps1.Text = reps;
            reps2.Text = reps;
            reps3.Text = reps;

            set1.Text = "Set 1";
            set2.Text = "Set 2";
            set3.Text = "Set 3";
            set4.Text = "Set 4: " + reps + "+";
            set5.Text = "Set 5: " + reps + "?";

            var reps4String = "";
            var reps5String = "";
            var test        = "";


            done.Click += async delegate
            {
                reps4String = reps4.Text;
                reps5String = reps5.Text;
                double reps4Int  = int.Parse(reps4String);
                double reps5Int  = int.Parse(reps5String);
                double repsInt   = int.Parse(reps);
                double x         = reps4Int - repsInt;
                double weightInt = double.Parse(weight);

                if (x >= 2)
                {
                    weightInt = (weightInt + 2.5);
                    weight    = weightInt.ToString();
                    Exercise exercise = new Exercise()
                    {
                        Id     = listSource[1].Id,
                        Name   = exercise1,
                        Sets   = sets,
                        Reps   = reps,
                        Weight = weight
                    };
                    db.updateTablePull2(exercise);
                    LoadData();
                }
                ;

                if (x <= -2)
                {
                    weightInt = weightInt - 2.5;
                    weight    = weightInt.ToString();
                    Exercise exercise = new Exercise()
                    {
                        Id     = listSource[1].Id,
                        Name   = exercise1,
                        Sets   = sets,
                        Reps   = reps,
                        Weight = weight
                    };
                    db.updateTablePull2(exercise);
                    LoadData();
                }
                ;

                try
                {
                    test = listSource[2].Name;
                    var intent = new Intent(this, typeof(Pull2Workout3));
                    this.StartActivity(intent);
                }
                catch
                {
                    var intent = new Intent(this, typeof(ProgramHome));
                    this.StartActivity(intent);
                };
            };
        }
示例#21
0
        public void Get_NotNull()
        {
            Exercise exercise = service.Get(1);

            Assert.That(exercise, Is.Not.Null);
        }
示例#22
0
    private IEnumerator RunWebInSeconds(float time, BehaviourParams p)
    {
        yield return new WaitForSeconds(time);
        behaviour.RunWeb(p);

        if (p.Variations == null)
            RewindExercise();
        else
            CurrentExercise = new Exercise(behaviour.randomAnimations[0], CurrentExercise.Limb);
    }
示例#23
0
 public PrepareExerciseWebParams(Exercise e, Caller c)
 {
     this.Exercise = e;
     this.Caller = c;
 }
示例#24
0
        public void DeleteExercise(long id)
        {
            Exercise exercise = Lb.Exercises.Find(id);

            Lb.Exercises.Remove(exercise);
        }
示例#25
0
        private void testFdGreeks <Engine>(Date today, Exercise exercise) where Engine : IFDEngine, new()
        {
            Dictionary <string, double> calculated = new Dictionary <string, double>(),
                                        expected   = new Dictionary <string, double>(),
                                        tolerance  = new Dictionary <string, double>();

            tolerance.Add("delta", 5.0e-3);
            tolerance.Add("gamma", 7.0e-3);
            // tolerance["theta"] = 1.0e-2;

            Option.Type[] types       = { Option.Type.Call, Option.Type.Put };
            double[]      strikes     = { 50.0, 99.5, 100.0, 100.5, 150.0 };
            double[]      underlyings = { 100.0 };
            double[]      qRates      = { 0.00, 0.10, 0.20 };
            double[]      rRates      = { 0.01, 0.05, 0.15 };
            double[]      vols        = { 0.05, 0.20, 0.50 };

            DayCounter dc = new Actual360();

            SimpleQuote spot  = new SimpleQuote(0.0);
            SimpleQuote qRate = new SimpleQuote(0.0);
            Handle <YieldTermStructure> qTS = new Handle <YieldTermStructure>(Utilities.flatRate(qRate, dc));
            SimpleQuote rRate = new SimpleQuote(0.0);
            Handle <YieldTermStructure> rTS = new Handle <YieldTermStructure>(Utilities.flatRate(rRate, dc));
            SimpleQuote vol = new SimpleQuote(0.0);
            Handle <BlackVolTermStructure> volTS = new Handle <BlackVolTermStructure>(Utilities.flatVol(vol, dc));

            for (int i = 0; i < types.Length; i++)
            {
                for (int j = 0; j < strikes.Length; j++)
                {
                    List <Date>   dividendDates = new List <Date>();
                    List <double> dividends     = new List <double>();
                    for (Date d = today + new Period(3, TimeUnit.Months);
                         d < exercise.lastDate();
                         d += new Period(6, TimeUnit.Months))
                    {
                        dividendDates.Add(d);
                        dividends.Add(5.0);
                    }

                    StrikedTypePayoff payoff = new PlainVanillaPayoff(types[i], strikes[j]);

                    BlackScholesMertonProcess stochProcess = new BlackScholesMertonProcess(new Handle <Quote>(spot),
                                                                                           qTS, rTS, volTS);

                    IPricingEngine        engine = new Engine().factory(stochProcess);
                    DividendVanillaOption option = new DividendVanillaOption(payoff, exercise, dividendDates, dividends);
                    option.setPricingEngine(engine);

                    for (int l = 0; l < underlyings.Length; l++)
                    {
                        for (int m = 0; m < qRates.Length; m++)
                        {
                            for (int n = 0; n < rRates.Length; n++)
                            {
                                for (int p = 0; p < vols.Length; p++)
                                {
                                    double u = underlyings[l];
                                    double q = qRates[m],
                                           r = rRates[n];
                                    double v = vols[p];
                                    spot.setValue(u);
                                    qRate.setValue(q);
                                    rRate.setValue(r);
                                    vol.setValue(v);

                                    // FLOATING_POINT_EXCEPTION
                                    double value = option.NPV();
                                    calculated["delta"] = option.delta();
                                    calculated["gamma"] = option.gamma();
                                    // calculated["theta"]  = option.theta();

                                    if (value > spot.value() * 1.0e-5)
                                    {
                                        // perturb spot and get delta and gamma
                                        double du = u * 1.0e-4;
                                        spot.setValue(u + du);
                                        double value_p = option.NPV(),
                                               delta_p = option.delta();
                                        spot.setValue(u - du);
                                        double value_m = option.NPV(),
                                               delta_m = option.delta();
                                        spot.setValue(u);
                                        expected["delta"] = (value_p - value_m) / (2 * du);
                                        expected["gamma"] = (delta_p - delta_m) / (2 * du);

                                        // perturb date and get theta

                                        /*
                                         * Time dT = dc.yearFraction(today-1, today+1);
                                         * Settings::instance().evaluationDate() = today-1;
                                         * value_m = option.NPV();
                                         * Settings::instance().evaluationDate() = today+1;
                                         * value_p = option.NPV();
                                         * Settings::instance().evaluationDate() = today;
                                         * expected["theta"] = (value_p - value_m)/dT;
                                         */

                                        // compare
                                        foreach (string greek in calculated.Keys)
                                        {
                                            double expct      = expected[greek],
                                                        calcl = calculated[greek],
                                                        tol   = tolerance[greek];
                                            double error      = Utilities.relativeError(expct, calcl, u);
                                            if (error > tol)
                                            {
                                                REPORT_FAILURE(greek, payoff, exercise,
                                                               u, q, r, today, v,
                                                               expct, calcl, error, tol);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
示例#26
0
 public async Task <IActionResult> UpdateFull([FromBody] Exercise exercise, CancellationToken cancellationToken = default)
 {
     //RemoveCacheKeys($"Report/TrainingMetrics{exercise.TrainingId}");
     return(Ok(await Mediator.Send(new UpdateFullExerciseRequest(exercise), cancellationToken)));
 }
示例#27
0
 public void Remove(Exercise entity)
 {
     Context.Set <Exercise>().Remove(entity);
 }
示例#28
0
 public void Add(Exercise entity)
 {
     Context.Set <Exercise>().Add(entity);
 }
        //works out the score of a given exercise and outputs to a text block, and shows a motivational message to the user
        private void score(Exercise e)
        {
            // divide by 300 frames since that is the total for one 10 second exercise at 30fps
            double percentageX = e.getTotalPercentageX() / 300;
            double percentageY = e.getTotalPercentageY() / 300;

            //average of the X and Y percentages
            double averageTotalPercent = (percentageX + percentageY) / 2;

            //divide percentage by 10 and round up to the nearest whole number to get score. Then output to 'percent' text block
            percent.Text = Math.Round(averageTotalPercent / 10, 0).ToString() + "/ 10";

            //Excellent score
            if (averageTotalPercent > 80)
            {
                //reset percentages
                averageTotalPercent = 0;
                percentageX         = 0;
                percentageY         = 0;

                //output motivation to text block
                motivation.Text = "EXCELLENT!";
            }

            //Great score
            else if (averageTotalPercent > 50 & averageTotalPercent < 80)
            {
                averageTotalPercent = 0;
                percentageX         = 0;
                percentageY         = 0;

                motivation.Text = string.Format("GREAT!,{0}TRY AGAIN!", Environment.NewLine);
            }

            // < 50
            else if (averageTotalPercent < 50)
            {
                averageTotalPercent = 0;
                percentageX         = 0;
                percentageY         = 0;

                motivation.Text = string.Format("OK, BUT{0}TRY AGAIN!{0}YOU CAN DO IT!", Environment.NewLine);
            }

            //exercise better in the y axis
            else if (percentageY - percentageX > 30)
            {
                averageTotalPercent = 0;
                percentageX         = 0;
                percentageY         = 0;

                motivation.Text = string.Format("GOOD,{0}TRY STRETCHING{0}TO THE{0}SIDE MORE!", Environment.NewLine);
            }

            //exercise better in the x axis
            else if (percentageX - percentageY > 30)
            {
                averageTotalPercent = 0;
                percentageX         = 0;
                percentageY         = 0;

                motivation.Text = string.Format("GOOD,{0}TRY STRETCHING{0}HIGHER!", Environment.NewLine);
            }
        }
示例#30
0
        private static void Main(string[] args)
        {
            var exercise = new Exercise();

            exercise.Run();
        }
示例#31
0
 public void Update(Exercise exercise)
 {
     throw new NotImplementedException();
 }
示例#32
0
 public Training GetById(Exercise id)
 {
     throw new NotImplementedException();
 }
示例#33
0
 public void AddExercise(Exercise exercise)
 {
     adminRepo.AddExercise(exercise);
 }
示例#34
0
        public ActionResult CreateExercise(ExerciseViewModel exercise)
        {
            string UID = exercise.PersonalTrainerID;

            if (exercise.ExerciseTitle == null)
            {
                ModelState.AddModelError("", "Please enter a Title");
            }

            if (exercise.ExerciseDescription == null)
            {
                ModelState.AddModelError("", "Please enter a Description");
            }

            if (exercise.VideoTitle != null && exercise.VideoURL == null)
            {
                ModelState.AddModelError("", "Please enter a Video URL");
            }

            //If success - return JSON with success. JS will do the Get to reload the page
            if (ModelState.IsValid)
            {
                //create Exercise Instance
                Exercise newExercise = new Exercise()
                {
                    Title             = exercise.ExerciseTitle,
                    Description       = exercise.ExerciseDescription,
                    PersonalTrainerID = UID
                };

                db.Exercises.Add(newExercise);
                db.SaveChanges();

                //Need to make Video not required
                if (exercise.VideoTitle != null)
                {
                    //Create Video Instance
                    Video newVideo = new Video()
                    {
                        Title      = exercise.VideoTitle,
                        ExerciseID = newExercise.ID,
                        URL        = exercise.VideoURL
                    };
                    //Store in DB
                    db.Videos.Add(newVideo);
                    db.SaveChanges();
                }

                return(Json(new { createStatus = "success", UID }));
            }


            //If error - return Model State errors
            List <string> errors = new List <string>();

            foreach (var v in ModelState.Values)
            {
                foreach (var e in v.Errors)
                {
                    errors.Add(e.ErrorMessage);
                }
            }



            return(Json(new { createStatus = "fail", errors, UID }));
        }
示例#35
0
        public User getUser(string userName, string password)
        {
            User user = new User();

            SqlConnection conn = getConnection();

            conn.Open();
            try
            {
                string        select = "SELECT * FROM USERS";
                SqlCommand    cmd    = new SqlCommand(select, conn);
                SqlDataReader reader = cmd.ExecuteReader();
                status = false;

                while (reader.Read())
                {
                    if (reader.GetString(reader.GetOrdinal("UserName")).Equals(userName))
                    {
                        if (reader.GetString(reader.GetOrdinal("Password")).Equals(password))
                        {
                            user.UserId      = reader.GetInt32(reader.GetOrdinal("UserId"));
                            user.UserName    = reader.GetString(reader.GetOrdinal("UserName"));
                            user.FirstName   = reader.GetString(reader.GetOrdinal("FirstName"));
                            user.LastName    = reader.GetString(reader.GetOrdinal("LastName"));
                            user.Password    = reader.GetString(reader.GetOrdinal("Password"));
                            user.CurrentDay  = reader.GetInt32(reader.GetOrdinal("CurrentDay"));
                            user.CurrentWeek = reader.GetInt32(reader.GetOrdinal("CurrentWeek"));
                            status           = true;
                        }
                    }
                }
                reader.Close();

                if (status)
                {
                    select = "Select * from Weeks Where userId =" + user.UserId + "";
                    cmd    = new SqlCommand(select, conn);
                    reader = cmd.ExecuteReader();
                    List <Week> weekList = new List <Week>();
                    while (reader.Read())
                    {
                        Week wk = new Week();
                        wk.WeekId          = reader.GetInt32(reader.GetOrdinal("WeekId"));
                        wk.WeekNumber      = reader.GetInt32(reader.GetOrdinal("WeekNumber"));
                        wk.WeekOrderNumber = reader.GetInt32(reader.GetOrdinal("WeekOrderNumber"));
                        weekList.Add(wk);
                    }
                    reader.Close();

                    foreach (Week wk in weekList)
                    {
                        select = "Select * from Days Where (UserId =" + user.UserId + " And WeekId =" + wk.WeekId + ")";
                        cmd    = new SqlCommand(select, conn);
                        reader = cmd.ExecuteReader();
                        List <Day> dayList = new List <Day>();
                        while (reader.Read())
                        {
                            Day day = new Day();
                            day.DayId          = reader.GetInt32(reader.GetOrdinal("DayId"));
                            day.DayNumber      = reader.GetInt32(reader.GetOrdinal("DayNumber"));
                            day.DayOrderNumber = reader.GetInt32(reader.GetOrdinal("DayOrderNumber"));
                            dayList.Add(day);
                        }
                        wk.Days = dayList;
                        reader.Close();
                    }

                    foreach (Week wk in weekList)
                    {
                        foreach (Day day in wk.Days)
                        {
                            IList <int> dayExerciseNumber = new List <int>();
                            select = "Select * From DayExerciseList Where DayId =" + day.DayId;
                            cmd    = new SqlCommand(select, conn);
                            reader = cmd.ExecuteReader();
                            while (reader.Read())
                            {
                                dayExerciseNumber.Add(reader.GetInt32(reader.GetOrdinal("Number")));
                            }
                            day.ExerciseListNumber = dayExerciseNumber;
                            reader.Close();
                        }
                    }

                    user.Weeks = weekList;

                    Console.WriteLine("Looking for exercises with userId: " + user.UserId);
                    select = "Select * From Exercises Where UserId =" + user.UserId;
                    List <Exercise> exerciseList = new List <Exercise>();
                    cmd    = new SqlCommand(select, conn);
                    reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        Exercise ex = new Exercise();
                        ex.ExerciseId     = reader.GetInt32(reader.GetOrdinal("ExerciseId"));
                        ex.Name           = reader.GetString(reader.GetOrdinal("Name"));
                        ex.ExerciseNumber = reader.GetInt32(reader.GetOrdinal("ExerciseNumber"));
                        ex.Weight         = (double)reader.GetDecimal(reader.GetOrdinal("Weight"));
                        ex.Sets           = reader.GetInt32(reader.GetOrdinal("Sets"));
                        ex.Reps           = reader.GetInt32(reader.GetOrdinal("Reps"));
                        exerciseList.Add(ex);
                    }
                    reader.Close();
                    user.ExerciseList = exerciseList;
                }
                else
                {
                    message = "Wrong user name or password";
                }
            }catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                conn.Close();
            }


            return(user);
        }
示例#36
0
 public void init()
 {
     ex = new Exercise();
 }
        private async Task <List <Student> > List(int id)
        {
            using (SqlConnection conn = Connection)
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"SELECT s.Id, s.FirstName, s.LastName, s.SlackHandle, s.CohortId StudentCohortId,
                                               c.Id CohortId, c.Name CohortName,
                                               e.Id ExerciseId, e.Name ExerciseName, e.Language ExerciseLanguage
                                        FROM Student s
                                        LEFT JOIN Cohort c 
                                            ON s.CohortId = c.Id
                                        LEFT JOIN StudentExercise se 
                                            ON s.Id = se.StudentId
                                        LEFT JOIN Exercise e 
                                            ON se.ExerciseId = e.Id ";

                    if (id > 0)
                    {
                        cmd.CommandText += @" WHERE s.Id = @id";
                        cmd.Parameters.Add(new SqlParameter("@id", id));
                    }

                    SqlDataReader reader = await cmd.ExecuteReaderAsync();

                    List <Student> students = new List <Student>();

                    int StudentIdOrdinal        = reader.GetOrdinal("Id");
                    int FirstNameOrdinal        = reader.GetOrdinal("FirstName");
                    int LastNameOrdinal         = reader.GetOrdinal("LastName");
                    int SlackHandleOrdinal      = reader.GetOrdinal("SlackHandle");
                    int StudentCohortIdOrdinal  = reader.GetOrdinal("StudentCohortId");
                    int CohortIdOrdinal         = reader.GetOrdinal("CohortId");
                    int CohortNameOrdinal       = reader.GetOrdinal("CohortName");
                    int ExerciseIdOrdinal       = reader.GetOrdinal("ExerciseId");
                    int ExerciseNameOrdinal     = reader.GetOrdinal("ExerciseName");
                    int ExerciseLanguageOrdinal = reader.GetOrdinal("ExerciseLanguage");

                    while (reader.Read())
                    {
                        var studentId = reader.GetInt32(StudentIdOrdinal);

                        var studentAlreadyAdded = students.FirstOrDefault(s => s.Id == studentId);

                        var hasExercise = !reader.IsDBNull(ExerciseIdOrdinal);

                        if (studentAlreadyAdded == null)
                        {
                            Student student = new Student
                            {
                                Id = reader.GetInt32(StudentIdOrdinal),
                                //Id = studentId,
                                FirstName   = reader.GetString(FirstNameOrdinal),
                                LastName    = reader.GetString(LastNameOrdinal),
                                SlackHandle = reader.GetString(SlackHandleOrdinal),
                                CohortId    = reader.GetInt32(StudentCohortIdOrdinal),
                                Cohort      = new Cohort()
                                {
                                    Id   = reader.GetInt32(CohortIdOrdinal),
                                    Name = reader.GetString(CohortNameOrdinal)
                                }
                            };
                            students.Add(student);

                            if (hasExercise)
                            {
                                Exercise exercise = new Exercise
                                {
                                    Id       = reader.GetInt32(ExerciseIdOrdinal),
                                    Name     = reader.GetString(ExerciseNameOrdinal),
                                    Language = reader.GetString(ExerciseLanguageOrdinal)
                                };
                                student.StudentsExercises.Add(exercise);
                            }
                        }
                        else
                        {
                            if (hasExercise)
                            {
                                studentAlreadyAdded.StudentsExercises.Add(new Exercise()
                                {
                                    Id       = reader.GetInt32(ExerciseIdOrdinal),
                                    Name     = reader.GetString(ExerciseNameOrdinal),
                                    Language = reader.GetString(ExerciseLanguageOrdinal)
                                });
                            }
                        }
                    }
                    reader.Close();

                    return(students);
                }
            }
        }
 protected void lbExerciseList_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (lbExerciseList.SelectedIndex > -1)
     {
         Exercise exerciseItem = new Exercise();
         exerciseItem = sysManager.getExercise(lbExerciseList.SelectedItem.Text);
         if (exerciseItem != null )
         {
             pnlDescription.Visible = true;
             lblDescription.Text = !exerciseItem.description.Trim().Equals("") ? exerciseItem.description.Trim(): "No Description";
             lblEquipment.Text = !exerciseItem.equipment.Trim().ToLower().Equals("none") ? exerciseItem.equipment.Replace(" ", "<br />") : "No Equipment";
         }
         else
             pnlDescription.Visible = false;
     }
 }
    // return the routine created
    public Routine createNewRoutine(String routineName, int userID, ICollection<Exercise> exerciseList)
    {
        using (var context = new Layer2Container())
        {
            Routine rc = new Routine();
            try
            {
                LimitBreaker lb = context.LimitBreakers.Where(x => x.id == userID).FirstOrDefault();
                Exercise exc = new Exercise();
                if (lb != null)
                {
                    rc.name = routineName.Trim();
                    rc.LimitBreaker = lb;
                    rc.lastModified = DateTime.Now;
                    foreach (Exercise ex in exerciseList)
                    {
        #if DEBUG
                        response.Write("Exercise: " + ex.name + "<br/> ID: " + ex.id + "<br/>");
        #endif
                        // to prevent object out of context error
                        exc = context.Exercises.Where(x => x.id == ex.id).FirstOrDefault();
                        rc.Exercises.Add(exc);
                        exc = new Exercise();
                    }

                    context.Routines.AddObject(rc);
                    context.SaveChanges();
                }
            }
            catch (NullReferenceException e)
            {
                Console.WriteLine(e.Message + Environment.NewLine + e.StackTrace);
                // write off the execeptions to my error.log file
                StreamWriter wrtr = new StreamWriter(System.Web.HttpContext.Current.ApplicationInstance.Server.MapPath("~/assets/documents/" + @"\" + "error.log"), true);

                wrtr.WriteLine(DateTime.Now.ToString() + " | Error: " + e);

                wrtr.Close();
            }

            return rc;
        }
    }
示例#40
0
 public void InsertExercise(Exercise exercise)
 {
     Lb.Exercises.Add(exercise);
     Save();
 }
示例#41
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            try
            {
                base.OnCreate(savedInstanceState);
                // Set our view from the "main" layout resource
                SetContentView(Resource.Layout.Main);

                var day = this.Intent.Extras.GetString("Day");

                ActionBar.Hide();

                //Create Database
                db = new Database();
                db.createDatabase();

                lstViewData = FindViewById <ListView>(Resource.Id.listView);

                var edtName   = FindViewById <EditText>(Resource.Id.edtName);
                var edtSets   = FindViewById <EditText>(Resource.Id.edtSets);
                var edtReps   = FindViewById <EditText>(Resource.Id.edtReps);
                var edtEmail  = FindViewById <EditText>(Resource.Id.edtEmail);
                var btnAdd    = FindViewById <Button>(Resource.Id.btnAdd);
                var btnEdit   = FindViewById <Button>(Resource.Id.btnEdit);
                var btnRemove = FindViewById <Button>(Resource.Id.btnRemove);
                var title     = FindViewById <TextView>(Resource.Id.toolbar_title);

                //Load Data
                LoadData();

                title.Text = day;

                try
                {
                    Toast error = Toast.MakeText(this, listSource[0].Name, ToastLength.Short);
                    error.Show();
                }
                catch
                {
                    Toast error = Toast.MakeText(this, "none yet", ToastLength.Short);
                    error.Show();
                }

                //Event
                btnAdd.Click += delegate
                {
                    Exercise exercise = new Exercise()
                    {
                        Workout = day,
                        Name    = edtName.Text,
                        Sets    = "10",
                        Reps    = edtReps.Text,
                        Weight  = edtEmail.Text
                    };

                    db.insertIntoTable(exercise);

                    LoadData();

                    try
                    {
                        Toast error = Toast.MakeText(this, listSource[0].Workout, ToastLength.Short);
                        error.Show();
                    }
                    catch
                    {
                        Toast error = Toast.MakeText(this, "Workout Error", ToastLength.Short);
                        error.Show();
                    }

                    try
                    {
                        Toast error = Toast.MakeText(this, listSource[0].Name, ToastLength.Short);
                        error.Show();
                    }
                    catch
                    {
                        Toast error = Toast.MakeText(this, "Name Error", ToastLength.Short);
                        error.Show();
                    }

                    try
                    {
                        Toast error = Toast.MakeText(this, listSource[0].Reps, ToastLength.Short);
                        error.Show();
                    }
                    catch
                    {
                        Toast error = Toast.MakeText(this, "Reps Error", ToastLength.Short);
                        error.Show();
                    }

                    try
                    {
                        Toast error = Toast.MakeText(this, listSource[0].Weight, ToastLength.Short);
                        error.Show();
                    }
                    catch
                    {
                        Toast error = Toast.MakeText(this, "Weight Error", ToastLength.Short);
                        error.Show();
                    }

                    try
                    {
                        Toast error = Toast.MakeText(this, listSource[0].Sets, ToastLength.Short);
                        error.Show();
                    }
                    catch
                    {
                        Toast error = Toast.MakeText(this, "Sets Error", ToastLength.Short);
                        error.Show();
                    }
                };
                btnEdit.Click += delegate
                {
                    Exercise exercise = new Exercise()
                    {
                        Id      = int.Parse(edtName.Tag.ToString()),
                        Workout = day,
                        Name    = edtName.Text,
                        Sets    = edtSets.Text,
                        Reps    = edtReps.Text,
                        Weight  = edtEmail.Text
                    };

                    db.updateTable(exercise);

                    LoadData();
                };
                btnRemove.Click += delegate
                {
                    Exercise exercise = new Exercise()
                    {
                        Id      = int.Parse(edtName.Tag.ToString()),
                        Workout = day,
                        Name    = edtName.Text,
                        Sets    = edtSets.Text,
                        Reps    = edtReps.Text,
                        Weight  = edtEmail.Text
                    };

                    db.removeTable(exercise);

                    LoadData();
                };
                lstViewData.ItemClick += (s, e) =>
                {
                    /*
                     * //Set Backround for selected item
                     * for (int i = 0; i < lstViewData.Count; i++)
                     * {
                     *  if (e.Position == i)
                     *      lstViewData.GetChildAt(i).SetBackgroundColor(Android.Graphics.Color.Black);
                     *  else
                     *      lstViewData.GetChildAt(i).SetBackgroundColor(Android.Graphics.Color.Transparent);
                     * }*/
                    //Binding Data
                    var txtName  = e.View.FindViewById <TextView>(Resource.Id.txtView_Name);
                    var txtSets  = e.View.FindViewById <TextView>(Resource.Id.txtView_Sets);
                    var txtReps  = e.View.FindViewById <TextView>(Resource.Id.txtView_Reps);
                    var txtEmail = e.View.FindViewById <TextView>(Resource.Id.txtView_Email);
                    edtName.Text  = txtName.Text;
                    edtName.Tag   = e.Id;
                    edtSets.Text  = txtSets.Text;
                    edtReps.Text  = txtReps.Text;
                    edtEmail.Text = txtEmail.Text;
                };

                var done = FindViewById <Button>(Resource.Id.done);

                done.Click += async delegate
                {
                    var intent = new Intent(this, typeof(ProgramHome));

                    this.StartActivity(intent);
                };
            }
            catch (Exception e)
            {
                System.Exception myException = e;
                Toast            error       = Toast.MakeText(this, "Main Text Error: " + e.Message, ToastLength.Short);
                error.Show();
            }
        }
示例#42
0
		public ExerciseViewModel(Exercise exercise, bool isCreateWorkoutOnly = false, User isFeedbackOnlyUser = null)
        {
			if (isCreateWorkoutOnly) {
				DisplayWeight = true;
			} else {
				DisplayWeight = false;
			}

			this.ImageSource = exercise.ImageSource;

            this.Exercise = exercise;

			if(Exercise.CardioExID != 0){
				IsCardioExercise = true;
			}
        }
 public AfterExerciseEvent(ExecutionContext executionContext, Exercise exercise)
     : base(executionContext)
 {
     exercise.AssertNotNull(nameof(exercise));
     this.exercise = exercise;
 }
示例#44
0
 public ExerciseProgramBuilder AddExercise(Exercise exercise)
 {
     this.exercises.Add(exercise);
     return(this);
 }
示例#45
0
    /// <summary>
    /// Nota: Si hay errores de Quaternion to Matrix comprobar que los parametros enviados son validos para el ejercicio indicado
    /// </summary>
    /// <param name="e"></param>
    /// <param name="param"></param>
    public void PrepareExercise(Exercise e, BehaviourParams param)
    {

        param.Angle = AngleFixer.FixAngle(param.Angle, e.Movement);
        if (param.Variations == null || param.Variations.Count == 0)
            behaviour = AnimationBehaviour.GetBehaviour(e.Movement, e.Limb);
        else
            behaviour = AnimationBehaviour.GetCentralBehaviour(e.Movement, e.Limb);

        if (behaviour == null)
        {
            Debug.LogError("No se encontró la máquina de estado. (Ejercicio = " + e.Movement + " "
                + (int)e.Movement + ") (Limb = " + e.Limb + ")" +
                "). Posiblemente se deba a una mala combinación de esos parámetros o el MonitoAnimatorController se bugeó");
            return;
        }

        behaviour.Prepare(param);
        behaviour.RepetitionEnd += behaviour_PrepareEnd;

        if (param.Variations == null || param.Variations.Count == 0)
            CurrentExercise = e;
        else
            CurrentExercise = new Exercise(behaviour.randomAnimations[0], e.Limb);
    }
示例#46
0
        public async Task <IActionResult> Get(string include)
        {
            using (SqlConnection conn = Connection)
            {
                conn.Open();

                using (SqlCommand cmd = conn.CreateCommand())
                {
                    if (include == "Exercise")
                    {
                        cmd.CommandText = @"SELECT s.Id AS StudentId, s.FirstName, s.LastName, s.CohortId, c.CohortName, c.Id AS CohortId, e.Id AS ExerciseId, e.ExerciseName, e.ExerciseLanguage, se.StudentId AS SEStudentId, se.ExerciseId AS SEExerciseId FROM StudentExercise se JOIN Student s ON se.StudentId = s.Id
                                        JOIN Cohort c ON c.Id = s.CohortId
                                        JOIN Exercise e ON e.Id = se.ExerciseId;";

                        List <Student> students = new List <Student>();

                        List <Exercise> exercises = new List <Exercise>();

                        SqlDataReader reader = await cmd.ExecuteReaderAsync();

                        while (reader.Read())
                        {
                            Exercise exercise = new Exercise
                            {
                                Id               = reader.GetInt32(reader.GetOrdinal("ExerciseId")),
                                ExerciseName     = reader.GetString(reader.GetOrdinal("ExerciseName")),
                                ExerciseLanguage = reader.GetString(reader.GetOrdinal("ExerciseLanguage"))
                            };

                            exercises.Add(exercise);


                            Student student = new Student
                            {
                                Id        = reader.GetInt32(reader.GetOrdinal("StudentId")),
                                FirstName = reader.GetString(reader.GetOrdinal("FirstName")),
                                LastName  = reader.GetString(reader.GetOrdinal("LastName")),
                                CohortId  = reader.GetInt32(reader.GetOrdinal("CohortId")),
                                Cohort    = new Cohort
                                {
                                    Id         = reader.GetInt32(reader.GetOrdinal("CohortId")),
                                    CohortName = reader.GetString(reader.GetOrdinal("CohortName"))
                                },
                                ExerciseList = exercises.Where(e => reader.GetInt32(reader.GetOrdinal("SEExerciseId")) == e.Id).ToList()
                            };

                            students.Add(student);
                        }

                        reader.Close();

                        return(Ok(students));
                    }
                    else
                    {
                        cmd.CommandText = @"SELECT
                                            s.Id AS StudentId,
                                            s.FirstName,
                                            s.LastName,
                                            s.CohortId,
                                            c.CohortName,
                                            c.Id AS CohortId
                                         FROM Student s
                                         JOIN Cohort c ON c.Id = s.CohortId";

                        List <Student> students = new List <Student>();

                        SqlDataReader reader = await cmd.ExecuteReaderAsync();

                        while (reader.Read())
                        {
                            Student student = new Student
                            {
                                Id        = reader.GetInt32(reader.GetOrdinal("StudentId")),
                                FirstName = reader.GetString(reader.GetOrdinal("FirstName")),
                                LastName  = reader.GetString(reader.GetOrdinal("LastName")),
                                CohortId  = reader.GetInt32(reader.GetOrdinal("CohortId")),
                                Cohort    = new Cohort
                                {
                                    Id         = reader.GetInt32(reader.GetOrdinal("CohortId")),
                                    CohortName = reader.GetString(reader.GetOrdinal("CohortName"))
                                }
                            };

                            students.Add(student);
                        }

                        reader.Close();

                        return(Ok(students));
                    }
                }
            }
        }
示例#47
0
    public void PrepareExerciseWeb(string s)
    {
        RaiseEvent(OnPrepareExerciseStart, PrepareStatus.Preparing);
        PrepareExerciseWebParams pwp = JsonConvert.DeserializeObject<PrepareExerciseWebParams>(s);
        Exercise e = (pwp.Exercise) as Exercise;
        this.prepareCaller = (Caller)(pwp.Caller);
        //Exercise e = JsonConvert.DeserializeObject<Exercise>(s);

        behaviour = AnimationBehaviour.GetBehaviour(e.Movement, e.Limb);
        if (behaviour == null)
        {
            DebugLifeware.LogAllDevelopers("Importante: Behaviour no encontrado");
            RaiseEvent(OnPrepareExerciseEnd, PrepareStatus.NotFound);
            return;
        }
        behaviour.RepetitionEnd += behaviour_PrepareEndWeb;
        timeSinceStartPrepareWeb = Time.time;  
        behaviour.PrepareWeb();
        CurrentExercise = e;    
    }
示例#48
0
 public void AddExercise(Exercise exercise)
 {
     context.AddExercise(exercise);
 }
示例#49
0
    static void Main(string[] args)
    {
        string input = Console.ReadLine();

        var data = new Dictionary <string, Dictionary <string, Dictionary <string, List <string> > > >();

        while (input.Equals("go go go") == false)
        {
            Exercise exercise = ReadExercise(input);

            string   topic            = exercise.Topic;
            string   courseName       = exercise.CourseName;
            string   judgeContestLink = exercise.JudgeContestLink;
            string[] problems         = exercise.Problems;

            if (!data.ContainsKey(topic))
            {
                data.Add(topic, new Dictionary <string, Dictionary <string, List <string> > >());
            }

            if (!data[topic].ContainsKey(courseName))
            {
                data[topic].Add(courseName, new Dictionary <string, List <string> >());
            }

            if (!data[topic][courseName].ContainsKey(judgeContestLink))
            {
                data[topic][courseName].Add(judgeContestLink, new List <string>());
            }

            data[topic][courseName][judgeContestLink].AddRange(problems);

            input = Console.ReadLine();
        }

        foreach (var itemData in data)
        {
            string topic     = itemData.Key;
            var    abilities = itemData.Value;

            Console.WriteLine($"Exercises: {topic}");

            foreach (var ability in abilities)
            {
                string courseName = ability.Key;
                var    links      = ability.Value;

                Console.WriteLine(
                    $"Problems for exercises and homework for " +
                    $"the \"{courseName}\" course @ SoftUni.");

                foreach (var link in links)
                {
                    string        judgeLink = link.Key;
                    List <string> problems  = link.Value;

                    int index = 1;

                    Console.WriteLine(
                        $"Check your solutions here: {judgeLink}");

                    foreach (var problem in problems)
                    {
                        Console.WriteLine($"{index}. {problem}");

                        index++;
                    }
                }
            }
        }
    }
 public IActionResult AddExercise(Exercise exercise) //This was originally a post to Index
 {
     Workout.Post(exercise);
     return(RedirectToAction("Index"));
 }
示例#51
0
 public DiscreteAveragingAsianOption(Average.Type averageType, double runningAccumulator, uint pastFixings, DateVector fixingDates, Payoff payoff, Exercise exercise) : this(NQuantLibcPINVOKE.new_DiscreteAveragingAsianOption((int)averageType, runningAccumulator, pastFixings, DateVector.getCPtr(fixingDates), Payoff.getCPtr(payoff), Exercise.getCPtr(exercise)), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
示例#52
0
 public IActionResult Create(Exercise exercise)
 {
     _exerciseRepo.SaveExercise(exercise);
     _exerciseRepo.SaveChanges();
     return(RedirectToAction("Index"));
 }
示例#53
0
 public void Update(Exercise entity)
 {
     Context.Entry(entity).State = EntityState.Modified;
 }
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Repository repository = new Repository();

            //get list of exercises from the database and prints it to the console
            List <Exercise> exercises = repository.GetExercises();

            repository.PrintExercises(exercises);

            Pause();

            // print exercises that use JS
            var JSExercises = exercises.Where(ex => ex.Language == "JavaScript").ToList();

            repository.PrintExercises(JSExercises);

            Pause();

            //add local instance of an exercise
            Exercise DoAllThings = new Exercise()
            {
                ExerciseName = "Do all the things", Language = "JavaScript"
            };

            //add that instance to the database
            repository.AddExerciseToDB(DoAllThings);

            exercises = repository.GetExercises();
            Console.Write("exercises after adding new");
            repository.PrintExercises(exercises);

            Pause();

            //get all instructors from database and print to console
            List <Instructor> instructors = repository.GetAllInstructorsWithCohorts();

            repository.PrintInstructors(instructors);

            Pause();

            //creating a new cohort, then a new instructor with that cohort included. adding to DB and printing to console
            Cohort Cohort32 = new Cohort()
            {
                Id = 3, CohortName = "Cohort 32"
            };
            Instructor instructor = new Instructor()
            {
                FirstName = "New", LastName = "Person", SlackHandle = "slackkk", Specialty = "none", Cohort = Cohort32
            };

            repository.AddInstructorToDB(instructor);
            instructors = repository.GetAllInstructorsWithCohorts();
            Console.Write("instructors after adding");
            repository.PrintInstructors(instructors);

            Pause();

            // get list of students from database and prints to console
            var students = repository.GetStudents();

            repository.PrintStudents(students);

            Pause();
        }
示例#55
0
 public bool Equals(Exercise e)
 {
     return (this.Movement == e.Movement && this.Limb == e.Limb);
 }
示例#56
0
        public async Task <IActionResult> CreateFitnessLogs([FromBody] List <FitnessLog> logs, int userId)
        {
            var logIds = new List <int>();

            var tokenInfo = TokenUtility.GetTokenInfo(HttpContext);

            if (userId != tokenInfo.Id)
            {
                return(Unauthorized(new { Error = "Invalid UserId" }));
            }

            foreach (var log in logs)
            {
                log.UserId = userId;
            }

            try
            {
                using (var transaction = _context.Database.BeginTransaction())
                {
                    // TODO: Fix how the log is created
                    foreach (var log in logs)
                    {
                        // Don't add the exercises/exercise maps until checking
                        // whether they already exist
                        var logMaps = log.ExerciseMaps;
                        log.ExerciseMaps = new List <FitnessLogExerciseMap>();

                        // Create the log
                        var newLog = await _context.FitnessLogs.AddAsync(log);

                        // Save the id for future use
                        await _context.SaveChangesAsync();

                        logIds.Add(newLog.Entity.FitnessLogId);

                        foreach (var exerciseMap in logMaps)
                        {
                            // Verify the exercise type and quantity type exist
                            var dbExerciseType = _context.Enums
                                                 .AsNoTracking()
                                                 .Where(e =>
                                                        e.EnumId == exerciseMap.Exercise.ExerciseTypeId
                                                        )
                                                 .FirstOrDefault();

                            var dbExerciseQuantityType = _context.Enums
                                                         .AsNoTracking()
                                                         .Where(e =>
                                                                e.EnumId == exerciseMap.Exercise.QuantityTypeId
                                                                )
                                                         .FirstOrDefault();

                            int mapExerciseId;

                            if (dbExerciseType != null || dbExerciseQuantityType != null)
                            {
                                // See if an exerise already exists
                                var dbExercise = _context.Exercises
                                                 .AsNoTracking()
                                                 .Where(ex =>
                                                        ex.Quantity == exerciseMap.Exercise.Quantity &&
                                                        ex.ExerciseTypeId == exerciseMap.Exercise.ExerciseTypeId &&
                                                        ex.QuantityTypeId == exerciseMap.Exercise.QuantityTypeId
                                                        )
                                                 .FirstOrDefault();

                                // Create new or use existing exercise
                                if (dbExercise == null)
                                {
                                    var newExercise = new Exercise
                                    {
                                        Quantity       = exerciseMap.Exercise.Quantity,
                                        ExerciseTypeId = dbExerciseType.EnumId,
                                        QuantityTypeId = dbExerciseQuantityType.EnumId
                                    };

                                    var newExerciseResult = await _context.Exercises.AddAsync(newExercise);

                                    await _context.SaveChangesAsync();

                                    mapExerciseId = newExerciseResult.Entity.ExerciseId;
                                }
                                else
                                {
                                    mapExerciseId = dbExercise.ExerciseId;
                                }

                                // Create the map
                                var newMap = new FitnessLogExerciseMap
                                {
                                    FitnessLogId = newLog.Entity.FitnessLogId,
                                    ExerciseId   = mapExerciseId
                                };

                                var newMapResult = await _context.FitnessLogExerciseMaps.AddAsync(newMap);
                            }
                        }
                    }

                    await _context.SaveChangesAsync();

                    await transaction.CommitAsync();
                }

                // Retrieve the new objects
                var results = await _context.FitnessLogs
                              .AsNoTracking()
                              .Include("WorkoutType")
                              .Include("ExerciseMaps.Exercise.ExerciseType")
                              .Include("ExerciseMaps.Exercise.QuantityType")
                              .Where(log =>
                                     log.UserId == userId &&
                                     logIds.Contains(log.FitnessLogId)
                                     )
                              .ToListAsync();

                return(Ok(new { Data = results }));
            }
            catch (Exception ex)
            {
                var message = $"Error creating fitness log for user {userId}";
                var data    = new
                {
                    Source         = ex.Source,
                    Message        = ex.Message,
                    InnerException = ex.InnerException,
                };

                var dataString = JsonConvert.SerializeObject(data);

                _context.Logs.Add(new KravWodLog {
                    Message = message, Data = dataString, TimeStamp = DateTimeOffset.Now
                });
                _context.SaveChanges();

                return(StatusCode(500, new { Error = message }));
            }
        }
示例#57
0
文件: TestBLL.cs 项目: holdbase/IES2
        /// <summary>
        /// 线下作业
        /// </summary>
        /// <param name="TestID">测试id</param>
        /// <param name="PaperName">试卷名称</param>
        /// <param name="OCID"></param>
        /// <param name="UserID">创建人id</param>
        /// <param name="content">内容</param>
        /// <param name="answer">答案</param>
        /// <returns></returns>
        public int Paper_OfflineTest_Edit(int TestID, string PaperName, int OCID, int UserID, string content, string answer, int PaperID)
        {
            ExerciseInfo model = new ExerciseInfo();
            ExerciseCommon exerciseCommon = new ExerciseCommon();
            Exercise exercise = new Exercise();
            PaperGroup pg = new PaperGroup();

            exercise.ExerciseID = 0;
            exercise.OCID = OCID;
            exercise.CourseID = 0;
            exercise.OwnerUserID = UserID;
            exercise.CreateUserID = UserID;
            exercise.ExerciseType = 10;
            exercise.ExerciseTypeName = "问答题";
            exercise.Scope = 0;
            exercise.Diffcult = 0;
            exercise.ShareRange = 0;
            exercise.Keys = "";
            exercise.Kens = "";
            exercise.Conten = content;
            exercise.Analysis = "";
            exercise.Answer = answer;
            exercise.ScorePoint = "";
            exercise.ParentID = 0;

            exerciseCommon.ExerciseType = 10;
            exerciseCommon.ExerciseID = 0;
            exerciseCommon.exercise = exercise;

            model.exercisecommon = exerciseCommon;

            pg.GroupID = 0;
            pg.PaperID = PaperID;
            pg.GroupName = "第1部分";
            pg.Orde = 1;
            pg.Brief = "";
            pg.Timelimit = 0;

            int ExerciseID = Exercise_Writing_M_Edit(model);  //线下作业,添加一个简答题。
            int PaperGroupID = PaperDAL.PaperGroup_ADD(pg);   //试卷添加分组。
            PaperDAL.PaperExercise_ADD(PaperID, PaperGroupID, ExerciseID, 100, 1,0);   //习题添加到试卷
            return TestDAL.Paper_OfflineTest_Edit(TestID, PaperName, OCID, UserID, content, answer, PaperID);
        }
示例#58
0
        public PagedResult <ExerciseDTO> GetExercises(ExerciseSearchCriteria searchCriteria, PartialRetrievingInfo retrievingInfo)
        {
            Log.WriteWarning("GetExercises:Username={0},Search-UserId:{1},SearchGroups:{2}", SecurityInfo.SessionData.Profile.UserName, searchCriteria.UserId, searchCriteria.SearchGroups.Count);
            var session = Session;

            //Profile _profile = null;
            Exercise _exercise = null;

            using (var transactionScope = new TransactionManager(true))
            {
                var myProfile = session.Load <Profile>(SecurityInfo.SessionData.Profile.GlobalId);
                if (searchCriteria.UserId.HasValue)
                {
                    myProfile = session.Load <Profile>(searchCriteria.UserId.Value);
                }

                var ids = myProfile.FavoriteExercises.Select(x => x.GlobalId).ToList();

                var queryExercises = session.QueryOver <Exercise>(() => _exercise).Where(x => !x.IsDeleted);

                if (searchCriteria.ExerciseTypes.Count > 0)
                {
                    var langOr = Restrictions.Disjunction();
                    foreach (var lang in searchCriteria.ExerciseTypes)
                    {
                        langOr.Add <Exercise>(x => x.ExerciseType == (ExerciseType)lang);
                    }
                    queryExercises = queryExercises.And(langOr);
                }

                if (!string.IsNullOrEmpty(searchCriteria.Name))
                {
                    queryExercises = queryExercises.Where(Restrictions.InsensitiveLike("Name", searchCriteria.Name + "%"));
                }


                if (searchCriteria.SearchGroups.Count > 0)
                {
                    Disjunction mainOr = Restrictions.Disjunction();
                    if (searchCriteria.SearchGroups.IndexOf(ExerciseSearchCriteriaGroup.Global) > -1)
                    {
                        Log.WriteVerbose("Search: global");
                        mainOr.Add <Exercise>(dto => dto.Profile == null);
                    }
                    if (searchCriteria.SearchGroups.IndexOf(ExerciseSearchCriteriaGroup.Mine) > -1)
                    {
                        Log.WriteVerbose("Search: mine");
                        mainOr.Add <Exercise>(dto => dto.Profile == myProfile);
                    }
                    if (searchCriteria.SearchGroups.IndexOf(ExerciseSearchCriteriaGroup.Other) > -1)
                    {
                        Log.WriteVerbose("Search: other");
                        mainOr.Add <Exercise>(dto => dto.Profile != null && dto.Profile != myProfile);
                    }
                    if (searchCriteria.SearchGroups.IndexOf(ExerciseSearchCriteriaGroup.Favorites) > -1)
                    {
                        if (ids.Count > 0)
                        {
                            mainOr.Add <BodyArchitect.Model.TrainingPlan>(x => x.GlobalId.IsIn((ICollection)ids));
                        }
                    }
                    queryExercises = queryExercises.Where(mainOr);
                }

                //if (searchCriteria.UserId.HasValue)
                //{
                //    queryExercises = queryExercises.Where(dto => dto.Profile == myProfile);
                //}
                queryExercises = queryExercises.ApplySorting(searchCriteria.SortOrder, searchCriteria.SortAscending);

                var res1 = (from rv in session.Query <RatingUserValue>()
                            from tp in session.Query <Exercise>()
                            where tp.GlobalId == rv.RatedObjectId &&
                            rv.ProfileId == SecurityInfo.SessionData.Profile.GlobalId
                            select rv).ToDictionary(t => t.RatedObjectId);

                var listPack = queryExercises.ToPagedResults <ExerciseDTO, Exercise>(retrievingInfo, null,
                                                                                     delegate(IEnumerable <Exercise> list)
                {
                    var output = new List <ExerciseDTO>();
                    foreach (var planDto in list)
                    {
                        var tmp = planDto.Map <ExerciseDTO>();
                        if (res1.ContainsKey(planDto.GlobalId))
                        {
                            tmp.UserRating       = res1[planDto.GlobalId].Rating;
                            tmp.UserShortComment = res1[planDto.GlobalId].ShortComment;
                        }
                        output.Add(tmp);
                    }
                    return(output.ToArray());
                });
                transactionScope.CommitTransaction();
                return(listPack);
            }
        }
示例#59
0
文件: Swaption.cs 项目: minikie/test
 public Swaption(VanillaSwap simpleSwap, Exercise exercise) : this(NQuantLibcPINVOKE.new_Swaption__SWIG_1(VanillaSwap.getCPtr(simpleSwap), Exercise.getCPtr(exercise)), true) {
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
 }
示例#60
0
 public ConvertibleFixedCouponBond(Exercise exercise, double conversionRatio, DividendSchedule dividends, CallabilitySchedule callability, QuoteHandle creditSpread, Date issueDate, int settlementDays, DoubleVector coupons, DayCounter dayCounter, Schedule schedule) : this(NQuantLibcPINVOKE.new_ConvertibleFixedCouponBond__SWIG_1(Exercise.getCPtr(exercise), conversionRatio, DividendSchedule.getCPtr(dividends), CallabilitySchedule.getCPtr(callability), QuoteHandle.getCPtr(creditSpread), Date.getCPtr(issueDate), settlementDays, DoubleVector.getCPtr(coupons), DayCounter.getCPtr(dayCounter), Schedule.getCPtr(schedule)), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }