def test_init_invalid_name_score(): """ 1001- Test if type of score name is a valid- a string""" with pytest.raises(ValueError): Score(100, 55) with pytest.raises(ValueError): Score('', 55) with pytest.raises(ValueError): Score('valid', '55')
def test_over_all_acc(self): sc = Score(tags) sc.fit(y, y) cm = sc.over_all_acc() self.assertEqual(cm, 1.) print(cm) sc = Score(tags) sc.fit(y, y_bad) cm = sc.over_all_acc() self.assertNotEqual(cm, 1.) print(cm)
def test_matrix_confusion(self): sc = Score(tags) sc.fit(y, y) cm = sc.matrix_confusion() print(cm) sc = Score(tags) sc.fit(y, y_bad) cm2 = sc.matrix_confusion() print(cm2) eq = np.min(np.min(cm == cm2)) self.assertEqual(eq, 0) same_amount = np.min(cm.sum() == cm2.sum()) self.assertEqual(same_amount, 1)
def test_adding_review_and_comment_to_proposal_in_database(database): """A reviewed proposal has a score and possible a comment added. Put a proposal with user and presenter into the database. Although this is not allowed in the application have the user score and comment on their proposal to show that this all works in the database. """ user = User(**user_data) proposal = Proposal(user, **proposal_data) presenter = Presenter(**presenter_data) ProposalPresenter(proposal, presenter, True) score = Score(proposal, user, 10) comment = Comment(proposal, user, 'Perfect') database.session.add(user) database.session.add(proposal) database.session.add(presenter) database.session.add(score) database.session.add(comment) database.session.commit() query_result = Proposal.query.filter_by(proposer=user).all() assert len(query_result) == 1 proposal = query_result[0] assert proposal.scores is not None assert len(proposal.scores) == 1 assert proposal.scores[0].score == 10 assert proposal.comments is not None assert len(proposal.comments) == 1 assert proposal.comments[0].comment == 'Perfect'
def confusion(self, y_hat, y): """ :param y_hat: :type y_hat: :param y: :type y: :return: :rtype: """ assert isinstance(y_hat, pd.Series) assert isinstance(y, pd.Series) a = y.values.reshape(-1) b = pd.Series(a) # c = b.drop(['<PAD>', '*', '<STOP>', ',']) # print(c) roll_y = pd.Series( y.values.reshape(-1)) #.drop(['<PAD>', '*', '<STOP>', ',']) roll_y_hat = pd.Series( y_hat.values.reshape(-1)) #.drop(['<PAD>', '*', '<STOP>', ',']) most_reacuent_tags = self.tag_corpus[2:12] sc = Score(most_reacuent_tags) sc.fit(roll_y, roll_y_hat) return sc.matrix_confusion()
def checking(): data = get_request_data(request, cls=LoyalityJSONDecoder) host_uid = get_current_host_id() if not host_uid: return jsonify({'message': "You need to be a staff"}), HTTP_403_FORBIDDEN user_uid = data.get('user_id') if not user_uid: return jsonify({'message': "No user_id provided"}), HTTP_400_BAD_REQUEST score_update = data['score'] if data.get('score') else None if not score_update or not (isinstance(score_update, int) or isinstance(score_update, float)): return jsonify({'message': "Score value is invalid"}), HTTP_400_BAD_REQUEST host = Host(uid=host_uid) if host.uid is None: return jsonify({'message': "No such host"}), HTTP_404_NOT_FOUND if not host.check_loyality(host.loyality_type, host.loyality_param, host.loyality_time_param, host.loyality_burn_param): return jsonify({ 'code': 2, 'message': "Loyality of the host is not set" }) if current_user.uid not in host.staff_uids: return jsonify({'message': "You are not a staff of this place" }), HTTP_403_FORBIDDEN user = User(uid=user_uid) if user.login is None: return jsonify({'message': "No such user"}), HTTP_404_NOT_FOUND score = Score(host.uid, user.uid) return f(host, user, score, score_update)
def test_constructor_invalid_incorrectvalue(): """ test that a ValueError is raised """ try: with pytest.raises(ValueError): player = Score(-100) except: assert False
def update_score(user_id, obj_id, score): obj = ObjectiveModel.query.get(obj_id) user = models.user.User.query.get(user_id) score_obj = Score.query.filter_by(user_id=user.id, objective_id=obj.id).first() if score_obj: score_obj.update(score) else: json = {"user": user, "objective": obj, "score": score} score_obj = Score(json) score_obj.create() return jsonify({'result': score_obj.to_json()}), 201
def get_host(): host_id = get_request_data(request).get('host_id') if not host_id: return jsonify({'message': "No host id provided"}), HTTP_400_BAD_REQUEST host = Host(uid=host_id) # 404 if there is a host with no title in db. No unnamed hosts allowed. response = host.to_dict() if response is None: return jsonify({'message': "No such host in db"}), HTTP_404_NOT_FOUND score = Score(host_id, session['user_id']) response.update({'score': score.score}) return jsonify(response)
def acc_per_tag(self, y_hat, y): assert isinstance(y_hat, pd.Series) assert isinstance(y, pd.Series) roll_y = pd.Series(y.values.reshape(-1)).drop( ['<PAD>', '*', '<STOP>', ',']) roll_y_hat = pd.Series(y_hat.values.reshape(-1)).drop( ['<PAD>', '*', '<STOP>', ',']) most_reacuent_tags = self.tag_corpus[:10] sc = Score(most_reacuent_tags) sc.fit(roll_y, roll_y_hat) return sc.acc_per_tag(roll_y, roll_y_hat)
def get_client_score(): data = get_request_data(request) client_id = data.get('client_id') if client_id is None: return jsonify({'message': "client_id required"}), HTTP_400_BAD_REQUEST host_id = session.get('host_id') if host_id is None: return jsonify({'message': "Please login as a staff"}), HTTP_403_FORBIDDEN score = Score(host_id, client_id).score if score is None: return jsonify({'message': "No host with this id"}), HTTP_404_NOT_FOUND return jsonify({'code': 0, 'points': score})
def match_pair(cls, game, pair_1, pair_2): """Match a pair and update game state""" game.attempts += 1 game.put() card_1 = Card.query(Card.game == game.key).filter(Card.index == pair_1).get() card_2 = Card.query(Card.game == game.key).filter(Card.index == pair_2).get() if card_1.matched or card_2.matched: raise RuntimeError('Could not rematch a matched card') form = MatchResultForm() if card_1.value == card_2.value: card_1.matched = True card_1.put() card_2.matched = True card_2.put() game.matched += 2 game.put() form.message = 'Success' else: form.message = 'Fail' # Construct return info form form.card_1 = card_1.to_form() form.card_2 = card_2.to_form() form.matched_count = game.matched if game.matched == 52: game.game_over = True game.put() Card.delete_cards_for_game(game) # Update average attempts of user user = game.user.get() games = Game.get_user_finished_games(user) count = len(games) if user.average_attempts == float('inf'): user.average_attempts = 0 user.average_attempts = ((count - 1) * user.average_attempts + game.attempts) / count user.put() score = Score(user=game.user, date=date.today(), attempts=game.attempts) score.put() form.message = 'Win' # Create history log History.create_history(game=game, card_1=card_1, card_2=card_2, message=form.message) return form
def post(self): args = Dict(parser.parse_args()) new_score = Score(name=args.name, score=args.score, added_time=datetime.now()) new_score.save() return { 'success': 1, 'message': 'New score added successfully', 'data': { 'score': new_score.score, 'name': new_score.name } }
def from_json(self): """ reads data from a json file and creates instance of score to add to instance of score manager :param json_file: json file :type json_file: JSON """ # Opening JSON file with open("models/scores.json", 'r') as openfile: # Reading from json file json_object = json.load(openfile) count = 0 for obj in json_object['scores']: name = obj['name'] score = Score(obj['score'], obj['name']) self.add_score(score)
def end_game(self, won=False): """Ends the game - if won is True, the player won. - if won is False, the player lost. Creates a Score object and stores it in the datastore. Args: won: Indicates whether the player wins or loses. """ self.game_over = True self.put() # Add the game to the score 'board' score = Score(user=self.user, date=date.today(), won=won, attempts_used=self.attempts - self.attempts_remaining, attempts=self.attempts) score.put()
def test_all_data(self): data = PreprocessTags().load_data(r'..\data\test.wtag') y_hat = data.y y = data.y roll_y = pd.Series(y.values.reshape(-1)) roll_y_hat = pd.Series(y_hat.values.reshape(-1)) index = pd.value_counts(y.values.reshape(-1)).index most_reacuent_tags = pd.Series(index, index=index).drop(['<STOP>', '*'])[:10] sc = Score(most_reacuent_tags) sc.fit(roll_y, roll_y_hat) cm = sc.matrix_confusion() acc_dict = sc.acc_per_tag(y, y_hat) print(acc_dict) print(cm)
def _save_scores(self, week, scores): query = Score.all() scorebox = {} result = {} query.filter('week =', week) result = query.fetch(25) if len(result) <= 0: # Completely new save for game in scores: scorebox = Score( year=self.get_season_year(), week=week, away_name=game[AWAY_NAME].encode('ascii', 'ignore'), away_score=int(game[AWAY_SCORE]), game_clock=str(game[GAME_CLOCK]), game_day=game[GAME_DAY].encode('ascii', 'ignore'), game_id=int(game[GAME_ID]), game_status=game[GAME_STATUS], game_time=game[GAME_TIME], home_name=game[HOME_NAME].encode('ascii', 'ignore'), home_score=int(game[HOME_SCORE]), timestamp=datetime.datetime.now()) scorebox.put() else: current = {} for scorebox in result: # Find the related game score for game in scores: if game[AWAY_NAME] == scorebox.away_name: current = game break key = scorebox.key() matchup = Score.get(key) # Update matchup.away_score = int(current[AWAY_SCORE]) matchup.home_score = int(current[HOME_SCORE]) matchup.game_clock = str(current[GAME_CLOCK]) matchup.game_status = current[GAME_STATUS] matchup.timestamp = datetime.datetime.now() #Push update matchup.put()
def end_game(self, won=False): """Ends the game. Args: won: if won is True, the player won, else the player lost.""" self.game_over = True user = self.user.get() if won: user.games_won += 1 # Add the game to the score 'board' score = Score(user=self.user, date=date.today(), won=won, harvest=self.plant.get().flowers) score.put() user.put() self.put()
def test_already_reviewed(registrant, proposal_single_presenter, proposal_multiple_presenters_single_lead): reviewer = User(**new_user) proposer = User(**registrant) proposals = (Proposal( proposer, proposal_single_presenter['title'], proposal_single_presenter['session_type'], proposal_single_presenter['summary'], ), Proposal( proposer, proposal_multiple_presenters_single_lead['title'], proposal_multiple_presenters_single_lead['session_type'], proposal_multiple_presenters_single_lead['summary'], )) assert not already_reviewed(proposals[0], reviewer) assert not already_reviewed(proposals[1], reviewer) score = Score(proposals[1], reviewer, 7) assert not already_reviewed(proposals[0], reviewer) assert already_reviewed(proposals[1], reviewer)
def post(self): # 1. Get data from json body json_score = request.get_json() name = json_score["name"] # dictionary score = json_score["score"] added_time = datetime.now() # 2. Add name, score into database new_score = Score() new_score.name = name new_score.score = score new_score.added_time = added_time new_score.save() return { 'success': 1, 'data': { 'name': new_score.name, 'score': new_score.score } }
def accuracy(self, y_hat, y): """ :param x: :type x: :param y: :type y: :return: :rtype: """ assert isinstance(y_hat, pd.Series) assert isinstance(y, pd.Series) roll_y = pd.Series(y.values.reshape(-1)).drop( ['<PAD>', '*', '<STOP>', ',']) roll_y_hat = pd.Series(y_hat.values.reshape(-1)).drop( ['<PAD>', '*', '<STOP>', ',']) most_reacuent_tags = self.tag_corpus[:10] sc = Score(most_reacuent_tags) sc.fit(roll_y, roll_y_hat) return sc.over_all_acc()
def bad_score(): """This is another sample of a valid score""" return Score('Bad', 0)
def review_proposal(id): check = is_acceptable_route() if not check[0]: return check[1] assert check[1] is None if is_logged_in(): reviewer = User.query.filter_by(email=session['email']).first() if request.method == 'POST': review_data = request.json if not reviewer: response = jsonify( 'Logged in person is not a reviewer. This cannot happen.') response.status_code = 400 return response proposal = Proposal.query.filter_by(id=id).first() if not proposal: response = jsonify( 'Proposal cannot be found. This cannot happen.') response.status_code = 400 return response # TODO Is this the right way of doing this? score = Score.query.filter_by(proposal=proposal, scorer=reviewer).all() if score: assert len(score) == 1 score[0].score = review_data['score'] else: db.session.add(Score(proposal, reviewer, review_data['score'])) if review_data['comment_for_proposer']: comment = CommentForProposer.query.filter_by( proposal=proposal, commenter=reviewer).all() if comment: comment[0].comment = review_data['comment_for_proposer'] else: db.session.add( CommentForProposer( proposal, reviewer, review_data['comment_for_proposer'])) if review_data['comment_for_committee']: comment = CommentForCommittee.query.filter_by( proposal=proposal, commenter=reviewer).all() if comment: comment[0].comment = review_data['comment_for_committee'] else: db.session.add( CommentForCommittee( proposal, reviewer, review_data['comment_for_committee'])) db.session.commit() return jsonify('Review stored.') if not reviewer: return render_template( '/general.html', page=md( base_page, { 'pagetitle': 'Review Proposal Failed', 'data': 'Logged in user is not a registered user. This cannot happen.', })) if reviewer.role != Role.reviewer: return render_template( '/general.html', page=md( base_page, { 'pagetitle': 'Review Proposal Failed', 'data': 'Logged in user is not a registered reviewer.', })) number_of_proposals = Proposal.query.count() if not (1 <= id <= number_of_proposals): return render_template( 'general.html', page=md( base_page, { 'pagetitle': 'Review Proposal Failed', 'data': 'Requested proposal does not exist.', })) proposal = Proposal.query.filter_by(id=id).first() presenters = [{ 'name': p.name, 'bio': p.bio } for p in proposal.presenters] score = '' comment_for_proposer = '' comment_for_committee = '' if already_reviewed(proposal, reviewer): scores = [s for s in reviewer.scores if s.proposal == proposal] assert len(scores) == 1 score = scores[0].score comments_for_proposer = [ c for c in reviewer.comments_for_proposer if c.proposal == proposal ] if comments_for_proposer: comment_for_proposer = comments_for_proposer[0].comment comments_for_committee = [ c for c in reviewer.comments_for_committee if c.proposal == proposal ] if comments_for_committee: comment_for_committee = comments_for_committee[0].comment has_next = id < number_of_proposals if has_next: for i in range(id + 1, number_of_proposals + 1): if not _reviewer_is_in_proposal_index(reviewer, i): break else: has_next = False has_previous = id > 1 if has_previous: for i in range(id - 1, 0, -1): if not _reviewer_is_in_proposal_index(reviewer, i): break else: has_previous = False return render_template( '/review_proposal.html', page=md( base_page, { 'pagetitle': 'Proposal to Review', 'data': 'There is no specific "do nothing" button, to not do anything simply navigate away from this page.', 'proposal_id': id, 'title': proposal.title, 'summary': proposal.summary, 'session_type': sessiontype_descriptions[proposal.session_type], 'audience': proposal.audience.value, 'notes': proposal.notes, 'presenters': presenters, 'button_label': 'Submit' if not score else 'Update', 'score': score, 'comment_for_proposer': comment_for_proposer, 'comment_for_committee': comment_for_committee, 'has_previous': has_previous, 'has_next': has_next, })) return render_template( 'general.html', page=md( base_page, { 'pagetitle': 'Review Proposal Failed', 'data': 'You must be registered, logged in, and a reviewer to review a proposal', }))
def post(self): json_data = request.get_json(force=True) score = Score(json_data) score.create() print("score %r created" % score) return {'result': True}
# Set up Pygame pygame.init() hit_wall = pygame.mixer.Sound('sounds/pong_wall.wav') hit_paddle = pygame.mixer.Sound('sounds/pong_wall.wav') screen = pygame.display.set_mode((Config.width, Config.height)) clock = pygame.time.Clock() # Set up Models leftPaddle = Paddle(Config.paddle_left_start_x, Config.paddle_left_start_y, Config.paddle_upper_limit, Config.paddle_lower_limit) rightPaddle = Paddle(Config.paddle_right_start_x, Config.paddle_right_start_y, Config.paddle_upper_limit, Config.paddle_lower_limit) ball = Ball(Config.ball_left_start_x, Config.ball_left_start_y, Config.ball_size) score = Score() pong = Pong(leftPaddle, rightPaddle, ball, score, hit_wall, hit_paddle, Config.color) # Game Loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() keys = pygame.key.get_pressed() if keys[pygame.K_q]: pong.move_left_up() if keys[pygame.K_a]: pong.move_left_down()
def score2(): return Score(15,'KOBE')
def score(): return Score(10)
def scores(self): scores_list = [] for value in self._scores.values(): scores_list.append(value) return scores_list def add_score(self, values): self._scores[values.name] = values def remove_score(self, score_name): if score_name in self._scores: del self._scores[score_name] def __len__(self): return len(self.scores) def get_scores(self): scores_to_return = [] for item in self._scores.values(): scores_to_return.append(item.__dict__) return scores_to_return if __name__ == "__main__": sm = ScoreManager() good = Score("Good", 999) bad = Score("bad", 222) sm.add_score(bad) sm.add_score(good) print(sm.get_scores())
def test_create(self): sc = Score(tags)
def test_fit(self): sc = Score(tags) sc.fit(y, y) self.assertTrue(np.min(sc.y_hat == y[2:-1]), 'The parsing is not working')