Beispiel #1
0
def update_score(game):
    """Update result to current day"""

    supremacy = Supremacy(game.game_id, game.game_host)
    current_day = game.day

    for day_index in range(game.last_day, current_day):
        day_index += 1

        result = supremacy.score(day_index)

        ranking = result["ranking"]["ranking"]
        ranking.pop(0)

        player_id = 0

        for score in ranking:
            player_id += 1
            if score >= 20:
                player = game.players.filter(
                    Player.player_id == player_id).first()
                day = player.days.filter(Day.day == day_index).first()

                if day is None:
                    day = Day()
                    day.day = day_index
                    day.points = score
                    day.game_id = game.id
                    day.player_id = player.id
                    db.session.add(day)

    db.session.commit()
Beispiel #2
0
def get_results(game_id):
    """Return result from game"""
    game = Game.query.filter(Game.game_id == game_id).first()
    if game is None:
        game = update_game(game_id)

    game.last_result_time = datetime.now()
    current_day = get_day(game)

    for day_index in range(game.last_day, current_day):
        day_index += 1

        result = get_score(game, day_index)
        result.pop(0)

        player_id = 0

        for score in result:
            player_id += 1
            if score >= 20:
                player = game.players.filter(
                    Player.player_id == player_id).first()
                day = player.days.filter(Day.day == day_index).first()

                if day is None:
                    day = Day()
                    day.day = day_index
                    day.points = score
                    day.game_id = game.id
                    day.player_id = player.id
                    db.session.add(day)

    db.session.commit()

    return game
Beispiel #3
0
def get_user_days(user):
    # Get all the days between today and 10 days before
    # user signed up
    days = list(user.days.all())

    if not days:
        used_dates = []
    used_dates = [day.date for day in days]

    today = datetime.date.today()

    # set first date checked
    currently_checked_date = user.date_joined.date() - datetime.timedelta(
        days=10)

    while currently_checked_date < today:
        if currently_checked_date not in used_dates:
            day = Day(user=user, date=currently_checked_date)
            day.save()

            days.append(day)

        currently_checked_date = currently_checked_date + datetime.timedelta(
            days=1)

    return days
Beispiel #4
0
def day_create():
    cset = CalendarSetting.query.get(1)
    if cset.finalized == True:
        flash("The calendar is finalized. You can't add new days.", "danger")
        return redirect(url_for('calendar.settings'))

    heading = "Create New Day"
    form = DayForm()
    form.submit.label.text = "Create Day"

    if form.validate_on_submit():
        order_num = get_next_day_order()

        new_day = Day(name=form.name.data,
                      abbreviation=form.abbreviation.data,
                      description=form.description.data,
                      order=order_num)

        db.session.add(new_day)
        db.session.commit()

        flash("Day added.", "success")
        return redirect(url_for("calendar.settings"))

    return render_template("calendar/form.html",
                           form=form,
                           heading=heading,
                           title=page_title("Add Day"))
Beispiel #5
0
def check():
    users = User.query.all()
    now = datetime.now()
    for user in users:
        today = str(now.year) + "-" + str(now.month) + "-" + str(now.day)
        day = Day(day=today, workhours=user.workings, user_id=user.id)
        db.session.add(day)
        db.session.commit()
        user.workings = 0.0
        db.session.add(user)
        db.session.commit()
        if now.day == 1:
            month = str(now.year) + "-" + str(now.month - 1)
            dayshours = 0.0
            days = Day.query.filter_by(user_id=user.id).all()
            for da in days:
                if da.day > month:
                    dayshours = dayshours + da.workhours
            month = Month(month=month, workhours=dayshours, user_id=user.id)
            db.session.add(month)
            db.session.commit()
            if now.month == 1:
                year = str(now.year - 1)
                monthshours = 0.0
                months = Month.query.filter_by(user_id=user.id).all()
                for mon in months:
                    if mon.month > year:
                        monthshours = monthshours + mon.workhours
                year = Year(year=year, workhours=monthshours, user_id=user.id)
                db.session.add(year)
                db.session.commit()
    return redirect(url_for("home.index"))
Beispiel #6
0
def store_day(date):
    day = get_day(date).toJSON()

    day_db_model = Day(
        date=day['date'],
        indoor_avg_temp=day['indoor_avg_temp'],
        indoor_avg_hum=day['indoor_avg_hum'],
        outdoor_avg_temp=day['outdoor_avg_temp'],
        outdoor_avg_hum=day['outdoor_avg_hum']
    )

    db.session.add(day_db_model)
    db.session.commit()
def create_day():
    try:
        data = request.get_json()
        day = Day(data)
        db.session.add(day)
        db.session.commit()
        return jsonify ({
            "status": "ok",
            "msg": "Успешно добавлено"})
    except Exception as e:
        return jsonify ({
            "status": "err",
            "msg": str(e)})
