Example #1
0
    def post(self):
        game = model.GetGame()
        team = login.GetTeamOrRedirect(game, self.request, self.response)
        if not team: return

        if game.voting_enabled:
            sr = range(len(model.Feedback().scores))
            puzzles = model.Puzzle.all().ancestor(game)
            feedback_keys = [
                db.Key.from_path("Feedback", str(team.key()), parent=p.key())
                for p in puzzles
            ]
            feedback = {}
            for p, f in zip(puzzles, model.Feedback.get(feedback_keys)):
                if p.key().parent() == team.key(): continue  # No self voting
                n = p.number
                score = [self.request.get("score.%s.%d" % (n, s)) for s in sr]
                score_orig = [
                    self.request.get("score.%s.%d.orig" % (n, s)) for s in sr
                ]
                if (score != score_orig) or not f:
                    if not f:
                        f = model.Feedback(parent=p, key_name=str(team.key()))
                    for s in sr:
                        f.scores[s] = puzzle.NormalizeScore(score[s])
                    if not self.request.get("normalize"): f.put()
                feedback.setdefault(p.key().name(), []).append(f)

            if self.request.get("normalize"):
                for flist in feedback.values():
                    for i in range(len(flist[0].scores)):
                        vector = [f.scores[i] for f in flist]
                        NormalizeVector(vector, 0, 5, 3)
                        for f, s in zip(flist, vector):
                            f.scores[i] = round(s * 10) / 10.0
                    for f in flist:
                        f.put()

        self.redirect("/team?t=%d" % team.key().id())
        team.name = self.request.get("name") or team.name
        team.email = self.request.get("email")

        set_pw = self.request.get("set_password")
        confirm_pw = self.request.get("confirm_password")
        if set_pw or confirm_pw:
            if set_pw != confirm_pw:
                self.response.headers["location"] += "&error=set_password"
            else:
                team.password = set_pw

        team.put()
Example #2
0
    def post(self):
        game = model.GetGame()
        team = login.GetTeamOrRedirect(game, self.request, self.response)
        if not team: return

        puzzle = MaybeGetPuzzle(game, self.request)
        if not puzzle: return self.error(404)

        self.redirect("/guess?t=%d&p=%s" %
                      (team.key().id(), self.request.get("p")))

        if self.request.get("comment", None) is not None:
            feedback = model.Feedback(parent=puzzle, key_name=str(team.key()))
            feedback.comment = self.request.get("comment")
            if game.solving_enabled or game.voting_enabled:
                for s in range(len(feedback.scores)):
                    feedback.scores[s] = NormalizeScore(
                        self.request.get("score.%d" % s))
            feedback.put()
            self.redirect("/team?t=%d" % team.key().id())

        answer = NormalizeAnswer(self.request.get("answer", ""))
        if answer and game.solving_enabled:
            start_time = datetime.datetime.now() - datetime.timedelta(
                0, SPAM_SECONDS)
            guesses = model.Guess.all().ancestor(puzzle).filter(
                "team", team.key())
            recent = guesses.filter("timestamp >=",
                                    start_time).fetch(SPAM_GUESSES)
            if answer in [g.answer for g in recent]:
                self.response.headers["location"] += "&error=dup"
            elif len(recent) >= SPAM_GUESSES:
                self.response.headers["location"] += "&error=spam"
            else:
                model.Guess(parent=puzzle, answer=answer, team=team).put()
Example #3
0
    def on_post(self, req, resp):
        """Create new feedback"""
        try:
            user = req.context['user']

            if not user.is_logged_in():
                resp.status = falcon.HTTP_400
                return

            data = json.loads(req.stream.read().decode('utf-8'))['feedback']

            if session.query(model.Task).get(int(data['taskId'])) is None:
                req.context['result'] = {
                    'errors': [{
                        'status': '404',
                        'title': 'Not found',
                        'detail': 'Úloha s tímto ID neexistuje.'
                    }]
                }
                resp.status = falcon.HTTP_404
                return

            content = json.dumps(
                util.feedback.parse_feedback(data['categories']),
                indent=2,
                ensure_ascii=False,
            )

            feedback = model.Feedback(
                user=user.get_id(),
                task=int(data['taskId']),
                content=content,
                lastUpdated=datetime.datetime.utcnow(),
            )

            session.add(feedback)
            session.commit()

            req.context['result'] = {
                'feedback': util.feedback.to_json(feedback)
            }

        except (EForbiddenType, EUnmatchingDataType, EMissingAnswer,
                EOutOfRange) as e:
            req.context['result'] = {
                'errors': [{
                    'status': '400',
                    'title': 'Bad Request',
                    'detail': str(e)
                }]
            }
            resp.status = falcon.HTTP_400
            return
        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()
