def stream(request, game_id, round_id, thread_id, message_id): thread = Thread.get_by_uid(thread_id) since = Activity.get_by_uid(message_id) if thread is None: raise Http404 if not thread.profile_can_view(request.profile): return HttpResponse('Unauthorized', status=401) if request.method != 'GET': return HttpResponse('Method Not Allowed', status=405) activities = Activity.get_activities(request.user, thread, since=since) return json(list(activities.run()))
def test_activity_logging(self): s = Student(first_name='billy') act1 = Activity(activity_name='nap') act_entry1 = ActivityLog(student_id=s.student_id, activity_id=act1.activity_id) s.activity.append(act_entry1) act1.student.append(act_entry1) act_entry2 = ActivityLog(student_id=s.student_id, activity_id=act1.activity_id) s.activity.append(act_entry2) act1.student.append(act_entry2) self.assertTrue(len(s.activity) == 2)
def new_activity() -> str: activity: str = request.json['activity'] user_id: int = request.json['userId'] new_scrum_activity: Activity = Activity(activity=activity, user_id=user_id) db.session.add(new_scrum_activity) db.session.commit() result = activity_schema.dump(new_scrum_activity) return jsonify(result.data)
def iap_activation(): """In-app purchase activation.""" data = request.get_json() user_id = data.get('user', {}).get('id') user = User.get(user_id) if user_id is not None else None if user is not None: user.iap_receipt = data.get('receipt', None) user.active = True user.promo_id = None user.promo_timestamp = None user.stripe_customer = None if user.stripe_subscription: try: stripe.Subscription.delete(user.stripe_subscription) except: pass Activity.activate(user.id, 399, True) return jsonify({"done": True})
def create_activity(item, mt, id_string): act = Activity() act.name = item['name'] act.polyline = item['map']['summary_polyline'] act.url = f'https://www.strava.com/activities/{item["id"]}' act.mountains.append(mt) act.activity_id = id_string act.date = item['start_date'] return act
def post_activity(user_id): data = request.json activity = Activity(user_id=user_id, title=data['title'], description=data['description'], distance=float(data['distance']), time=float(data['time']), gpx_file=data['gpx_file']) db.session.add(activity) db.session.commit() return 'Done', 201
def add_activity(itinerary_id): form = ActivityForm() if form.validate_on_submit(): activity = Activity(itinerary_id=itinerary_id, name=form.name.data, description=form.description.data) db.session.add(activity) db.session.commit() print("dONE") return redirect(url_for('itinerary', itinerary_id=itinerary_id)) return render_template('add_activity.html', form=form)
def test_get_misspelled_words(self): u = User(username='******', email='*****@*****.**', role="Student", current_class="test") newClass = Class("test", "test", 2019, "French", "Class") a = Activity() a.populate_table() db.session.add_all([u, newClass]) db.session.commit() misspelled_word = Misspelled_Word(class_id=u.current_class, user_id=u.user_id, word="Hello", translated_word="Bonjour") db.session.add(misspelled_word) db.session.commit() user_mispelled = u.get_misspelled_words(u.current_class).all() class_mispelled = newClass.get_misspelled_words().all() self.assertEqual(len(user_mispelled), 1) self.assertEqual(len(class_mispelled), 1)
def get_activity(current_user, activity_id): """ Return an activity object for the supplied activity id. :param current_user: User :param activity_id: Activity Id :return: """ try: activity = Activity(int(activity_id)) return response_for_activity(activity.json) except ValueError: return response('failed', "Activity not found", 404)
def test_get_students_new_vocab(self): u = User(username='******', email='*****@*****.**', role="Student", current_class="test") newClass = Class("test", "test", 2019, "French", "Class") a = Activity() a.populate_table() db.session.add_all([u, newClass]) db.session.commit() newVocab = Student_Vocab(english="hello", translation="bonjour", user_id=u.user_id, class_id=u.current_class, activity_id=14) db.session.add(newVocab) db.session.commit() vocab = u.get_students_new_vocab(u.current_class).all() class_vocab = newClass.get_class_new_vocab() self.assertEqual(len(vocab), 1) self.assertEqual(len(class_vocab), 1)
def test_class_stats(self): u = User(username='******', email='*****@*****.**', role="Student") newClass = Class("test", "test", 2019, "French", "Class") a = Activity() a.populate_table() db.session.add_all([u, newClass]) db.session.commit() student_class = Student_Class(u.user_id, "test") u.current_class = "test" db.session.add(student_class) db.session.commit() score = 50 activity_id = 2 activity_result = Activity_Results(activity_id=activity_id, score=score, class_id=u.current_class) db.session.add(activity_result) db.session.commit() student_activity = Student_Activity( activity_instance_id=activity_result.activity_instance_id, student_id=u.user_id) db.session.add(student_activity) db.session.commit() studentsInClass = newClass.get_all_students_in_class().all() students_with_averages, class_average = newClass.get_students_with_average( studentsInClass) activities = newClass.get_activity_scores_in_class().all() highest_activity, lowest_activity, barData = newClass.get_activity_averages_in_class( activities) filename, averages = newClass.get_class_distribution_chart( students_with_averages) self.assertEqual(class_average, 50) self.assertEqual(highest_activity[0], "Numbers") self.assertEqual(lowest_activity[0], "Numbers") self.assertEqual(highest_activity[1], 50) self.assertEqual(lowest_activity[1], 50) self.assertEqual(len(averages), 1) self.assertEqual(averages[0], 50)
def activities(request, game_id, round_id, thread_id): thread = Thread.get_by_uid(thread_id) if thread is None: raise Http404 if not thread.profile_can_view(request.profile): return HttpResponse('Unauthorized', status=401) if request.method == 'GET': return json(list(Activity.get_activities(request.user, thread))) # no POSTs here, return 404 raise Http404
def add_activity(): form = AddActivityForm() templates = os.listdir('app/templates/activity_templates') form.template.choices = [(n, templates[n]) for n in range(len(templates))] if form.validate_on_submit(): act = Activity(name=form.name.data, password=form.password.data, owner=current_user.id, template=templates[int(form.template.data)]) db.session.add(act) db.session.commit() return redirect(url_for('index')) return render_template('add_activity.html', form=form)
def test_get_incorrect_letters(self): u = User(username='******', email='*****@*****.**', role="Student", current_class="test") newClass = Class("test", "test", 2019, "French", "Class") a = Activity() a.populate_table() db.session.add_all([u, newClass]) db.session.commit() for guessChar, wordChar in zip("hillo", "hello"): if guessChar != wordChar: incorrect_character = Incorrect_Character( class_id=u.current_class, user_id=u.user_id, incorrect_letter=guessChar, correct_letter=wordChar) db.session.add(incorrect_character) db.session.commit() incorrect = u.get_incorrect_letters(u.current_class).all() self.assertEqual(len(incorrect), 1) self.assertEqual( len(newClass.get_incorrect_letters_by_students().all()), 1)
def load_activity(self): self.activity = Activity( start_time=pytz.utc.localize( self.activity_data.get_value('start_time') + self.tz_offset), elapsed_time=self.activity_data.get_value('total_elapsed_time'), start_position_lat=self.activity_data.get_value( 'start_position_lat'), start_position_long=self.activity_data.get_value( 'start_position_long'), timer_time=self.activity_data.get_value('total_timer_time'), distance=self.activity_data.get_value('total_distance'), strides=self.activity_data.get_value('total_strides'), speed=self.activity_data.get_value('enhanced_avg_speed'), max_speed=self.activity_data.get_value('enhanced_max_speed'), calories=self.activity_data.get_value('total_calories'), ascent=self.activity_data.get_value('total_ascent'), descent=self.activity_data.get_value('total_descent'), lap_count=self.activity_data.get_value('num_laps'), heart_rate=self.activity_data.get_value('avg_heart_rate'), max_heart_rate=self.activity_data.get_value('max_heart_rate'), cadence=self.activity_data.get_value('avg_running_cadence'), max_cadence=self.activity_data.get_value('max_running_cadence'), aerobic_training_effect=self.activity_data.get_value( 'total_training_effect'), anaerobic_training_effect=self.activity_data.get_value( 'total_anaerobic_training_effect'), max_power=0, power=0) for r in self.records: if r.power > self.activity.max_power: self.activity.max_power = r.power self.activity.power += r.power self.activity.power /= len(self.records) self.activity.save()
def test_week_activity_duration_two_activity_same_day(): iso_date = '2020-06-18T21:58:33.302785-07:00' my_date = datetime.strptime(iso_date, '%Y-%m-%dT%H:%M:%S.%f%z').date() start_week = charting.get_start_week_date(my_date) activity = Activity(id=1, type=1, title='title', duration=25, iso_timestamp='2020-06-15T21:58:33.302785-07:00') activity_1 = Activity(id=2, type=1, title='title', duration=32, iso_timestamp='2020-06-15T05:58:33.302785-07:00') activities = [activity, activity_1] week_duration = charting.calc_daily_duration_per_exercise_type( activities, start_week) assert len(week_duration) == 6 assert len(week_duration[1]) == 7 assert week_duration[1] == [57, 0, 0, 0, 0, 0, 0]
def add(): form_category = AddCategory() form_activity = AddActivity() all_cat = Category.json_all() if form_category.validate_on_submit( ) and form_category.submit_new_category.data: a_category = Category(category=form_category.category_name.data, username_id=current_user.id) Category.save_to_db(a_category) # print(f'well done, we changed {form_category.name} into {form_category.category_name.data}') return render_template('add.html', form_activity=form_activity, form_category=form_category) if form_activity.validate_on_submit( ) and form_activity.submit_new_activity.data: try: a_activity = Activity(name=form_activity.activity_name.data, category_id=form_activity.category_id.data, username_id=current_user.id) # if form_activity.box.data: # a_activity.category_id = form_activity.activity_category_id.data Activity.save_to_db(a_activity) flash(f'well done, we added {form_activity.activity_name.data}') return render_template('add.html', form_activity=form_activity, form_category=form_category, added_activity=True) except: return render_template('add.html', form_activity=form_activity, form_category=form_category, added_activity=True) return render_template('add.html', form_activity=form_activity, form_category=form_category)
def create_activity(): # res = json.loads(request.data) res = request.get_json() # activity = reqparse.RequestParser() # activity.add_argument('title',type=str,required=True,help='title must be provide') # activity.add_argument('status',type=int,required=True,help='status must be provide') # activity.add_argument('link',type=str,required=True,help='link must be provide') # activity.add_argument('main_img',type=str,required=True,help='main_img must be provide') # activity.add_argument('sort',type=int,required=True,help='sort must be provide') # try: # args = activity.parse_args() # except Exception as e: # print(e) # print(args['title']) # print(res['title'],res['status'],res['link'],res['main_img'],res['sort']) try: if not all([res['title'], str(res['status']), res['link'], res['main_img'], res['sort']]): print((111)) return jsonify(status=-2, errmsg='参数错误') except Exception as e: print((222)) return jsonify(status=-2, errmsg='参数错误') newid = 'HD' + str(Activity.query.count() + 1).zfill(6) data = Activity( activityid=newid, title=res['title'], tag=res.get('tag', ''), link=res['link'], main_img=res['main_img'], sort=res['sort'], status=res['status'] ) try: db.session.add(data) db.session.commit() data = { 'status': '0', 'msg': 'success' } except Exception as e: db.session.rollback() print(e) data = { 'status': '-2', 'msg': 'Fail' } return jsonify(data)
def handle_open(self, endpoint, content): """Handle the opening of a gate by an endpoint. """ if endpoint[0].type == 'openalpr': code, success, meta = self.read_openalpr(endpoint, content) else: code, success, meta = self.read_generic(endpoint, content) if code == '': return False access = Access.query.filter( Access.code == code, Access.endpoint == endpoint[0].id).first() snapshot = self.save_snapshot(endpoint[4]) a = Activity() a.endpoint = endpoint[0].id a.code = code a.meta = meta a.snapshot = snapshot if 'tags' not in a.meta: a.meta['tags'] = [] # TODO: handle valid from/to timestamps if access and success: # Send gate open command requests.get(endpoint[1], timeout=1) a.success = True a.access = access.id # Send NVR trigger requests.get(endpoint[2], timeout=1) db.session.add(a) db.session.commit() return a.success
def addactivity(): form = AddActivityForm() form.activitytype.choices = [(type.id, type.name) for type in current_user.activitytypes] if request.method == "POST": if form.validate_on_submit(): a = Activity(activitytype_id=form.activitytype.data, user_id=current_user.id, timestamp=form.date.data) db.session.add(a) db.session.commit() flash('Activity added!') return redirect(url_for('index')) else: flash('Failed to add activity.') return render_template('add.html', form=form, what="Activity")
def insert_one(self, activity): new_activity = Activity() if "activity" in activity: new_activity.activity = activity["activity"] if "user_id" in activity: new_activity.user = User.objects.get(pk=activity["user_id"]) new_activity.save() return False if new_activity.pk is None else new_activity
def activities(): if request.method == 'GET': activity = db.session.query(Activity).all() if activity is None: return jsonify(status='empty') a_list = [i.return_dict() for i in activity] return jsonify(status='ok', result=a_list) elif request.method == 'POST': data = request.values if data: if data.get('acid'): acid = data.get('acid') activity = Activity.query.filter_by(acid=acid).first() activity.actype = data.get('actype') activity.vol_time = data.get('vol_time') activity.ac_place = data.get('ac_place') activity.subject = data.get('title') finish_time = data.get('finish_time').encode('utf8') start_time = data.get('start_time').encode('utf8') activity.introduce = data.get('introduce') activity.required_stus = data.get('required_stus') activity.finish_time = ' '.join(finish_time.split('T')) + ':00' activity.start_time = ' '.join(start_time.split('T')) + ':00' else: acid = int(time.time()) actype = data.get('actype') vol_time = data.get('vol_time') ac_place = data.get('ac_place') subject = data.get('title') finish_time = data.get('finish_time').encode('utf8') start_time = data.get('start_time').encode('utf8') introduce = data.get('introduce') required_stus = data.get('required_stus') finish_time = ' '.join(finish_time.split('T'))+':00' start_time = ' '.join(start_time.split('T'))+':00' activity = Activity(acid=acid, actype=actype, vol_time=vol_time, ac_place=ac_place, subject=subject, finish_time=finish_time, start_time=start_time, introduce=introduce, required_stus=required_stus) db.session.add(activity) db.session.commit() return jsonify(status='ok') return jsonify(status='fail')
def challenge_done(current_user): random_challenge = None currentuser = current_user.uuid # generates new random challeng while True: query = db.session.query(Challenge.cid) challenges = query.all() # random challenge random_challenge = random.choice(challenges) activity = db.session.query(Activity.cid).filter( Activity.user_id == int(currentuser), Activity.cid == random_challenge.cid).first() if activity is None: break # generates unique id for activity. activityid = (uuid.uuid4().int & (1 << 29) - 1) #get current activity. for a in Activity.query.filter_by(user_id=currentuser, chal_status=4).all(): a.set_status(2) # set current activity to done a.set_point(3) # 3 points for each activity completed a.set_current(False) # not current anymore # add a new activity for this user. active = Activity(activity_id=activityid, cid=random_challenge.cid, user_id=int(currentuser), current=True, chal_status=4) db.session.add(active) db.session.commit() # update user last activity update_last_activity(currentuser) print('Done execute') sys.stdout.flush()
def manual_entry(): if request.method == 'POST': if manual_entry_data_check(request.form['mountain'], request.form['date']): act = Activity() act.name = request.form['act_name'] act.polyline = None act.url = '/view/' + act.name mt = find_mountain(request.form['mountain']) act.mountains.append(mt) act.activity_id = None act.date = convert_date(request.form['date']) current_user.activities.append(act) act.description = request.form['description'] db.session.commit() flash("Peak Saved!") return redirect(url_for('index')) else: flash("Invalid Data") return render_template('manual_entry.html', title="Manual Entry", mt_list=appforms.mountain_choices())
def challenge_skip(current_user): random_challenge = None currentuser = current_user.uuid # generates new random challeng while True: query = db.session.query(Challenge.cid) challenges = query.all() # random challenge random_challenge = random.choice(challenges) activity = db.session.query(Activity.cid).filter( Activity.user_id == int(currentuser), Activity.cid == random_challenge.cid).first() if activity is None: break # generates a unique id for activity. activityid = (uuid.uuid4().int & (1 << 29) - 1) #delete current activity db.session.query(Activity).filter( Activity.chal_status != 2, Activity.user_id == currentuser).delete() # add a new activity for this user. active = Activity(activity_id=activityid, cid=random_challenge.cid, user_id=int(currentuser), current=True, chal_status=4) db.session.add(active) db.session.commit() # update the user last activity. update_last_activity(currentuser) print('Skip executed') sys.stdout.flush()
def add_activity(): param = request.json title = param.get('title') patch_img_url = param.get('patch_img_url') content_url = param.get('content_url') poster_url = param.get('poster_url') enroll_start_at = param.get('enroll_start_at') enroll_stop_at = param.get('enroll_stop_at') status = param.get('status') if title is None: return response(None, ResponseCodeEnum.miss_param) activity_id = getRandString('ac_', 16) activity = Activity(activity_id, title, patch_img_url, content_url, poster_url, enroll_start_at, enroll_stop_at, status) db.session.add(activity) db.session.commit() return response()
def test_week_activity_duration_single_activity_start_week(): iso_date = '2020-06-18T21:58:33.302785-07:00' my_date = datetime.strptime(iso_date, '%Y-%m-%dT%H:%M:%S.%f%z').date() start_week = charting.get_start_week_date(my_date) activity = Activity(id=1, type=1, title='title', duration=25, iso_timestamp='2020-06-15T21:58:33.302785-07:00') activities = [activity] week_duration = charting.calc_daily_duration_per_exercise_type( activities, start_week) assert len(week_duration) == 6 assert len(week_duration[1]) == 7 assert week_duration[1] == [25, 0, 0, 0, 0, 0, 0] for i in range(2, 6): assert week_duration[i] == [0, 0, 0, 0, 0, 0, 0]
def todolist(): form = ActivityForm() if form.validate_on_submit(): activity = Activity(body=form.activity.data, author=current_user) db.session.add(activity) db.session.commit() flash(_l('Your activity is now live!')) return redirect(url_for('main.todolist')) page = request.args.get('page', 1, type=int) cases = current_user.followed_activity().paginate( page, 10, False) next_url = url_for('main.todolist', page=cases.next_num) \ if cases.has_next else None prev_url = url_for('main.todolist', page=cases.prev_num) \ if cases.has_prev else None return render_template('todolist.html', title='Todo list', form=form, activity=cases.items, next_url=next_url, prev_url=prev_url)
def test_week_activity_null_distance_end_week(): # has an entry on the exact last day of the week iso_date = '2020-06-18T21:58:33.302785-07:00' my_date = datetime.strptime(iso_date, '%Y-%m-%dT%H:%M:%S.%f%z').date() _, start_week, end_week = charting.get_week_bookends(my_date) activity = Activity(id=1, type=1, title='title', duration=25, iso_timestamp='2020-06-15T21:58:33.302785-07:00') activities = [activity] week_duration = charting.calc_daily_duration_per_exercise_type( activities, start_week, end_week, sum_by='distance') assert len(week_duration) == 6 assert len(week_duration[1]) == 7 assert week_duration[1] == [0, 0, 0, 0, 0, 0, 0]
def logrun(): if not current_user.is_authenticated: return redirect(url_for('login')) form = LogRunForm() if form.validate_on_submit(): run = Activity(date=form.date.data, walk_miles=form.walk.data, run_miles=form.run.data, total_miles=form.walk.data + form.run.data, type=form.type.data, shoe=form.shoe.data, user_id=current_user.id) db.session.add(run) db.session.commit() return redirect(url_for('logrun')) return render_template('logrun.html', title='Log Run', form=form)
def test_insertion(self): conn = engine.connect() insertion = Activity( date='20160704', steps=10000, user_id='1', total_sleep=8, resting_hr=60, step_week_slope=1, sleep_week_slope=1, hr_week_slope=1, curr_health_score=60, health_score_in_week=65 ) db.session.add(insertion) db.commit() s = db.select() result = conn.execute(s) for row in result: print row self.assertEqual(result, 200)
def test_week_activity_distance_positive_timezone(): # has an entry for a timezone ahead of UTC iso_date = '2020-06-18T21:58:33.302785-07:00' my_date = datetime.strptime(iso_date, '%Y-%m-%dT%H:%M:%S.%f%z').date() _, start_week, end_week = charting.get_week_bookends(my_date) activity = Activity(id=1, type=1, title='title', duration=25, distance=10, iso_timestamp='2020-06-15T04:58:33.302785+05:00') activities = [activity] week_duration = charting.calc_daily_duration_per_exercise_type( activities, start_week, end_week, sum_by='distance') assert len(week_duration) == 6 assert len(week_duration[1]) == 7 assert week_duration[1] == [10, 0, 0, 0, 0, 0, 0]