Beispiel #8
0
def user_data(request):
    form = UserDataForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            user = request.user
            user.userprofile.age = form.cleaned_data['age']
            user.userprofile.weight = form.cleaned_data['weight']
            user.userprofile.height = form.cleaned_data['height']
            user.userprofile.sex = form.cleaned_data['sex']
            user.userprofile.kcal = form.cleaned_data['kcal']
            user.userprofile.protein = form.cleaned_data['protein']
            user.userprofile.carbohydrates = form.cleaned_data['carbohydrates']
            user.userprofile.fats = form.cleaned_data['fats']
            user.userprofile.water = form.cleaned_data['water']
            user.userprofile.steps = form.cleaned_data['steps']
            user.save()
            if user.userprofile.first_login == 1:
                user.userprofile.first_login = 0
                user.userprofile.pulse = 60
                user.save()
                meal_set = MealSet()
                meal_set.save()
                day = Day(
                    date=datetime.datetime.now(),
                    weight=user.userprofile.weight,
                    pulse=user.userprofile.pulse,
                    expected_kcal=user.userprofile.kcal,
                    expected_protein=user.userprofile.protein,
                    expected_carbohydrates=user.userprofile.carbohydrates,
                    expected_fats=user.userprofile.fats,
                    expected_water=user.userprofile.water,
                    expected_steps=user.userprofile.steps,
                    meal_set=meal_set,
                    user=user)
                day.save()
            else:
                day = user.day_set.filter(date=datetime.datetime.now()).first()
                day.weight = form.cleaned_data['weight']
                day.expected_kcal = form.cleaned_data['kcal']
                day.expected_protein = form.cleaned_data['protein']
                day.expected_carbohydrates = form.cleaned_data['carbohydrates']
                day.expected_fats = form.cleaned_data['fats']
                day.expected_water = form.cleaned_data['water']
                day.expected_steps = form.cleaned_data['steps']
                day.save()
                return redirect('/user_panel')
            return redirect('/index')
    if request.user.userprofile.first_login == 0:
        form = UserDataForm(initial={'sex': request.user.userprofile.sex})
    context = {'form': form}
    return render(request, 'user_data.html', context)
 def test_get_or_create_days(self, mock_get_settings):
     mock_get_settings.return_value = ListSettings(
         start_day_of_week=-1, days_to_display=7)
     u = push_dummy_user()
     list_ = push_dummy_list(u, 'list_')
     c = push_dummy_list(u, 'c')
     self.assertTrue(len(list_.get_or_create_days()) == 7)
     now = date.today()
     days = []
     for i in range(0, 7):
         delta = timedelta(days=i)
         day = Day(list_id=c.id, day=now+delta)
         days.append(day)
         db.session.add(day)
     db.session.commit()
     c_days = c.get_or_create_days()
     self.assertEqual(c_days, days)
Beispiel #10
0
def add_cases():
    date = datetime.strptime(request.json['date'], '%Y/%m/%d')
    count = request.json['count']

    day = Day.query.filter_by(date=date).first()

    if day is not None:
        day.date = date
        day.count = count
        db.session.commit()
        return day_schema.jsonify(day)

    day_cases = Day(date=date, count=count)

    db.session.add(day_cases)
    db.session.commit()

    return day_schema.jsonify(day_cases)
Beispiel #11
0
def new_day():
    if current_user.id != 1:
        return redirect(url_for('not_allowed'))
    days = Day.query.all()
    form = DayCreationForm(request.form)

    if form.validate():
        a = Day(task=form.task.data)
        db.session.add(a)
        db.session.commit()
        day = Day.query.order_by(Day.id.desc()).first()
        date_ = day.timestamp
        new_month = str(form.month.data)
        new_day = str(form.day.data)
        date_ = date_.strptime(new_month + "-" + new_day, "%m-%d")
        day.timestamp = date_
        day.month_str = date_.strftime('%B')
        db.session.add(day)
        db.session.commit()

        return redirect(url_for('activity_manager'))
    return render_template('new_day.html', form=form, days=days)
Beispiel #12
0
 def setUp(self):
     super().setUp()
     self.locality = Locality(id=1, name='Barcelona', country='Spain')
     self.day = Day(**day, locality=self.locality)
     db.session.add_all([self.locality, self.day])
Beispiel #13
0
 def make_day(self, data, **kwargs):
     return Day(**data)