Example #4
0
    def on_put(self, req, resp, id):
        """Update feedback."""
        try:
            user = req.context['user']

            if not user.is_logged_in():
                resp.status = falcon.HTTP_400
                return

            data = json.loads(req.stream.read().decode('utf-8'))['feedback']

            feedback = session.query(model.Feedback).get((user.get_id(), id))
            if feedback is None:
                feedback = model.Feedback(
                    user=user.get_id(),
                    task=id,
                    content='{}',
                )
                session.add(feedback)

            feedback.lastUpdated = datetime.datetime.utcnow()
            feedback.content = json.dumps(
                util.feedback.parse_feedback(data['categories']),
                indent=2,
                ensure_ascii=False,
            )

            session.commit()

        except (EForbiddenType, EUnmatchingDataType, EMissingAnswer,
                EOutOfRange) as e:
            req.context['result'] = {
                'errors': [{
                    'status': '400',
                    'title': 'Bad Request',
                    'detail': str(e)
                }]
            }
            resp.status = falcon.HTTP_400
            return
        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()

        self.on_get(req, resp, id)
Example #5
0
 def post(self):
     feedback = model.Feedback()
     payload = json.loads(self.request.body)
     user = get_state()['user']
     json_reply(self)
     d = dict()
     d['status'] = 'ok'
     if 'feedback' in payload:
         feedback.feedback = payload['feedback']
     if 'user_id' in payload:
         if payload['user_id'] != user.user_id:
             d['status'] = 'insufficient permission'
             self.response.write(to_json(d))
             return
         else:
             feedback.user = user.key
     feedback.put()
     d['feedback'] = feedback.to_dict()
     self.response.write(to_json(d))
Example #6
0
    def get(self):
        game = model.GetGame()
        team = login.GetTeamOrRedirect(game, self.request, self.response)
        if not team: return

        puzzle = MaybeGetPuzzle(team, self.request)
        if not puzzle: return self.error(404)
        if puzzle.parent_key() != team.key(): return self.error(403)

        props = {
            "form_url": blobstore.create_upload_url("/puzzle"),
            "game": model.GetProperties(game),
            "team": model.GetProperties(team),
            "puzzle": model.GetProperties(puzzle),
            "comments": [],
            "votes": [],
            "solves": [],
        }

        no_scores = model.Feedback().scores
        for feedback in model.Feedback.all().ancestor(puzzle):
            comment = (feedback.comment or "").strip()
            if comment: props["comments"].append(comment)
            props["votes"].append(feedback.scores)

        props["puzzle"]["answers"] = "\n".join(props["puzzle"].get(
            "answers", []))
        props["comments"].sort(key=unicode.lower)
        props["votes"].sort(reverse=True)

        solvers = {}
        for guess in model.Guess.all().ancestor(puzzle).order("timestamp"):
            if guess.answer in puzzle.answers and not solvers.get(
                    guess.team.key()):
                solvers[guess.team.key()] = 1
                props["solves"].append(guess)

        self.response.out.write(template.render("puzzle.dj.html", props))
Example #7
0
    def get(self):
        game = model.GetGame()

        props = {
            "admin_email": admin.GetAdminEmail(game),
            "admin_logout_url": users.create_logout_url(dest_url="/"),
            "game": model.GetProperties(game),
            "puzzles": [],
            "teams": [],
        }

        team_by_key = {}
        for team in model.Team.all().ancestor(game):
            team_props = team_by_key[team.key()] = model.GetProperties(team)
            team_props.update({
                "generosity": {},
                "score": team_props.get("bonus") or 0.0,
                "solve_count": 0,
                "solve_score": 0,
                "solve_time": 0,
                "works": [],
                "wrote": {},
                "wrote_score": 0,
            })
            cookie = login.CookiePassword(team, self.request)
            if cookie:
                props["cookie_team"] = team_props
                props["cookie_password"] = cookie
            props["teams"].append(team_props)

        puzzle_by_key = {}
        for p in sorted(model.Puzzle.all().ancestor(game), key=puzzle.SortKey):
            puzzle_props = puzzle_by_key[p.key()] = model.GetProperties(p)
            author_props = team_by_key.get(p.key().parent(), {})
            puzzle_props.update({
                "author": author_props.get("name"),
                "author_id": author_props.get("key_id"),
                "score": 0,
                "solve_count": 0,
                "votes": [],
            })
            author_props["wrote"][p.key().name()] = puzzle_props
            props["puzzles"].append(puzzle_props)

        for feedback in model.Feedback.all().ancestor(game):
            puzzle_props = puzzle_by_key[feedback.key().parent()]
            puzzle_props["votes"].append(feedback.scores)
            puzzle_type = puzzle_props["key_name"]
            team_props = team_by_key[db.Key(feedback.key().name())]
            generosity = team_props["generosity"].setdefault(
                puzzle_props["key_name"], [0] * len(feedback.scores))
            generosity[:] = [
                a + b for a, b in zip(generosity, feedback.scores)
            ]

        work_by_keys = {}
        for team_props in props["teams"]:
            for puzzle_props in props["puzzles"]:
                work_props = work_by_keys[(team_props["key"],
                                           puzzle_props["key"])] = {
                                               "puzzle": puzzle_props,
                                               "guess_count": 0,
                                           }
                team_props["works"].append(work_props)

        for guess in model.Guess.all().ancestor(game).order("timestamp"):
            work_props = work_by_keys[(guess.team.key(), guess.key().parent())]
            if guess.answer in work_props["puzzle"]["answers"]:
                if not work_props.get("solve_time"):
                    team_props = team_by_key[guess.team.key()]
                    work_props["solve_time"] = team_props[
                        "solve_time"] = guess.timestamp
                    work_props["puzzle"]["solve_count"] += 1
                    team_props["solve_count"] += 1

        #
        # Compute scores
        #

        no_scores = model.Feedback().scores
        for team_props in props["teams"]:
            for puzzle_props in team_props["wrote"].values():
                wrote_scores = puzzle_props["scores"] = [0 for s in no_scores]
                for scores in puzzle_props["votes"]:
                    for i in range(len(wrote_scores)):
                        if i < len(scores): wrote_scores[i] += scores[i]

                unvoted = len(team_by_key) - len(puzzle_props["votes"]) - 1
                if unvoted > 0:
                    for i in range(len(wrote_scores)):
                        wrote_scores[i] += no_scores[i] * unvoted

                points = 2 * wrote_scores[0] + sum(wrote_scores[1:])
                puzzle_props["score"] = points
                team_props["score"] += points
                team_props["wrote_score"] += points

            for work_props in team_props["works"]:
                if work_props.get("solve_time"):
                    points = 9 + len(
                        props["teams"]) - work_props["puzzle"]["solve_count"]
                    work_props["score"] = points
                    team_props["solve_score"] += points
                    team_props["score"] += points

        props["teams"].sort(
            key=lambda tp: (-tp["solve_count"], tp["solve_time"], tp["name"]))

        self.response.out.write(template.render("main.dj.html", props))
