def scoreUpdate(self, **kw): print "-------------" print kw id = kw['id'] value = kw['value'] score = Score.get(int(id)) crit = score.criterion assessment = score.assessment category = crit.category score.value = value user = identity.current.user eh = EditHistory.selectBy(assessmentID=assessment.id, category=category) if eh.count() > 0: eh[0].editor = user.firstlast() eh[0].program = user.program.name else: EditHistory(assessmentID=assessment.id, category=category, editor=user.firstlast(), program=user.program.name) if crit.prefix in ['Y','Z']: st_crit = Criterion.selectBy(level=assessment.level, category=category, prefix="Z")[0] na_crit = Criterion.selectBy(level=assessment.level, category=category, prefix="Y")[0] possible = util.scorePossible(category, assessment.level) subtotal = Score.selectBy(criterionID=st_crit.id, assessmentID=assessment.id)[0].value na = Score.selectBy(criterionID=na_crit.id, assessmentID=assessment.id)[0].value return str(util.percent(subtotal,possible,na)) return dict()
def add_player_score(match_id, c_round, player_id, r_score): session = connectToDatabase() player_score = Score() player_score.match_id = match_id player_score.round = c_round player_score.player_id = player_id player_score.r_score = r_score session.add(player_score) session.commit() session.close()
def get_high_scores(self, request): """Returns a list of the high scores""" limit = request.number_of_results if limit and limit < 0: raise endpoints.BadRequestException( "Please request a positive number of results") if limit and limit > 0: scores = Score.query().order(-Score.score).fetch(limit=limit) else: scores = Score.query().order(-Score.score) return ScoreTable(items=[score.to_form() for score in scores])
def fillUpdate(self, **kw): assessment = Assessment.get(cherrypy.session['current_assessment']) category = cherrypy.session['current_category'] fill = kw['fill'] value = kw['values'] cherrypy.session['fill'] = fill cherrypy.session['values'] = value scores = assessment.scores criteria = Criterion.selectBy(category=category, level=assessment.level) if value == 'previous': sorted_assessments = Assessment.select(AND(Assessment.q.childID==assessment.childID, Assessment.q.id!=assessment.id), orderBy='-dateEntered') previous = sorted_assessments[0] for c in criteria: score = Score.selectBy(criterionID=c.id, assessmentID=assessment.id, type='score') if score.count() == 0: if value == 'previous': temp = Score.selectBy(criterionID=c.id, assessmentID=previous.id, type='score') if temp.count() > 0: Score(value=temp[0].value, criterionID=c.id, assessmentID=assessment.id, type='score') elif value == 'zeros': Score(value="0", criterionID=c.id, assessmentID=assessment.id, type='score') elif value == 'twos': Score(value="2", criterionID=c.id, assessmentID=assessment.id, type='score') elif score[0].value not in ['0','1','2','#'] or fill == 'all': if value == 'previous': temp = Score.selectBy(criterionID=c.id, assessmentID=previous.id, type='score') if temp.count() > 0: score[0].value = temp[0].value elif value == 'zeros': score[0].value = "0" elif value == 'twos': score[0].value = "2" user = identity.current.user eh = EditHistory.selectBy(assessmentID=assessment.id, category=category) if eh.count() > 0: eh[0].editor = user.firstlast() eh[0].program = user.program.name else: EditHistory(assessmentID=assessment.id, category=category, editor=user.firstlast(), program=user.program.name) raise redirect("/assessment")
def standings_entry(self) -> StandingsEntry: return StandingsEntry( self._team, GameStatistics(self._regulation_win_count, self._overtime_win_count, self._overtime_loss_count, self._regulation_loss_count), Score(self._goals_for, self._goals_against), self._points)
def get_user_scores(self, request): """Returns the users top 5 scores""" user = User.query(User.user_name == request.user_name).get() if not user: raise endpoints.NotFoundException("That user doesn't exist") scores = Score.query(user.key == Score.user_name).order(-Score.score) return ScoreTable(items=[score.to_form() for score in scores])
def score(): data = request.data.decode("utf-8") print("----") print(data) data = loads(data) if "user_id" not in login_session or login_session["user_id"] is not data[ "user_id"]: print(type(login_session["user_id"])) print(type(data["user_id"])) return "Forbidden", 403 current_score = db_session.query(Score) \ .filter_by(user_id=data["user_id"]) \ .filter_by(quiz_id=data["quiz_id"]) \ .first() print(current_score) if current_score == None: print('Creating new score') new_score = Score(score=data["score"], user_id=data["user_id"], quiz_id=data["quiz_id"]) db_session.add(new_score) else: print('Found current score') current_score.score = max(current_score.score, data["score"]) db_session.commit() return "OK", 200
def load_scores(): """ This function seeds the scores database table. It does this by first loading in all the airports from a file. It then calculates all the scores of each airport. Then creates a Score object containing airport code, city and score, adds it, and commits it to the database """ # Loads the 50 busiest airports from a file, with both the code and their city/state load_airports_from_file() # Calculate the FlightScores and other stats for each airport airports_and_scores = calculate_stats() # Seed the table for airport in airports_and_scores.keys(): if all_airports.get(airport): city = all_airports.get(airport) else: city = "" score = Score(airport_code=airport, city=city, score=airports_and_scores[airport][0], volume=airports_and_scores[airport][1], pct_delay=airports_and_scores[airport][2], avg_delay=airports_and_scores[airport][3]) # Add each airport to the session db.session.add(score) # Once we're done, commit all the stats to the database db.session.commit()
def deleteAssessment(self, **kw): id = int(kw['id']) try: scores = Assessment.get(id).scores for s in scores: Score.delete(s.id) Assessment.delete(id) except SQLObjectNotFound: pass if len(Child.get(cherrypy.session['current_child']).assessments) == 0: print "*****" print len(Child.get(cherrypy.session['current_child']).assessments) cherrypy.response.status = 500 return dict()
def get(self): evaluator = checkauth(self.request.headers.get('Authorization')) if evaluator is None: self.response.set_status(401) return scores = Score.query(Score.evaluator == evaluator.key) data = json.dumps([s.to_dict() for s in scores]) self.response.write(data)
def setUp(self): """ Create a validator and add one note to it. Note(delay=100, height=15, duration=100) """ self.the_note = Note(delay=100, height=15, duration=100) score = Score([self.the_note]) self.validator = Validator(score, margin=10) self.validator.add_reference_note(self.the_note)
def save_score(): business_index = int(request.form.get('business-index')) score = int(request.form.get('score')) yelphelper_session_businesses = crud.get_businesses_by_yelphelper_session_id( session['yelphelper_session_id']) business = yelphelper_session_businesses[business_index] new_score = Score(business=business, user_id=session['user_id'], yelphelper_session_id=session['yelphelper_session_id'], score=score) db.session.add(new_score) db.session.commit() return "score has been added."
def calcScore(email, loc): total_points = 0 for crit in crud.get_user(email).criteria: yelp_endpoint = yelp(crit, loc) matches = get_matches(yelp_endpoint, crit, loc) loccrit = recordLocCrit(matches, crit, loc) total_points += loccrit.points index = (total_points / crud.get_user(email).get_max_pts()) * 100 score = Score(index=index, latlong=loc.latlong, email=email) db.session.add(score) db.session.commit() return score
def test_single_note(self): a = Note(100, 15, 250) score = Score([a]) for i in [40, 99, 101, 349, 350, 341, 450]: self.assertEquals(0, len(score.starts_at(i))) self.assertEquals(1, len(score.starts_at(100))) for i in [40, 99, 100, 101, 349, 351, 450]: self.assertEquals(0, len(score.ends_at(i))) self.assertEquals(1, len(score.ends_at(350))) for i in [50, 99, 350, 351, 450]: self.assertEquals(0, len(score.sounding_at(i))) for i in [100, 101, 349]: self.assertEquals(1, len(score.sounding_at(i)))
def test_chord(self): a = Note(100, 15, 250) b = Note(100, 11, 250) c = Note(100, 18, 250) score = Score([a, b, c]) for i in [40, 99, 101, 349, 350, 351, 450]: self.assertEquals(0, len(score.starts_at(i))) self.assertEquals(3, len(score.starts_at(100))) for i in [40, 99, 100, 101, 349, 351, 450]: self.assertEquals(0, len(score.ends_at(i))) self.assertEquals(3, len(score.ends_at(350))) for i in [50, 99, 350, 351, 450]: self.assertEquals(0, len(score.sounding_at(i))) for i in [100, 101, 349]: self.assertEquals(3, len(score.sounding_at(i)))
def test_interval(self): a = Note(100, 15, 200) b = Note(200, 11, 200) c = Note(300, 18, 200) score = Score([a, b, c]) for i in [40, 99, 101, 199, 201, 299, 301, 400, 500]: self.assertEquals(0, len(score.starts_at(i))) for i in [100, 200, 300]: self.assertEquals(1, len(score.starts_at(i))) for i in [40, 99, 100, 101, 200, 201, 299, 301, 499]: self.assertEquals(0, len(score.ends_at(i))) for i in [300, 400, 500]: self.assertEquals(1, len(score.ends_at(i))) for i in [50, 99, 500]: self.assertEquals(0, len(score.sounding_at(i))) for i in [100, 101, 199, 400, 499]: self.assertEquals(1, len(score.sounding_at(i))) for i in [200, 201, 299, 300, 301, 399]: self.assertEquals(2, len(score.sounding_at(i)))
def sign_up(): ''' allows a user to signup and adds new users to the database''' # Receiving request from forms with username and password # With more time, I would spend more time on form validation to prevent security risks new_username = request.form["SignUpInputEmail"].lower() new_password = request.form["SignUpPassword"] confirm_password = request.form["ConfirmInputPassword"] # checks if user is already an existing user to prevent duplicate usernames before adding name to database existing_user = User.query.filter_by(username=new_username).first() # Checks if password matches confirmatory password # If password matches confirmatory password and user is not an existing user, the new user is saved to the db so that they can log in. # In the future, I plan to use password encryption, validation, and set password requirements to increase security if new_password == confirm_password and not existing_user: new_user = User(username = new_username, password=new_password) db.session.add(new_user) db.session.commit() # adds user information directly to session, and instantiates a new word game which is added to session. session["user_id"] = new_user.user_id session["name"] = new_user.username # Creates a session with a default difficulty level of '1' # a new game is added to the database session["difficulty_level"] = "1" word_game = Game(session["difficulty_level"]) new_game = Score(date=datetime.now(), user_id=int(session['user_id']), word=word_game.get_word(), score=word_game.get_score(), won=word_game.win(), game_information=word_game.stringify_attributes(), completed=False) db.session.add(new_game) db.session.commit() session["game_id"] = new_game.score_id # User is forwarded to play game return redirect("/play") # checks to make sure passwords match elif new_password != confirm_password: flash("Passwords do not match") return redirect("/") # if user already exists, triggered to create a new account else: flash("User Already Exists. Please create a new username") return redirect("/")
def upsert_score(recipe_id, user_id, score): # -- TESTED """Add/update score based on recipe and user_id.""" user_score = get_score(recipe_id, user_id) if user_score: # update in database user_score.score = score user_score.rated_at = datetime.now() # Else else: # Add new score row to database new_score = Score(rated_at=datetime.now(), score=int(score), user_id=user_id, recipe_id=recipe_id) db.session.add(new_score) db.session.commit()
def example_data(): ''' creates some example data to test models''' # sample game players player1 = User(username="******", password="******") player2 = User(username="******", password="******") player3 = User(username="******", password="******") player4 = User(username="******", password="******") player5 = User(username="******", password="******") # sample games score1 = Score(user=player1, date=datetime.now(), score=0, word="arduous", won=True, completed=False, game_information='{"word": "arduous", "correct_guessed_letters": ["a"], "incorrect_guessed_letters": ["i"], "incorrect_guesses": 1, "max_incorrect_guesses": 6, "incorrect_words_guessed": ["ambient"]}') score2 = Score(user=player1, date=datetime.now(), score=0, word="joyful", won=False, completed=False, game_information='{"word": "joyful", "correct_guessed_letters": ["j"], "incorrect_guessed_letters": ["z", "e", "i", "p", "s"], "incorrect_guesses": 5, "max_incorrect_guesses": 6, "incorrect_words_guessed": []}') score3 = Score(user=player1, date=datetime.now(), score=150, word="success", won=True, completed=True, game_information='{"word": "success", "correct_guessed_letters": ["s", "u", "c", "e"], "incorrect_guessed_letters": ["a"], "incorrect_guesses": 1, "max_incorrect_guesses": 6, "incorrect_words_guessed": []}') score4 = Score(user=player2, date=datetime.now(), score=0, word="tedious", won=False, completed=False, game_information='{"word": "tedious", "correct_guessed_letters": ["t", "e"], "incorrect_guessed_letters": ["s", "a"], "incorrect_guesses": 2, "max_incorrect_guesses": 6, "incorrect_words_guessed": []}') score5 = Score(user=player2, date=datetime.now(), score=0, word="alacrity", won=False, completed=False, game_information='{"word": "alacrity", "correct_guessed_letters": ["a", "i"], "incorrect_guessed_letters": ["s", "e"], "incorrect_guesses": 2, "max_incorrect_guesses": 6, "incorrect_words_guessed": []}') score6 = Score(user=player3, date=datetime.now(), score=0, word="crystal", won=False, completed=False, game_information='{"word": "crystal", "correct_guessed_letters": ["c", "a", "l"], "incorrect_guessed_letters": ["i", "e", "o", "p", "w"], "incorrect_guesses": 5, "max_incorrect_guesses": 6, "incorrect_words_guessed": []}') score7 = Score(user=player3, date=datetime.now(), score=0, word="um", won=False, completed=True, game_information='{"word": "um", "correct_guessed_letters": [], "incorrect_guessed_letters": ["i", "e", "o", "p", "w", "d"], "incorrect_guesses": 6, "max_incorrect_guesses": 6, "incorrect_words_guessed": []}') score8 = Score(user=player5, date=datetime.now(), score=0, word="grit", won=False, completed=False, game_information='{"word": "grit", "correct_guessed_letters": ["g", "r", "t"], "incorrect_guessed_letters": ["e"], "incorrect_guesses": 1, "max_incorrect_guesses": 6, "incorrect_words_guessed": []}') score9 = Score(user=player5, date=datetime.now(), score=200, word="", won=True, completed=True, game_information='{"word": "resilience", "correct_guessed_letters": ["r", "e", "s", "i", "l", "n", "c"], "incorrect_guessed_letters": ["w", "z", "y", "m"], "incorrect_guesses": 4, "max_incorrect_guesses": 6, "incorrect_words_guessed": []}') players = [player1, player2, player3, player4, player5] scores = [score1, score2, score3, score4, score5, score6, score7, score8, score9] db.session.add_all(players) db.session.add_all(scores) db.session.commit()
def SSVParse(filename, resolution): """ Parse a SSV (?). Resolution must be integer. """ g = open(filename) notes = [] playing = [None] * 128 for line in g: parts = line.split() delay = int(float(parts[0]) * 1000) / resolution * resolution height = int(parts[1]) speed = int(parts[2]) if speed > 0: playing[height] = delay else: if playing[height] is not None: note = Note(playing[height], height, delay - playing[height]) notes.append(note) return Score(notes)
def obj_building(path): def filter_year(item): years = ["2021", "2020"] result = False if item['event_date'][:4] in years: result = True return result TEAMS = [] teams = {} for x in root["teams"]: data = json.loads(x) teams[data["team_id"]] = data for team_id in root['fixture']: # breakpoint() fixtures = root["fixture"][team_id] team = teams[team_id] pyteam = PyTeam(team["team_id"], team["name"], team["country"]) fixtures = filter(filter_year, fixtures) for fixture in fixtures: params = ( fixture['fixture_id'], fixture['status'], Score(*(*fixture['score'].values(), )).__dict__, TeamFixture(*(*fixture['homeTeam'].values(), )).__dict__, TeamFixture(*(*fixture['awayTeam'].values(), )).__dict__, fixture['goalsHomeTeam'], fixture['goalsAwayTeam'], ) pyfixture = PyFixture(*params) pyteam.fixtures.append(pyfixture._asdict()) # breakpoint() TEAMS.append(pyteam.__dict__) zopedb.cacheMinimize() log.info("Team: {}".format(team["name"])) # breakpoint() with open(path, "wb") as f: pickle.dump(TEAMS, f)
def log_in(): ''' allows a user to login to play the game by checking login credentials ''' # Receiving request from browser with form information # with more time, I would spend more time on form validation to prevent security threats # request.form returns an immutable MultiDict(). Used form.to_dict() to convert MultiDict() to dictionary request_info = request.form.to_dict() entered_username = request_info['InputUsername'] entered_password = request_info['InputPassword'] existing_user = User.query.filter(User.username==entered_username).first() # checks to make sure user exists in database if not existing_user: flash("Username does not exist. Please sign up or check your spelling") return redirect("/") # if user exists, checks password, to make sure it matches password found in database # if so, logs user into the game. # a new game is added to the database else: if existing_user.password == entered_password: session["user_id"] = existing_user.user_id session["name"] = existing_user.username session["difficulty_level"] = "1" word_game = Game(session["difficulty_level"]) new_game = Score(date=datetime.now(), user_id=int(session['user_id']), word=word_game.get_word(), score=word_game.get_score(), won=word_game.win(), game_information=word_game.stringify_attributes(), completed=False) db.session.add(new_game) db.session.commit() session["game_id"] = new_game.score_id # when user logs in, flashes a message that they have successfully logged in (see html templating) flash("you have successfully logged in") return redirect("/play") # if passwords do not match, user is redirected home, and flashed a message to try again else: flash("Password Incorrect. Please try again") return redirect("/")
def play_again(): ''' a route that responds to an AJAX call from the browser to refresh the word ''' # Checks if user changed the difficulty level. Returns None if the user has not changed the difficutly level. new_difficulty_level = request.args.get('difficulty-level') # If the user changed the difficulty level, instantiates a new game with the new difficutly level as an argument. # finds the user in the dictionary using the key user_id from the session, and replaces it with the new word if new_difficulty_level: session['difficulty_level'] = new_difficulty_level word_game = Game(session["difficulty_level"]) new_game = Score(date=datetime.now(), user_id=int(session['user_id']), word=word_game.get_word(), score=word_game.get_score(), won=word_game.win(), game_information=word_game.stringify_attributes(), completed=False) db.session.add(new_game) db.session.commit() session["game_id"] = new_game.score_id # Gets the length of the word and remaining guesses to send to browser to modify DOM for new word length_word = word_game.get_word_length() remaining_guesses = word_game.guesses_left() return jsonify({"word_length": length_word, "remaining_guesses":remaining_guesses, "difficulty_level": session['difficulty_level']})
def search_reddit(subreddit="france", limit=100, category=HOT): """ Connect to reddit and gather posts from a subreddit. Note: Can be quite long (few minutes to run with limit=100) so cache it with save_data. Args: subreddit (:obj:`str`, optional): A string that designate an existing subreddit. Default is "france". limit (:obj:`int`, optional): Number of reddit posts to retrieve. Default is 100. category (:obj:`int`, optional): Either HOT or TOP. Those constants are defined in model.py. They determine if you gather post from the TOP (best posts ever) or HOT (newest posts) category. Default is HOT. Returns: :obj:`dict`: Return a dict of posts gathered. With key being the id of the post and value being the posts themselves. """ user_agent = "Natural Language Processing:v0.1.0 (by /u/lughaidhdev)" reddit = praw.Reddit(user_agent=user_agent) subreddit_obj = reddit.get_subreddit(subreddit) posts = None if category == HOT: posts = subreddit_obj.get_hot(limit=limit) elif category == TOP: posts = subreddit_obj.get_top(limit=limit) else: print("ERROR: category must be either HOT or TOP, not ", category) return {} word_count = Counter() my_posts = {} for post in posts: thread = post.comments tmp_post = Post(id=post.id, title=post.title, author=post.author.name, comments=[], score=Score(total=post.score, ups=post.ups, downs=post.downs)) for comment in thread: if isinstance(comment, praw.objects.MoreComments): pass else: if comment.body == "[deleted]" or comment.body == "[removed]": pass else: cleancomment = clean_comment(comment.body) word_count.update(cleancomment) tmp_comment = Comment(id=comment.id, content=comment.body, clean_content=cleancomment, author=comment.author.name, score=Score(total=comment.score, ups=comment.ups, downs=comment.downs)) tmp_post.comments.insert(0, tmp_comment) my_posts[post.id] = tmp_post words_count_update(word_count) return my_posts
elif isinstance(o, db.Model): d = db.to_dict(o) k = o.key() d["__key__"] = str(k) d["__id__"] = k.id() d["__name__"] = k.name() return d elif isinstance(o, (datetime, date, time)): # ISO 8601 time, UTC timezone return (o).isoformat('T') + 'Z' remote_api_stub.ConfigureRemoteApi(None, REMOTE_API_PATH, auth_func, APP_DOMAIN) scores_query = Score.all().order("-date") #scores_query = SecretSalt.all() cursor = None batch_has_result = True # TODO: This isn't terminating when finished while batch_has_result: if cursor: scores_query = Score.all().order("-date").with_cursor(cursor) #scores_query = SecretSalt.all().with_cursor(cursor) batch_has_result = False for score in scores_query.run(limit=1000, batch_size=1000): batch_has_result = True # print db.to_dict(score)
d["__name__"] = k.name() return d elif isinstance(o, db.Model): d = db.to_dict(o) k = o.key() d["__key__"] = str(k) d["__id__"] = k.id() d["__name__"] = k.name() return d elif isinstance(o, (datetime, date, time)): # ISO 8601 time, UTC timezone return (o).isoformat('T')+'Z' remote_api_stub.ConfigureRemoteApi(None, REMOTE_API_PATH, auth_func, APP_DOMAIN) scores_query = Score.all().order("-date") #scores_query = SecretSalt.all() cursor = None batch_has_result = True # TODO: This isn't terminating when finished while batch_has_result: if cursor: scores_query = Score.all().order("-date").with_cursor(cursor) #scores_query = SecretSalt.all().with_cursor(cursor) batch_has_result = False for score in scores_query.run(limit=1000, batch_size=1000): batch_has_result = True # print db.to_dict(score)
def index2(self, id=None, category=None, osep='None', print_area='false'): if not identity.current.user.basketmode: raise redirect(url("index1",id=id,category=category,osep=osep,print_area=print_area)) osep = True if print_area == 'true': print_area = True else: print_area = False id = util.session('current_assessment', 0, id) child = util.session('current_child', 0) if id == 0: # no id given raise redirect("/") try: current_assessment = Assessment.get(id) except SQLObjectNotFound: # Child with given id does not exist raise redirect("/") current_child = current_assessment.child all_assessments = current_child.assessments sorted_assessments = Assessment.select(AND(Assessment.q.childID==current_assessment.childID, Assessment.q.id!=id, Assessment.q.level==current_assessment.level), orderBy='-dateEntered') old = list(sorted_assessments[:7]) categories = self.category_list data = {} for c in categories: cdata = {} subtotal = Criterion.selectBy(category=c, level=current_assessment.level, prefix='Z')[0] _na = Criterion.selectBy(category=c, level=current_assessment.level, prefix='Y')[0] cdata['subtotal'] = subtotal cdata['na'] = _na oldtotals = {} oldna = {} percents = {} for t in old: stscore = Score.selectBy(assessmentID=t.id, criterionID=subtotal.id) if stscore.count() > 0: stscore = stscore[0] else: stscore = Score(assessmentID=t.id, criterionID=subtotal.id, value="0", type='subtotal') oldtotals[t.id] = stscore.value nascore = Score.selectBy(assessmentID=t.id, criterionID=_na.id) if nascore.count() > 0: nascore = nascore[0] else: nascore = Score(assessmentID=t.id, criterionID=_na.id, value="0", type='na') oldna[t.id] = nascore.value percents[t.id] = util.percent(stscore.value, util.scorePossible(c, current_assessment.level), nascore.value) cdata['oldtotals'] = oldtotals cdata['oldna'] = oldna cdata['percents'] = percents stscore = Score.selectBy(assessmentID=id, criterionID=subtotal.id) nascore = Score.selectBy(assessmentID=id, criterionID=_na.id) if stscore.count() > 0: stscore = stscore[0] else: stscore = Score(assessmentID=id, criterionID=subtotal.id, value="0", type='subtotal') if nascore.count() > 0: nascore = nascore[0] else: nascore = Score(assessmentID=id, criterionID=_na.id, value="0", type='na') percent = util.percent(stscore.value, util.scorePossible(c, current_assessment.level), nascore.value) cdata['stscore'] = stscore cdata['nascore'] = nascore cdata['percent'] = percent data[c] = cdata baskets = [] for i in [1,2,3]: bdata = {} prefix = "B" + str(i) b = Criterion.selectBy(level=current_assessment.level, prefix=prefix)[0] oldb = {} for t in old: bscore = Score.selectBy(assessmentID=t.id, criterionID=b.id) if bscore.count() > 0: bscore = bscore[0] else: bscore = Score(assessmentID=t.id, criterionID=b.id, value="0", type='basket') oldb[t.id] = bscore bdata['old'] = oldb bscore = Score.selectBy(assessmentID=id, criterionID=b.id) if bscore.count() > 0: bscore = bscore[0] else: bscore = Score(assessmentID=id, criterionID=b.id, value="0", type='basket') bdata['val'] = bscore baskets.append(bdata) return dict(child=current_child, id=id, a=current_assessment, old=old, categories=categories, \ print_area=print_area, getEditor=self.getEditor, pcheck=self.persistCheck, \ shaded=util.shaded, scoreclass=util.color, scorePossible=util.scorePossible, \ data=data, baskets=baskets)
def index1(self, id=None, category=None, osep='None', print_area='false'): if identity.current.user.basketmode: raise redirect(url("index2",id=id,category=category,osep=osep,print_area=print_area)) osep = True if print_area == 'true': print_area = True else: print_area = False id = util.session('current_assessment', 0, id) category = util.session('current_category', 'Fine Motor', category) osep = util.session('osep', False, osep) child = util.session('current_child', 0) if id == 0: # no id given raise redirect("/") try: current_assessment = Assessment.get(id) except SQLObjectNotFound: # Child with given id does not exist raise redirect("/") current_child = current_assessment.child all_assessments = current_child.assessments sorted_assessments = Assessment.select(AND(Assessment.q.childID==current_assessment.childID, Assessment.q.id!=id, Assessment.q.level==current_assessment.level), orderBy='-dateEntered') old = list(sorted_assessments[:7]) if osep: criteria = Criterion.selectBy(category=category, level=current_assessment.level, osep=True) else: criteria = Criterion.selectBy(category=category, level=current_assessment.level) criteria = criteria.orderBy('sort_order') crit_ids = [c.id for c in criteria] sums = {} for t in old: sum = 0; for s in t.scores: if s.criterionID in crit_ids and s.criterion.rank != "1": try: sum += int(s.value) except: pass sums[t.id] = sum sum = 0; for s in current_assessment.scores: if s.criterionID in crit_ids and s.criterion.rank != "1": try: sum += int(s.value) except: pass sums[current_assessment.id] = sum util.session('fill', 'missing') if len(old) == 0: temp = util.session('values', 'zeros') if temp == 'previous': cherrypy.session['values'] = 'zeros' else: util.session('values', 'previous') subtotal = Criterion.selectBy(category=category, level=current_assessment.level, prefix='Z')[0] _na = Criterion.selectBy(category=category, level=current_assessment.level, prefix='Y')[0] oldtotals = {} oldna = {} percents = {} for t in old: stscore = Score.selectBy(assessmentID=t.id, criterionID=subtotal.id) if stscore.count() > 0: stscore = stscore[0] else: stscore = Score(assessmentID=t.id, criterionID=subtotal.id, value="0", type='subtotal') oldtotals[t.id] = stscore.value nascore = Score.selectBy(assessmentID=t.id, criterionID=_na.id) if nascore.count() > 0: nascore = nascore[0] else: nascore = Score(assessmentID=t.id, criterionID=_na.id, value="0", type='na') oldna[t.id] = nascore.value percents[t.id] = util.percent(stscore.value, util.scorePossible(category, current_assessment.level), nascore.value) stscore = Score.selectBy(assessmentID=id, criterionID=subtotal.id) nascore = Score.selectBy(assessmentID=id, criterionID=_na.id) if stscore.count() > 0: stscore = stscore[0] else: stscore = Score(assessmentID=id, criterionID=subtotal.id, value="0", type='subtotal') if nascore.count() > 0: nascore = nascore[0] else: nascore = Score(assessmentID=id, criterionID=_na.id, value="0", type='na') percent = util.percent(stscore.value, util.scorePossible(category, current_assessment.level), nascore.value) return dict(child=current_child, id=id, a=current_assessment, old=old, oldtotals=oldtotals, \ stc=subtotal, subtotal=stscore, criteria=criteria, osep=osep, sums=sums, \ catlist=self.category_list, category=category, nextCategory=self.nextCategory, \ print_area=print_area, getEditor=self.getEditor, pcheck=self.persistCheck, \ shaded=util.shaded, scoreclass=util.color, scorePossible=util.scorePossible, \ nac=_na, na=nascore, oldna=oldna, percents=percents, percent=percent)
def test_shift(self): a = Note(100, 15, 250) shift = 100 score = Score([copy(a)]) score.shift_all_notes(shift) for i in [140, 199, 201, 449, 450, 451, 550]: self.assertEquals(0, len(score.starts_at(i))) self.assertEquals(1, len(score.starts_at(200))) for i in [140, 199, 200, 201, 449, 451, 550]: self.assertEquals(0, len(score.ends_at(i))) self.assertEquals(1, len(score.ends_at(450))) for i in [150, 199, 450, 451, 550]: self.assertEquals(0, len(score.sounding_at(i))) for i in [200, 201, 449]: self.assertEquals(1, len(score.sounding_at(i))) notes = score.starts_at(200) for n in notes: self.assertEquals(n.delay, a.delay + shift)
'--view', action='store', choices=VIEWS, default="cocos", help='select view (default: %(default)s)') args = parser.parse_args() # user_input if args.midi: user_input = USER_INPUTS[args.input](args.midi) else: user_input = USER_INPUTS[args.input]() # reference input if args.reftype == "none": score = Score([]) elif args.reftype == "midi": composition = MidiFileIn.MIDI_to_Composition(args.file) score = Score.from_track(composition[0].tracks[args.track], bpm=args.bpm) elif args.reftype == "ssv": score = SSVParse(args.file, 50) score.shift_all_notes(1000) # audio if args.audio == "none": sequencer = DummySequencer(score) elif args.audio: sequencer = FluidSynthSequencer(score) fluidsynth.init(args.soundfont, args.audio)
def get(self): scores = Score.query() data = [s.to_dict() for s in scores] self.response.write(json.dumps(data))
def put(self, presenter_key): presenter_key = ndb.Key(Presenter, int(presenter_key)) evaluator = checkauth(self.request.headers.get('Authorization')) if evaluator is None: self.response.set_status(401) return data = json.loads(self.request.body) score = Score.query(Score.evaluator == evaluator.key, Score.presenter == presenter_key).get() if score is None: score = Score() score.evaluator = evaluator.key score.presenter = presenter_key score.score1 = int(data.get('score1')) score.score2 = int(data.get('score2')) score.score3 = int(data.get('score3')) score.comment = data.get('comment') score.put() self.response.write(json.dumps(score.to_dict()))