Beispiel #14
0
def index(request):
    user = request.user
    date = datetime.datetime.now()
    if request.GET.dict():
        day_param = request.GET.dict()['date']
        year = int(day_param.split('-')[0])
        month = int(day_param.split('-')[1])
        day = int(day_param.split('-')[2])
        date = datetime.date(year, month, day)
    day = user.day_set.filter(date=date).first()
    if day is None:
        previous_day = user.day_set.filter(
            date__lte=date).order_by('-date').first()
        next_day = user.day_set.filter(date__gte=date).order_by('date').first()
        meal_set = MealSet()
        meal_set.save()
        if previous_day is not None:
            day = Day(
                date=date,
                weight=previous_day.weight,
                pulse=previous_day.pulse,
                expected_kcal=previous_day.expected_kcal,
                expected_protein=previous_day.expected_protein,
                expected_carbohydrates=previous_day.expected_carbohydrates,
                expected_fats=previous_day.expected_fats,
                expected_water=previous_day.expected_water,
                expected_steps=previous_day.expected_steps,
                meal_set=meal_set,
                user=user)
        elif next_day is not None:
            day = Day(date=date,
                      weight=next_day.weight,
                      pulse=next_day.pulse,
                      expected_kcal=next_day.expected_kcal,
                      expected_protein=next_day.expected_protein,
                      expected_carbohydrates=next_day.expected_carbohydrates,
                      expected_fats=next_day.expected_fats,
                      expected_water=next_day.expected_water,
                      expected_steps=next_day.expected_steps,
                      meal_set=meal_set,
                      user=user)
        else:
            day = Day(date=date,
                      weight=user.userprofile.weight,
                      pulse=user.userprofile.pulse,
                      expected_kcal=user.userprofile.kcal,
                      expected_protein=user.userprofile.protein,
                      expected_carbohydrates=user.userprofile.carbohydrates,
                      expected_fats=user.userprofile.fats,
                      expected_water=user.userprofile.water,
                      expected_steps=user.userprofile.steps,
                      meal_set=meal_set,
                      user=user)
        day.save()
    date = add_zero_if_needed(day.date.day) + '/' + add_zero_if_needed(
        day.date.month) + '/' + str(day.date.year)
    activites = PhysicalActivity.objects.all()
    empty_bottles = math.ceil((day.expected_water - day.water) / 250)
    full_bottles = math.ceil(day.expected_water / 250) - empty_bottles
    trainings = day.training_set.all()
    meals = day.meal_set.meal_set.all()
    breakfast = meals.filter(meal_type=MealType.objects.filter(
        name='Breakfast').first()).first()
    lunch = meals.filter(meal_type=MealType.objects.filter(
        name='Lunch').first()).first()
    dinner = meals.filter(meal_type=MealType.objects.filter(
        name='Dinner').first()).first()
    others = meals.filter(meal_type=MealType.objects.filter(
        name='Other').first()).first()
    if breakfast is not None:
        breakfast = breakfast.mealproduct_set.all()
    if lunch is not None:
        lunch = lunch.mealproduct_set.all()
    if dinner is not None:
        dinner = dinner.mealproduct_set.all()
    if others is not None:
        others = others.mealproduct_set.all()
    context = {
        'empty_loop_times': range(1, empty_bottles + 1),
        'full_loop_times': range(1, full_bottles + 1),
        'day': day,
        'date': date,
        'workout_time': convert_seconds_to_time_string(day.activity_time),
        'activities': activites,
        'meals': meals,
        'breakfast': breakfast,
        'lunch': lunch,
        'dinner': dinner,
        'others': others,
        'trainings': trainings
    }
    return render(request, 'index.html', context)
Beispiel #15
0
def day(goal_id):
    goal = Goal.query.get_or_404(goal_id)
    if goal.person != current_user:
        abort(403)
    date_today = date.today()
    diff = (date_today - goal.start_date).days
    day = Day.query.filter_by(day_date=date.today()).first()
    if day == None:
        day = Day(goal=goal)
        db.session.add(day)
        db.session.commit()

    form = DayForm()

    if form.validate_on_submit():
        if form.breakfast_pic.data:
            pf = save_picture1(form.breakfast_pic.data)
            day.breakfast_img_file = pf
            p_img = "C:/Users/Dell/Desktop/OST_Project/Calorimeter/app/static/food_pics/" + format(
                pf)
            p_class = pc.predict_class(p_img)
            p_cal = pc.predict_cal(p_class)
            # predict calories in breakfast, pf is the picture
            # cal = predict(pf)
            day.breakfast = p_cal

        if form.lunch_pic.data:
            pf = save_picture1(form.lunch_pic.data)
            day.lunch_img_file = pf
            p_img = "C:/Users/Dell/Desktop/OST_Project/Calorimeter/app/static/food_pics/" + format(
                pf)
            p_class = pc.predict_class(p_img)
            p_cal = pc.predict_cal(p_class)
            # predict calories in lunch, pf is the picture
            day.lunch = p_cal

        if form.dinner_pic.data:
            pf = save_picture1(form.dinner_pic.data)
            day.dinner_img_file = pf
            p_img = "C:/Users/Dell/Desktop/OST_Project/Calorimeter/app/static/food_pics/" + format(
                pf)
            p_class = pc.predict_class(p_img)
            p_cal = pc.predict_cal(p_class)
            # predict calories in dinner, pf is the picture
            # cal = predict(pf)
            day.dinner = p_cal

        db.session.commit()
        flash('Meal for the day updated successfully', 'success')
        return redirect(url_for('day', goal_id=goal.id))

    b_img = url_for('static', filename='food_pics/' + day.breakfast_img_file)
    l_img = url_for('static', filename='food_pics/' + day.lunch_img_file)
    d_img = url_for('static', filename='food_pics/' + day.dinner_img_file)
    return render_template('day.html',
                           goal=goal,
                           diff=diff,
                           day=day,
                           b_img=b_img,
                           l_img=l_img,
                           d_img=d_img,
                           form=form)