Example #8
0
    def get(self):
        game = model.GetGame()
        team = login.GetTeamOrRedirect(game, self.request, self.response)
        if not team: return

        props = {
            "error": self.request.get_all("error"),
            "game": model.GetProperties(game),
            "team": model.GetProperties(team),
            "team_puzzles": [],
            "other_puzzles": [],
            "errata_puzzles": [],
        }

        puzzle_props = {}
        for p in sorted(model.Puzzle.all().ancestor(game), key=puzzle.SortKey):
            pp = puzzle_props[p.key()] = model.GetProperties(p)
            pp.update({
                "guess_count": 0,
                "solve_teams": set(),
                "comment_count": 0,
                "vote_count": 0,
            })
            if pp.get("errata"):
                props["errata_puzzles"].append(pp)
            if p.parent_key() == team.key():
                props["team_puzzles"].append(pp)
            else:
                props["other_puzzles"].append(pp)

        feedback_keys = [
            db.Key.from_path("Feedback", str(team.key()), parent=pp["key"])
            for pp in props["other_puzzles"]
        ]
        for key, feedback in zip(feedback_keys,
                                 model.Feedback.get(feedback_keys)):
            pp = puzzle_props.get(key.parent())
            if pp:
                pp["feedback"] = model.GetProperties(
                    feedback or model.Feedback(key=key))

        no_scores = model.Feedback().scores
        for review in model.Feedback.all().ancestor(team):
            pp = puzzle_props.get(review.key().parent())
            if pp:
                if review.comment and review.comment.strip():
                    pp["comment_count"] += 1
                pp["vote_count"] += 1

        for guess in model.Guess.all().ancestor(game):
            pp = puzzle_props.get(guess.parent_key())
            if not pp: continue

            if guess.answer in pp["answers"]:
                pp["solve_teams"].add(guess.team.key())

            if guess.team.key() == team.key():
                if guess.answer in pp["answers"]:
                    pp["solve_time"] = guess.timestamp
                pp["guess_count"] += 1

        self.response.out.write(template.render("team.dj.html", props))
Example #9
0
cudnn.benchmark = True
if torch.cuda.is_available() and not opt.cuda:
    print(
        "WARNING: You have a CUDA device, so you should probably run with --cuda"
    )
# load data
data = util.DATA_LOADER(opt)
print("Training samples: ", data.ntrain)
print("Dataset: ", opt.dataset)

# Init modules: Encoder, Generator, Discriminator
netE = model.Encoder(opt)
netG = model.Generator(opt)
netD = model.Discriminator_D1(opt)
# Init models: Feedback module, auxillary module
netF = model.Feedback(opt)
netDec = model.AttDec(opt, opt.attSize)

print(netE)
print(netG)
print(netD)

print(netF)
print(netDec)

# Init Tensors
input_res = torch.FloatTensor(opt.batch_size, opt.resSize)
input_att = torch.FloatTensor(opt.batch_size, opt.attSize)
noise = torch.FloatTensor(opt.batch_size, opt.nz)
one = torch.FloatTensor([1])
mone = one * -1