def put(self, node_id): node = None nodes = Node.query.all() # @UndefinedVariable if nodes: for x in nodes: if x.rid == node_id: node = x if node: args = self.reqparse.parse_args() new_lat = args['lat'] new_lon = args['lon'] new_pos = args['position'] location = Location(lat=new_lat, lon=new_lon) db.session.add(location) # @UndefinedVariable exisiting_goal_id = 0 existing_goal = None for goal in node.goals: old_pos = goal.position if int(old_pos) == (int(new_pos)+1): exisiting_goal_id = goal.id exisiting_goal = goal if exisiting_goal_id != 0: db.session.delete(exisiting_goal) newgoal = Goal() newgoal.location = location newgoal.position = int(new_pos) + 1 db.session.add(newgoal) node.goals.append(newgoal) db.session.commit() return {'new_goals': jsonNodeGoal(node)}
def get(self, d): # Run after admin user logs in u = User.query().get() if u: today = datetime.today() g = Goal.CreateMonthly(u, date=today) g.Update(text=["Get it done"]) g2 = Goal.Create(u, str(today.year)) g2.Update(text=["Make progress"]) ndb.put_multi([g, g2]) h = Habit.Create(u) h.Update(name="Run") h.put() p = Project.Create(u) p.Update(title="Blog post", subhead="How Flow works") p.put() Task.Create(u, "Get this done").put() t = Task.Create(u, "Think hard", due=datetime.today()) t2 = Task.Create(u, "Think even harder", due=datetime.today()) message = "OK" else: message = "No user" self.json_out({'message': message})
def goals(): requests = User.objects(id = g.user.id).first().goalrequest myGoals = Goal.objects(people=g.user.id) completedGoals = Goal.objects(completed=g.user.id) missedGoals = Goal.objects(missed=g.user.id) return render_template('goals.html', goals = myGoals, completedGoals = completedGoals, missedGoals = missedGoals, requests = requests)
def add_goal(): username = session['username'] if request.form["button"] == u"新規作成": goal_text = request.form['goal_text'] if goal_text != "": Goal(username=username, content=goal_text).save() elif request.form["button"] == u"削除": rmgoal = request.form['rmgoal'] Goal.objects(username=username, content=rmgoal).delete() return redirect('/goal')
def setUp(self): self.set_application(tst_app) self.setup_testbed() self.init_standard_stubs() self.init_app_basics() u = self.users[0] self.goal_annual = Goal.Create(u, '2017') self.goal_annual.Update(text=["Annual goal 1", "Annual goal 2"]) self.goal_monthly = Goal.CreateMonthly(u) self.goal_monthly.put() self.goal_annual.put()
def goals(): requests = User.objects(id=g.user.id).first().goalrequest myGoals = Goal.objects(people=g.user.id) completedGoals = Goal.objects(completed=g.user.id) missedGoals = Goal.objects(missed=g.user.id) return render_template('goals.html', goals=myGoals, completedGoals=completedGoals, missedGoals=missedGoals, requests=requests)
def goal_new(): from models import Goal form = NewGoalForm(request.form) new_status = "form" if request.method == "POST": try: new_goal = Goal(title=form.title.data, user=current_user.self(), description=form.description.data) new_goal.save() new_status = "success" except OperationError: new_status = "fail" return render_template("goal/new.html", form=form, new_status=new_status)
def add(week_id): """Add a goal task.""" f = GoalForm() # print(f.data) if f.validate_on_submit(): new_goal = Goal() f.populate_obj(new_goal) new_goal.week_id = week_id db.session.add(new_goal) db.session.commit() # else: # print('validation failed') return redirect(url_for('worksheet.worksheet', week_id=week_id))
def goal_copy(goal_id): from models import Goal, Milestone goal = Goal.objects.get_or_404(id=goal_id) if (goal.user.id == current_user.get_id()): abort(410) else: new_goal = Goal(title=goal.title, description=goal.description, user=current_user.self(), original=goal) new_goal.save() milestones = Milestone.objects(goal=goal.id) for milestone in milestones: new_milestone = Milestone(goal=new_goal, message=milestone.message) new_milestone.save() return redirect("/goal/%s" % new_goal.id)
def goal_view(goal_id=None): if goal_id: # ---- Delete a goal and redirect to http ref goal = Goal.get_by_id(goal_id) if goal_id else None if not goal: flash('The goal with the id {} could not be found'.format(goal_id), 'error') else: if goal.movement.get().get_current_cycle() >= goal.cycle: flash('You can only delete goals for future cycles', 'error') else: goal.key.delete() flash("Goal has been deleted", 'info') return redirect(request.referrer or url_for('index')) else: # ---- Create a new goal and redirect http ref form = GoalForm(request.form) if form.validate_on_submit(): author = Persona.get_by_id(users.get_current_user().user_id()) if not author: flash("You user account was not found", "error") return redirect(request.referrer) movement = Movement.get_by_id(int(form.movement_id.data)) if not movement: flash("The movement '{}' was not found".format(form.movement_id.data), 'error') return redirect(request.referrer) if len(form.desc.data) > 500: # Remove non-ascii characters flash("Goals can have at most 500 characters. Your goal: {}".format( "".join(i for i in form.desc.data if ord(i) < 128)), "error") return redirect(request.referrer) goal = Goal( movement=movement.key, author=author.key, cycle=int(form.cycle.data) if form.cycle.data else None, desc=form.desc.data ) try: goal.put() goal_id = goal.key.id() flash("Goal successfully created", 'success') return redirect(request.referrer or url_for('index')) except CapabilityDisabledError: flash("Sorry, datastore is currently in read-only mode", 'error') return redirect(request.referrer or url_for('index')) else: flash("Invalid form submitted", "error") return redirect(request.referrer)
def post(self): # save the goal currentGame = self.request.get("currentGame") if(currentGame): newGoal = Goal(game = currentGame, destination = self.request.get("destination"), pointValue = int(self.request.get("pointValue"))) newGoal.put() # attach the goal to the current game myGame = Game.query(Game.gameName==currentGame).fetch()[0] myGame.goals.append(newGoal) myGame.put() self.redirect(self.request.referer)
def add_problem(request, patient_id): role = UserProfile.objects.get(user=request.user).role authenticated = True if (role == 'physician' or role == 'admin') else False if 'problem_name' in request.POST: problem = Problem(patient=User.objects.get(id=patient_id), problem_name=request.POST['problem_name'], concept_id=request.POST['concept_id'], authenticated=authenticated) problem.save() elif 'goal' in request.POST: goal = Goal(patient=User.objects.get(id=patient_id), goal=request.POST['goal']) goal.save() elif 'todo' in request.POST: print 'todo' print request.POST todo = ToDo(patient=User.objects.get(id=patient_id), todo=request.POST['todo']) todo.save() return HttpResponse('added')
def goal_create_goal(request): """ Creates a goal if the user is authenticated. """ if request.user.is_authenticated(): if request.method == "GET": return render(request, 'goals/createGoal.html') if request.user.is_authenticated(): data = json.loads(request.body) title = data['title'] description = data['description'] creator = request.user prize = data['prize'] private_setting = data['private_setting'] goal_type = data['goal_type'] unit = data['unit'] ending_value = data['ending_value'] ending_date = data['ending_date'] response = Goal.create(title, description, creator, prize, private_setting, goal_type, ending_value, unit, ending_date) if response['errors']: return HttpResponse(json.dumps(response), content_type = "application/json") else: goal = response['goal'] redirect = "/goals/%s/" % (goal.id) return HttpResponse(json.dumps({"redirect" : redirect, "errors" : response["errors"]}), content_type = "application/json") else: return HttpResponse("Invalid request", status=500) else: return HttpResponseRedirect('/')
def get(self, id, *args, **kwargs): log.info('Getting a goal: %s' % (id,)) goal = Goal.get_by_id(int(id)) if goal is None: self.response.write(dumps({'error': 'invalid id: %s' % (id,)})); return self.response.write(dumps(goal.get_as_dict()))
def post(self, id, *args, **kwargs): log.info('Posting a goal update for %s of %s' % (id, unicode(self.request.POST),)) goal = Goal.get_by_id(int(id)) if goal is None: self.response.write(dumps({'error': 'invalid id: %s' % (id,)})) return try: if 'name' in self.request.POST: goal.name = self.request.get('name') if 'latitude' in self.request.POST: goal.center.lat = float(self.request.get('latitude')) if 'longitude' in self.request.POST: goal.center.lon = float(self.request.get('longitude')) if 'radius' in self.request.POST: goal.radius = int(self.request.get('radius')) if 'expires' in self.request.POST: goal.expires = \ datetime.utcfromtimestamp(int(self.request.get('expires'))) if 'count' in self.request.POST: goal.count = int(self.request.get('count')) if 'desired' in self.request.POST: goal.desired = self.request.get('desired') in \ ['yes','1','true'] and True or False goal.put() self.response.write(dumps({'updated': goal.key().id()})) except Exception, e: log.exception('Error updating a goal') self.response.write(dumps({'error': unicode(e)}))
def joingoal(goalid): goal = Goal.objects(id=goalid).first() me = User.objects(id=g.user.id).first() feeditem = GoalRequest(message=g.user.name + " just joined a goal you are working on", user=me, goal=goal) for person in goal.people: if person != me: person.feed.append(feeditem) person.save() friend = person goal.people.append(me) goal.save() feeditem = GoalRequest(message="Check out the goal you just joined with " + friend.name, user=friend, goal=goal) User.objects(id=g.user.id).update_one(pull__feed__goal=ObjectId(goalid)) User.objects(id=g.user.id).update_one(push__feed=feeditem) User.objects(id=g.user.id).update_one(pull__goalrequest=ObjectId(goalid)) return redirect(url_for('index'))
def update(self, d): ''' Create or update ''' id = self.request.get('id') params = tools.gets(self, strings=['text1', 'text2', 'text3', 'text4'], integers=['assessment'] ) goal = self.user.get(Goal, id=id) if not goal: goal = Goal.Create(self.user, id=id) if goal: text = [] for i in range(1, 5): key = 'text%d' % i if key in params: text_i = params.get(key) if text_i: text.append(text_i) if text: params['text'] = text goal.Update(**params) goal.put() self.message = "Goal saved" self.success = True else: self.message = "Couldn't create goal" self.set_response({ 'goal': goal.json() if goal else None })
def current(self, d): [annual, monthly, longterm] = Goal.Current(self.user) self.set_response({ 'annual': annual.json() if annual else None, 'monthly': monthly.json() if monthly else None, 'longterm': longterm.json() if longterm else None }, success=True)
def setUp(self): self.school = School(name='Minnesota') db.session.add(self.school) db.session.commit() self.tch = Teacher(first_name='Jess', last_name='Christensen', title='K4-2nd Sped', school_id=self.school.id, username='******', password='******') db.session.add(self.tch) db.session.commit() self.stu = Student(first_name='Fake', last_name='Kid', dob=date(2012, 1, 24), grade=1, teacher_id=self.tch.id, dis_area='OHI') db.session.add(self.stu) db.session.commit() self.iep = IEP(student_id=self.stu.id, teacher_id=self.tch.id) db.session.add(self.iep) db.session.commit() self.goal = Goal(iep_id=self.iep.id, goal="Increase CWPM to 23", standard="Read with fluency") db.session.add(self.goal) db.session.commit()
def post(self, userid): user = User.query.filter_by(userid=userid).first_or_404() goal = Goal(user=user) update_obj_with(goal, request.json, Goal.write_fields.iterkeys()) db.session.add(goal) db.session.commit() return goal
def goal_edit_goal(request, gid): """ Edit the attributes of a goal if you are it's creator """ gid = int(gid) goal = Goal.objects.get(id=gid) user = request.user goalTitle= str(goal.title) if ( user.is_authenticated() and goal.creator.id == user.id ): if request.method == "GET": return render(request, 'goals/editGoal.html', {"goal": goal }) elif request.method == "POST": data = json.loads(request.body) title = data["title"] description = data["description"] prize = data["prize"] ending_value = data["ending_value"] unit = data["unit"] edits = {'title': title, 'description': description, 'prize' : prize, 'ending_value' : ending_value, 'unit' : unit} response = Goal.edit(goal, edits) if response['errors']: return HttpResponse(json.dumps(response), content_type = "application/json") else: return HttpResponse(json.dumps({"redirect":"/goals/" + str(gid), "errors" : response["errors"]}), content_type = "application/json") else: return HttpResponse("Invalid request", status=500)
def get(self): goals = [] for goal in Goal.all().order('-time'): goals.append({ 'prompt': goal.prompt, 'pid': goal.pid, 'time': str(goal.time), }) self.response.out.write(json.dumps(goals))
def _start_match(self): print("Starting match ...") team1 = Team(name=self.team1_name, members=self.team1_members, score_handler=_team_scored) team2 = Team(name=self.team2_name, members=self.team2_members, score_handler=_team_scored) dev = MotionSensor(16, pull_up=True, sample_rate=120, queue_len=1) goal_a = Goal(name="Goal A", score_device=dev, score_handler=None) dev = MotionSensor(19, pull_up=True, sample_rate=120, queue_len=1) goal_b = Goal(name="Goal B", score_device=dev, score_handler=None) self.devices = [goal_a.input_device, goal_b.input_device] games_played = 0 while games_played < self.games_per_match: if games_played % 2 == 0: last_game = self._start_new_game(team1, goal_a, team2, goal_b, ui_queue=self.ui_queue) else: last_game = self._start_new_game(team1, goal_b, team2, goal_a, ui_queue=self.ui_queue) if self.cancelled: self._clean_up() print("Match was cancelled") return # Game has finished check if the next game in the match should be played games_played += 1 if games_played < self.games_per_match: if not self._play_next_game(last_game): self._clean_up() if self.match_end_callback: self.match_end_callback() break else: # Match is over if self.match_end_callback: self.match_end_callback() print("Match is over hope you had fun!")
def newgoal(): goals = Goal.objects(people = g.user.id) me = User.objects(id = g.user.id).first() friends = Set() if goals: for goal in goals: friends.update(goal.people) friends.update(goal.completed) if friends: friends.remove(me) else: friends.add(User.objects(username = '******').first()) form = GoalForm() if form.validate_on_submit(): me = User.objects(id = g.user.id).first() if form.description.data: goal = Goal(name = form.name.data, description = form.description.data, end = form.end.data, people = [me] ) else: goal = Goal(name = form.name.data, end = form.end.data, people = [me] ) goal.save() feeditem = GoalRequest(user=me,goal=goal,message='Your friend invited you to join their goal') people = [] for email in form.people.data: friend = User.objects(username = email).first() friend.feed.append(feeditem) friend.goalrequest.append(goal) friend.save() flash ('Goal added!') return redirect(url_for('goals')) else: print "Nope" return render_template('newgoal.html',users = friends, form = form)
def save(self, current_user, goal=None): if goal: goal.updated_by = current_user for f in ['is_achieved', 'title']: if self.cleaned_data.get(f) is not None: setattr(goal, f, self.cleaned_data[f]) goal.updated_at = datetime.utcnow() goal.updated_by = current_user else: goal = Goal(title=self.cleaned_data.get("title", ""), created_by=current_user, updated_by=current_user, is_achieved=self.cleaned_data.get( "is_achieved", False)) goal.save() return goal
def post(self, *args, **kwargs): log.info('Posting a goal: %s' % (unicode(self.request.POST),)) try: name = self.request.get('name') latitude = float(self.request.get('latitude', None)) longitude = float(self.request.get('longitude', None)) center = db.GeoPt(latitude, longitude) radius = int(self.request.get('radius')) expires = datetime.utcfromtimestamp(int(self.request.get('expires'))) count = int(self.request.get('count', 1)) desired = self.request.get('desired', 'yes') in ['yes', '1', 'true'] and True or False goal = Goal(name=name, center=center, radius=radius, expires=expires, count=count, desired=desired, user=users.get_current_user()) goal.put() log.info('Created a new goal: %s' % (goal.key().id(),)) self.response.write(dumps({'created': str(goal.key().id())})) except Exception, e: log.exception('Error creating a goal') self.response.write(dumps({'error': unicode(e)}))
def add_problem(request, patient_id): role = UserProfile.objects.get(user=request.user).role authenticated = True if (role == 'physician' or role == 'admin') else False if 'problem_name' in request.POST: problem = Problem(patient=User.objects.get(id=patient_id), problem_name=request.POST['problem_name'], concept_id=request.POST['concept_id'], authenticated=authenticated) problem.save() elif 'goal' in request.POST: goal = Goal(patient=User.objects.get(id=patient_id), goal=request.POST['goal']) goal.save() elif 'todo' in request.POST: # print 'todo' # print request.POST todo = ToDo(patient=User.objects.get(id=patient_id), todo=request.POST['todo']) todo.save() return HttpResponse('added')
def parse_mission_text(text): goal_by_id = {} text_by_key = parse_text_by_key(text, '# ', lambda key: key.lower()) mission_text = text_by_key.get('mission', '') try: line = mission_text.splitlines()[0] except IndexError: pass else: goal = Goal.parse_text(line) goal_by_id[goal.id] = goal return goal_by_id
def friends(): goals = Goal.objects(people = g.user.id) me = User.objects(id = g.user.id).first() friends = Set() for goal in goals: friends.update(goal.people) friends.update(goal.completed) if friends: friends.remove(me) return render_template('friends.html', friends = friends)
def friends(): goals = Goal.objects(people=g.user.id) me = User.objects(id=g.user.id).first() friends = Set() for goal in goals: friends.update(goal.people) friends.update(goal.completed) if friends: friends.remove(me) return render_template('friends.html', friends=friends)
def load_goals(): goals = { 'travel': '⛱ Для путешествий', 'study': '🏫 Для учебы', 'work': '🏢 Для работы', 'relocate': '🚜 Для переезда', 'programming': '💻 Для программирования' } for key, value in goals.items(): goal = Goal(goal_slug=key, goal_text=value) db.session.add(goal) db.session.commit()
def addGoal(): lid = str(request.json['leader']) lat = str(request.json['lat']) lon = str(request.json['lon']) msg = 'No message' if int(lid) == 0: # no leader specified, grab first leader in db leader = Node.query.filter_by(leader_id=0).first() # @UndefinedVariable goal = Goal() location = Location(lat=lat, lon=lon) db.session.add(location) # @UndefinedVariable goal.location = location goal.position = len(leader.jumppoints) + 1 db.session.add(goal) leader.goals.append(goal) db.session.commit() return jsonify({'status':'OK','msg': "Goal Added"}) return jsonify({'status':'ERRROR','msg': msg})
def goaltree(goalid): me = User.objects(id=g.user.id).first() goal = Goal.objects(id=goalid).first() tasks = Task.objects(goal=goalid).order_by('-end') form = TaskForm() if form.validate_on_submit(): task = Task(goal=goal, name=form.name.data, description=form.description.data, end=form.end.data, people=[me]) task.save() feeditem = TaskRequest( message='A task was added to a goal you are working on', user=me, task=task, goal=goal) for person in goal.people: if person != me: person.feed.append(feeditem) person.save() return redirect(url_for('goaltree', goalid=goalid)) megacounts = {} for person in goal.people: counts = {'active': [], 'completed': [], 'missed': []} for task in tasks: if person in task.people: counts['active'].append(task) if person in task.completed: counts['completed'].append(task) if person in task.missed: counts['missed'].append(task) megacounts[person.id] = counts return render_template('goaltreelite.html', me=me, goal=goal, tasks=tasks, today=datetime.datetime.now(), form=form, allCounts=megacounts)
def goal_remove_goal(request): """ Removes the goal if it belongs to the user. """ data = json.loads(request.body) goal_id = data["goal_id"] user = request.user response = Goal.remove(goal_id, user) if response['errors']: return HttpResponse(json.dumps(response), content_type = "application/json") return HttpResponse(json.dumps({"redirect" : "/dashboard", "errors" : response["errors"]}), content_type = "application/json")
def test_goal_report(self): g = Goal.Create(self.u, "2017") g.Update(text=["Goal 1", "Goal 2"], assessments=[3, 4]) g.put() self._test_report( {'type': REPORT.GOAL_REPORT}, [[ 'Goal Period', 'Date Created', 'Text 1', 'Text 2', 'Text 3', 'Text 4', 'Goal Assessments', 'Overall Assessment' ], [ "2017", tools.sdatetime(g.dt_created, fmt="%Y-%m-%d %H:%M:%S %Z"), "Goal 1", "Goal 2", "", "", "\"3,4\"", "3.5" ]])
def addincentives(goalid): goal = Goal.objects(id=goalid).first() form = AddIncentivesForm() if form.validate_on_submit(): #TODO will want to prepopulate fields if incentives already exist if form.first.data: first = Incentive(penalties=[form.first.data], number=1) Goal.objects(id=goalid).update_one(add_to_set__incentives=first) if form.second.data: second = Incentive(penalties=[form.second.data], number=2) Goal.objects(id=goalid).update_one(add_to_set__incentives=second) if form.third.data: third = Incentive(penalties=[form.third.data], number=3) Goal.objects(id=goalid).update_one(add_to_set__incentives=third) if form.beyond.data: beyond = Incentive(penalties=[form.beyond.data], number=4) Goal.objects(id=goalid).update_one(add_to_set__incentives=beyond) return redirect(url_for('goaltree', goalid=goalid)) return render_template('addincentives.html', form=form)
def create_network(self, data): goals = data['goals'] policies = data['policies'] id_mapping = {} links = [] network = Network() for policy in policies: p = Policy(id=policy['id']) update_node_from_dict(p, policy) id_mapping[policy['id']] = p network.policies[p.id] = p for conn in policy['connections']: i = conn['id'] a = conn['from_id'] b = conn['to_id'] w = conn['weight'] links.append((i, a, b, w)) for goal in goals: g = Goal(id=goal['id']) update_node_from_dict(g, goal) id_mapping[goal['id']] = g network.goals[g.id] = g for conn in goal['connections']: i = conn['id'] a = conn['from_id'] b = conn['to_id'] w = conn['weight'] links.append((i, a, b, w)) for i, a, b, w in links: a = id_mapping[a] b = id_mapping[b] l = Edge(id=i) l.init(a, b, w) network.edges[l.id] = l network.rank() self.network = network
def newgoal(): goals = Goal.objects(people=g.user.id) me = User.objects(id=g.user.id).first() friends = Set() if goals: for goal in goals: friends.update(goal.people) friends.update(goal.completed) if friends: friends.remove(me) else: friends.add(User.objects(username='******').first()) form = GoalForm() if form.validate_on_submit(): me = User.objects(id=g.user.id).first() if form.description.data: goal = Goal(name=form.name.data, description=form.description.data, end=form.end.data, people=[me]) else: goal = Goal(name=form.name.data, end=form.end.data, people=[me]) goal.save() feeditem = GoalRequest( user=me, goal=goal, message='Your friend invited you to join their goal') people = [] for email in form.people.data: friend = User.objects(username=email).first() friend.feed.append(feeditem) friend.goalrequest.append(goal) friend.save() flash('Goal added!') return redirect(url_for('goals')) else: print "Nope" return render_template('newgoal.html', users=friends, form=form)
def addincentives(goalid): goal = Goal.objects(id = goalid).first() form = AddIncentivesForm() if form.validate_on_submit(): #TODO will want to prepopulate fields if incentives already exist if form.first.data: first = Incentive(penalties = [ form.first.data ], number = 1) Goal.objects(id = goalid).update_one(add_to_set__incentives=first) if form.second.data: second = Incentive(penalties = [ form.second.data ], number = 2) Goal.objects(id = goalid).update_one(add_to_set__incentives=second) if form.third.data: third = Incentive(penalties = [ form.third.data ], number = 3) Goal.objects(id = goalid).update_one(add_to_set__incentives=third) if form.beyond.data: beyond = Incentive(penalties = [ form.beyond.data ], number = 4) Goal.objects(id = goalid).update_one(add_to_set__incentives=beyond) return redirect(url_for('goaltree', goalid=goalid)) return render_template('addincentives.html',form = form)
def edit_goal_page(goal_id): goal = Goal.query.get(goal_id) iep = IEP.query.get(goal.iep.id) teacher = Teacher.query.get(goal.iep.teacher_id) if goal.iep.is_locked == True: flash('IEP is locked. Goals cannot be edited.', 'bad') return redirect(f'/teacher/{teacher.id}') student = Student.query.get(goal.iep.student_id) standards = get_standards_list(student.teacher.school.state_code) grade_level = get_grade_level_standard_sets( append_zero_convert_to_string(student.grade), standards) subject_list = get_subject_list(grade_level) g_form = GoalForm() d_form = ClassworkDataForm() g_form.subject.choices = subject_list if g_form.validate_on_submit() and d_form.validate_on_submit(): Goal.query.filter_by(id=goal.id).delete() ClassworkData.query.filter_by(goal_id=goal.id).delete() goal = Goal(iep_id=iep.id, goal=g_form.goal.data, subject=g_form.subject.data) db.session.add(goal) db.session.commit() data = ClassworkData(goal_id=goal.id, baseline=d_form.baseline.data, current=d_form.baseline.data, attainment=d_form.attainment.data) db.session.add(data) db.session.commit() flash(f"Goal updated!", "good") return redirect(f'/goal/{goal.id}/standard_set') return render_template('/student/edit-goal.html', g_form=g_form, d_form=d_form)
def _goals_request(self): [annual, monthly, longterm] = Goal.Current(self.user) speech = None g = None if monthly: g = monthly speech = "Goals for %s. " % datetime.strftime(g.date, "%B %Y") elif annual: g = annual speech = "Goals for %s. " % g.year() if g: if g.text: for i, text in enumerate(g.text): speech += "%d: %s. " % (i + 1, text) else: speech = "No goals yet" else: speech = "You haven't set up any goals yet. " + GOAL.SET_INFO return speech
def add_goal(message): text_splits = message.text.split(maxsplit=1) goal_main = text_splits[1] if entered_correct(goal_main): goal_created, goal_deadline, goal_name = parse_goal(goal_main) session = Session() goal = Goal(chat_id=message.chat.id, name=goal_name, deadline=goal_deadline, created=goal_created, flag_finished=False) session.add(goal) session.commit() text = "List of your goals: \n" for goal in session.query(Goal).filter( Goal.chat_id == message.chat.id): text += goal.name + '\n' session.close() bot.send_message(message.chat.id, text) else: bot.send_message(message.chat.id, "Sorry, your data isn't correct")
def setUp(self): self.set_application(tst_app) self.setup_testbed() self.init_datastore_stub() self.init_memcache_stub() self.init_taskqueue_stub() self.init_mail_stub() self.register_search_api_stub() self.init_app_basics() self.u = u = self.users[0] self.u.Update(name="George") self.u.put() h = Habit.Create(u) h.Update(name="Run") h.put() t = Task.Create(u, "Dont forget the milk") t.put() g = Goal.CreateMonthly(u, date=datetime.today().date()) g.Update(text=["Get it done", "Also get exercise"]) g.put()
def get(self, d): # TODO: Async fetches with_habits = self.request.get_range('with_habits', default=0) == 1 with_tracking = self.request.get_range('with_tracking', default=1) == 1 with_goals = self.request.get_range('with_goals', default=1) == 1 with_tasks = self.request.get_range('with_tasks', default=1) == 1 date_start = self.request.get('date_start') date_end = self.request.get('date_end') dt_start, dt_end = tools.fromISODate(date_start), tools.fromISODate( date_end) iso_dates = [] habits = [] today = datetime.today() habitdays = [] goals = [] journals, iso_dates = MiniJournal.Fetch(self.user, dt_start, dt_end) if with_habits: habits = Habit.Active(self.user) habitdays = HabitDay.Range(self.user, habits, dt_start, dt_end) if with_tracking: tracking_days = TrackingDay.Range(self.user, dt_start, dt_end) if with_goals: goals = Goal.Year(self.user, today.year) if with_tasks: tasks = Task.DueInRange(self.user, dt_start, dt_end, limit=100) self.set_response( { 'dates': iso_dates, 'journals': [j.json() for j in journals if j], 'habits': [h.json() for h in habits], 'goals': [g.json() for g in goals], 'tasks': [t.json() for t in tasks], 'tracking_days': [p.json() for p in tracking_days], 'habitdays': tools.lookupDict(habitdays, keyprop="key_id", valueTransform=lambda hd: hd.json()) }, success=True)
def test_goals_data_handler(self): load_goals() # List goals response = self.testapp.get('/goals/data') self.assertEquals(response.status_int, 200) self.assertEquals(response.content_type, 'application/json') data = json.loads(response.normal_body) self.assertEquals(len(data), 3) # Add goal response = self.testapp.post_json('/goals/data', {'title': 'Do Great Things'}) self.assertEquals(response.status_int, 200) self.assertEquals(len(Goal.all()), 4) # Complete goal goal = Goal.all()[0] self.assertFalse(goal.done) response = self.testapp.post_json('/goals/data', {'_id': goal.key.id(), 'done': True, 'action': 'accomplish'}) self.assertEquals(response.status_int, 200) goal = Goal.get(goal.key.id()) self.assertTrue(goal.done) # Update goal response = self.testapp.post_json('/goals/data', {'_id': goal.key.id(), 'action': 'update', 'title': 'Do What Matters'}) self.assertEquals(response.status_int, 200) goal = Goal.get(goal.key.id()) self.assertEquals(goal.title, 'Do What Matters') # Disable goal response = self.testapp.post_json('/goals/data', {'_id': goal.key.id(), 'action': 'delete'}) data = json.loads(response.normal_body) self.assertEquals(response.status_int, 200) self.assertEquals(4, len(Goal.all())) self.assertFalse(data['enabled']) # Restore goal response = self.testapp.post_json('/goals/data', {'_id': goal.key.id(), 'action': 'restore'}) data = json.loads(response.normal_body) self.assertEquals(response.status_int, 200) self.assertEquals(4, len(Goal.all())) self.assertTrue(data['enabled'])
def set_new_reading_goal(): if "user_id" in request.form and "target" in request.form and "year" in request.form: user_id = request.form["user_id"], target = request.form["target"], year = request.form["year"] check_achievement(user_id, 'goal') # change so current reads from count of HasRead with dates within that year # current = db.session.query(func.count(HasRead).label('current')).filter(HasRead.user_id==user_id, HasRead.finish_date.between(year + '-01-01', year + '-12-31')).all() # authors = db.session.query(func.count(Book.author).label('count'), Book.author).join(HasRead, HasRead.book_id==Book.book_id).filter(HasRead.user_id==user_id).group_by(Book.author).order_by(desc('count')).limit(3).all() existing_goal = db.session.query(Goal).filter( Goal.user_id == user_id, Goal.year == year).scalar() is not None if not existing_goal: db.session.add( Goal(target=target, current=0, user_id=user_id, year=year)) db.session.commit() return make_response( jsonify({"success:": "Reading goal successfully set"}), 200) else: return make_response(jsonify({"error:": "Failed to set goal"}), 404)
def joingoal(goalid): goal = Goal.objects(id = goalid).first() me = User.objects(id = g.user.id).first() feeditem = GoalRequest(message=g.user.name+" just joined a goal you are working on",user = me, goal = goal) for person in goal.people: if person != me: person.feed.append(feeditem) person.save() friend = person goal.people.append(me) goal.save() feeditem = GoalRequest(message="Check out the goal you just joined with " + friend.name, user = friend, goal = goal) User.objects(id = g.user.id).update_one(pull__feed__goal=ObjectId(goalid)) User.objects(id = g.user.id).update_one(push__feed=feeditem) User.objects(id = g.user.id).update_one(pull__goalrequest=ObjectId(goalid)) return redirect(url_for('index'))
def create_goal(iep_id): iep = IEP.query.get(iep_id) student = Student.query.get(iep.student_id) standards = get_standards_list(student.teacher.school.state_code) grade_level = get_grade_level_standard_sets( append_zero_convert_to_string(student.grade), standards) subject_list = get_subject_list(grade_level) g_form = GoalForm() d_form = ClassworkDataForm() g_form.subject.choices = subject_list goals = Goal.query.filter_by(iep_id=iep.id).all() if g_form.validate_on_submit() and d_form.validate_on_submit(): goal = Goal(iep_id=iep.id, goal=g_form.goal.data, subject=g_form.subject.data) db.session.add(goal) db.session.commit() data = ClassworkData(goal_id=goal.id, baseline=d_form.baseline.data, current=d_form.baseline.data, attainment=d_form.attainment.data) db.session.add(data) db.session.commit() flash( f"Goal created! {goal.goal}. {data.baseline}. {data.attainment}. Select Standard Set", "good") return redirect(f'/goal/{goal.id}/standard_set') return render_template('/student/goal.html', g_form=g_form, d_form=d_form, student=student, iep_id=iep.id, goals=goals)
def test_goal_model(self): goal = Goal(title="Do Great things") goal_key = goal.put() self.assertEquals(len(Goal.all()), 1) g = Goal.get(goal_key.id()) self.assertEquals(g.title, "Do Great things") self.assertFalse(g.done) # Delete goal g.delete() self.assertEquals(len(Goal.all()), 1) self.assertFalse(g.enabled) # Restore goal g.restore() self.assertTrue(g.enabled) # Purge goal g.purge() self.assertEquals(len(Goal.all()), 0)
def goaltree(goalid): me = User.objects(id = g.user.id).first() goal = Goal.objects(id = goalid).first() tasks = Task.objects(goal = goalid).order_by('-end') form = TaskForm() if form.validate_on_submit(): task = Task(goal=goal,name = form.name.data, description = form.description.data, end = form.end.data, people = [me]) task.save() feeditem = TaskRequest(message='A task was added to a goal you are working on',user=me,task=task,goal=goal) for person in goal.people: if person != me: person.feed.append(feeditem) person.save() return redirect(url_for('goaltree',goalid=goalid)) megacounts = {} for person in goal.people: counts = {'active':[],'completed':[],'missed':[]} for task in tasks: if person in task.people: counts['active'].append(task) if person in task.completed: counts['completed'].append(task) if person in task.missed: counts['missed'].append(task) megacounts[person.id] = counts return render_template('goaltreelite.html',me = me, goal = goal, tasks = tasks, today = datetime.datetime.now(), form = form, allCounts=megacounts)
def get(self): self.response.write(dumps([goal.get_as_dict() for goal in Goal.all().filter('user =', self.get_current_user())]))
def completegoal(goalid): Goal.objects(id = goalid).update_one(pull__people = ObjectId(g.user.id)) Goal.objects(id = goalid).update_one(push__completed = ObjectId(g.user.id)) return redirect(url_for('goaltree',goalid=goalid))
def approveincentives(goalid): goal = Goal.objects(id = goalid).first() return render_template('approveincentives.html', goal = goal)
def get_context_data(self, **kwargs): context = super(Dashboard, self).get_context_data(**kwargs) context['goals'] = Goal.all().filter('user ='******'Found %d goals' % (context['goals'].count(),)) return context
def user(user_id): from models import User, Goal user = User.objects.get_or_404(id=user_id) goals = Goal.objects(user=user) return render_template("user/profile.html", user=user, goals=goals)
import json from app import db from models import Teacher, Goal """ """ with open("teachers.json") as f: teachers = json.load(f) with open("goals.json") as f: goals = json.load(f) for goal, name in goals.items(): goal_add = Goal(name_slug=goal, name=name[2:], name_symvol=name[0]) db.session.add(goal_add) for teacher in teachers: name = teacher["name"] about = teacher["about"] rating = float(teacher["rating"]) picture = teacher["picture"] price = int(teacher["price"]) free = json.dumps(teacher["free"]) teacher_add = Teacher(name=name, about=about, rating=rating, picture=picture, price=price, free=free) for goal in teacher["goals"]: goal_teacher = db.session.query(Goal).filter(Goal.name_slug == goal) teacher_add.goals.extend(goal_teacher) db.session.add(teacher_add)
iep4 = IEP(student_id=4, teacher_id=1, is_locked=True) iep5 = IEP(student_id=5, teacher_id=2, is_locked=True) iep6 = IEP(student_id=6, teacher_id=3, is_locked=True) iep7 = IEP(student_id=1, teacher_id=1, is_locked=True) db.session.add(iep1) db.session.add(iep2) db.session.add(iep3) db.session.add(iep4) db.session.add(iep5) db.session.add(iep6) db.session.add(iep7) db.session.commit() goal1 = Goal(iep_id=1, goal='Pay attention for 10 minutes', subject='Time on task') goal2 = Goal(iep_id=1, goal='Correct display table data', subject='Math') goal3 = Goal(iep_id=1, goal='Categorize words to demonstrate knowledge', subject='Reading') goal4 = Goal(iep_id=7, goal='Identify and follow classroom rules', subject='Social/Emotional') goal5 = Goal(iep_id=7, goal='Display knowledge of symmetry.', subject='Math') goal6 = Goal(iep_id=7, goal='Read multisyllable words', subject='Reading') # goal4 = Goal(iep_id=2, goal='Read a whole book', standard='Reading') # goal5 = Goal(iep_id=2, goal='Finish math problems', standard='Math') # goal6 = Goal(iep_id=3, goal='Finish math problems', standard='Math')
def addEditNode(node_id): node = None # get choices for node leaders leader_choices = [(0, 'Self')] for x in Node.query.filter_by(leader_id=0): # @UndefinedVariable leader_choices.append((x.id,x.name)) form = NodeForm() form.leader.choices = leader_choices form.leader.default = 0 if node_id is not None: node = Node.query.get(node_id) # @UndefinedVariable if request.method == 'GET': if node is None: form.new.data = True else: form.new.data = False form.id.data = node.id form.name.data = node.name form.rid.data = node.rid form.ip.data = node.ip form.location.lat.data = node.location.lat form.location.lon.data = node.location.lon form.leader.data = node.leader_id jumppoints = [] for jp in node.jumppoints: form.jumppoints.append_entry({"jp_id": jp.id, "lat": jp.location.lat, "lon":jp.location.lon }) goals = [] for goal in node.goals: form.goals.append_entry({"goal_id": goal.id, "lat": goal.location.lat, "lon":goal.location.lon }) elif request.method == 'POST' and form.validate(): # @UndefinedVariable if node is None: #new node has passed validation, add to db location = Location(lat=form.location.lat.data, lon=form.location.lon.data) db.session.add(location) # @UndefinedVariable node = Node(name=form.name.data, leader_id=form.leader.data, location=location, rid=form.rid.data, ip=form.ip.data) db.session.add(node) # @UndefinedVariable db.session.commit() # @UndefinedVariable for index, point in enumerate(form.jumppoints.data): jp = JumpPoint() location = Location(lat=point['lat'], lon=point['lon']) db.session.add(location) # @UndefinedVariable jp.location = location jp.position = int(point['pos']) + 1 db.session.add(jp) node.jumppoints.append(jp) for index, point in enumerate(form.goals.data): goal = Goal() location = Location(lat=point['lat'], lon=point['lon']) db.session.add(location) # @UndefinedVariable goal.location = location goal.position = int(point['pos']) + 1 db.session.add(goal) node.goals.append(goal) db.session.commit() # @UndefinedVariable flash("Node has been created") else: #node has been updated. save updates node.name = form.name.data node.rid = form.rid.data node.ip = form.ip.data location = Location.query.get(node.loc_id) # @UndefinedVariable location.lat = form.location.lat.data location.lon = form.location.lon.data node.location = location node.leader_id = form.leader.data # create a list of all points already included on this path. will be used to determine if # any points were deleted from the list. deleteList = [] for jp in node.jumppoints: deleteList.append(jp.id) for index, jp in enumerate(form.jumppoints.data): if int(jp['jp_id']) == 0: newjp = JumpPoint() location = Location(lat=jp['lat'], lon=jp['lon']) db.session.add(location) # @UndefinedVariable newjp.location = location newjp.position = int(jp['pos']) + 1 db.session.add(newjp) node.jumppoints.append(newjp) else: # found existing point. update and remove from delete list savedjp = JumpPoint.query.get(jp['jp_id']) # @UndefinedVariable savedjp.position = int(jp['pos']) + 1 savedLoc = Location.query.get(savedjp.loc_id) # @UndefinedVariable savedLoc.lat = jp['lat'] savedLoc.lon = jp['lon'] deleteList.remove(int(jp['jp_id'])) for id in deleteList: jp= JumpPoint.query.get(id) # @UndefinedVariable db.session.delete(jp) deleteList = [] for goal in node.goals: deleteList.append(goal.id) for index, goal in enumerate(form.goals.data): if int(goal['goal_id']) == 0: newgoal = Goal() location = Location(lat=goal['lat'], lon=goal['lon']) db.session.add(location) # @UndefinedVariable newgoal.location = location newgoal.position = int(goal['pos']) + 1 db.session.add(newgoal) node.goals.append(newgoal) else: # found existing point. update and remove from delete list savedGoal = Goal.query.get(goal['goal_id']) # @UndefinedVariable savedGoal.position = int(goal['pos']) + 1 savedLoc = Location.query.get(savedGoal.loc_id) # @UndefinedVariable savedLoc.lat = goal['lat'] savedLoc.lon = goal['lon'] deleteList.remove(int(goal['goal_id'])) for id in deleteList: goal= Goal.query.get(id) # @UndefinedVariable db.session.delete(goal) db.session.commit() flash("Node has been updated") # after creating the new state, redirect them back to dce config page return redirect(url_for("nodePage")) return render_template("nodeForm.html", form=form)