Beispiel #16
0
from app import db
from app.models import Course, Day, Room, CourseCount, MondayRoomAvailability, TuesdayRoomAvailability, ThursdayRoomAvailability, WednesdayRoomAvailability, FridayRoomAvailability, SaturdayRoomAvailability

day1 = Day(day_id="Mon", day_name="Monday")
day2 = Day(day_id="Tues", day_name="Tuesday")
day3 = Day(day_id="Wed", day_name="Wednesday")
day4 = Day(day_id="Thur", day_name="Thursday")
day5 = Day(day_id="Fri", day_name="Friday")
day6 = Day(day_id="Sat", day_name="Saturday")

db.session.add(day1)
db.session.commit()
db.session.add(day2)
db.session.commit()
db.session.add(day3)
db.session.commit()
db.session.add(day4)
db.session.commit()
db.session.add(day5)
db.session.commit()
db.session.add(day6)
db.session.commit()

course1 = Course(course_id="COMP2211", course_name="Analysis of Algorithms")
course2 = Course(course_id="COMP2201", course_name="Discrete Mathematics")
course3 = Course(course_id="COMP2190", course_name="Net-Centric Computing")
course4 = Course(course_id="COMP3191",
                 course_name="Principles of Computer Networking")
course5 = Course(course_id="COMP3702", course_name="Theory of Computations")
course6 = Course(course_id="COMP3161",
                 course_name="Database Management Systems")
Beispiel #17
0
def parse_data(data):
    latestDate = str(data['time'])
    if latestDate[:10] != currentData['date'][:10]:
        d = Day(year=currentData['date'][:4],
                month=currentData['date'][5:7],
                day=currentData['date'][8:10],
                maxtemp=temprange['maxtemp'],
                mintemp=temprange['mintemp'],
                avetemp=temprange['avetemp'],
                rain=currentData['rain'])
        db.session.add(d)
        db.session.commit()
        del temps[:]
        del temptime[:]
        del rain[:]
        print("New Day!")
    currentData['date'] = str(data['time'])
    try:
        try:
            checkDate = Temperature.query.all()
            if checkDate[0].date[:10] != latestDate[:10]:
                Temperature.query.delete()
                Rain.query.delete()
                db.session.commit()
        except Exception:
            pass

        currentData['temp'] = round(
            (float(data['temperature_F']) - 32) * (0.55), 2)
        t = Temperature(date=currentData['date'], temp=currentData['temp'])
        db.session.add(t)
        db.session.commit()

        myTemps = Temperature.query.all()
        for x in myTemps:
            temps.append(x.temp)
            temptime.append(x.date)

        temprange['maxtemp'] = max(temps)
        temprange['maxtime'] = temptime[temps.index(max(temps))]
        temprange['mintemp'] = min(temps)
        temprange['mintime'] = temptime[temps.index(min(temps))]
        temprange['avetemp'] = round(sum(temps) / float(len(temps)), 2)

        del temps[:]
        del temptime[:]

    except Exception:
        pass
    try:
        currentData['windspeed'] = round(
            float(data['wind_speed_mph']) * 1.60934, 2)
        #print(currentWindSpeed)
    except Exception:
        pass
    try:
        currentData['winddir'] = str(data['wind_dir'])
        #print(currentWindDir)
    except Exception:
        pass
    try:
        currentData['humidity'] = str(data['humidity'])
        #print(currentHumidity)
    except Exception:
        pass
    try:
        r = Rain(rain=float(data['raincounter_raw']))
        db.session.add(r)
        db.session.commit()
        myRain = Rain.query.all()
        for x in myRain:
            rain.append(x.rain)
        currentData['rain'] = (max(rain) - min(rain)) * 0.25
        del rain[:]

        #print(currentRain)
    except Exception:
        pass