We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Awards is not accounted in `user.place()`
[`user.place()`][user_place] is not accounting awards while [`get_standings()`][get_standings] does. This causes different ordering in scoreboard and team profile. Is this by design?

[user_place]: https://github.com/CTFd/CTFd/blob/master/CTFd/models.py#L200
[get_standings]: https://github.com/CTFd/CTFd/blob/master/CTFd/scoreboard.py#L11


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `CTFd/models.py`
Content:
```
1 import datetime
2 import hashlib
3 import json
4 import netaddr
5 from socket import inet_pton, inet_ntop, AF_INET, AF_INET6
6 from struct import unpack, pack, error as struct_error
7 
8 from flask_sqlalchemy import SQLAlchemy
9 from passlib.hash import bcrypt_sha256
10 from sqlalchemy.exc import DatabaseError
11 
12 
13 def sha512(string):
14     return str(hashlib.sha512(string).hexdigest())
15 
16 
17 def ip2long(ip):
18     '''Converts a user's IP address into an integer/long'''
19     return int(netaddr.IPAddress(ip))
20 
21 
22 def long2ip(ip_int):
23     '''Converts a saved integer/long back into an IP address'''
24     return str(netaddr.IPAddress(ip_int))
25 
26 
27 db = SQLAlchemy()
28 
29 
30 class Pages(db.Model):
31     id = db.Column(db.Integer, primary_key=True)
32     route = db.Column(db.String(80), unique=True)
33     html = db.Column(db.Text)
34 
35     def __init__(self, route, html):
36         self.route = route
37         self.html = html
38 
39     def __repr__(self):
40         return "<Pages route {0}>".format(self.route)
41 
42 
43 class Containers(db.Model):
44     id = db.Column(db.Integer, primary_key=True)
45     name = db.Column(db.String(80))
46     buildfile = db.Column(db.Text)
47 
48     def __init__(self, name, buildfile):
49         self.name = name
50         self.buildfile = buildfile
51 
52     def __repr__(self):
53         return "<Container ID:(0) {1}>".format(self.id, self.name)
54 
55 
56 class Challenges(db.Model):
57     id = db.Column(db.Integer, primary_key=True)
58     name = db.Column(db.String(80))
59     description = db.Column(db.Text)
60     max_attempts = db.Column(db.Integer, default=0)
61     value = db.Column(db.Integer)
62     category = db.Column(db.String(80))
63     type = db.Column(db.Integer)
64     hidden = db.Column(db.Boolean)
65 
66     def __init__(self, name, description, value, category, type=0):
67         self.name = name
68         self.description = description
69         self.value = value
70         self.category = category
71         self.type = type
72         # self.flags = json.dumps(flags)
73 
74     def __repr__(self):
75         return '<chal %r>' % self.name
76 
77 
78 class Hints(db.Model):
79     id = db.Column(db.Integer, primary_key=True)
80     type = db.Column(db.Integer, default=0)
81     chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))
82     hint = db.Column(db.Text)
83     cost = db.Column(db.Integer, default=0)
84 
85     def __init__(self, chal, hint, cost=0, type=0):
86         self.chal = chal
87         self.hint = hint
88         self.cost = cost
89         self.type = type
90 
91     def __repr__(self):
92         return '<hint %r>' % self.hint
93 
94 
95 class Awards(db.Model):
96     id = db.Column(db.Integer, primary_key=True)
97     teamid = db.Column(db.Integer, db.ForeignKey('teams.id'))
98     name = db.Column(db.String(80))
99     description = db.Column(db.Text)
100     date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
101     value = db.Column(db.Integer)
102     category = db.Column(db.String(80))
103     icon = db.Column(db.Text)
104 
105     def __init__(self, teamid, name, value):
106         self.teamid = teamid
107         self.name = name
108         self.value = value
109 
110     def __repr__(self):
111         return '<award %r>' % self.name
112 
113 
114 class Tags(db.Model):
115     id = db.Column(db.Integer, primary_key=True)
116     chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))
117     tag = db.Column(db.String(80))
118 
119     def __init__(self, chal, tag):
120         self.chal = chal
121         self.tag = tag
122 
123     def __repr__(self):
124         return "<Tag {0} for challenge {1}>".format(self.tag, self.chal)
125 
126 
127 class Files(db.Model):
128     id = db.Column(db.Integer, primary_key=True)
129     chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))
130     location = db.Column(db.Text)
131 
132     def __init__(self, chal, location):
133         self.chal = chal
134         self.location = location
135 
136     def __repr__(self):
137         return "<File {0} for challenge {1}>".format(self.location, self.chal)
138 
139 
140 class Keys(db.Model):
141     id = db.Column(db.Integer, primary_key=True)
142     chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))
143     key_type = db.Column(db.Integer)
144     flag = db.Column(db.Text)
145     data = db.Column(db.Text)
146 
147     def __init__(self, chal, flag, key_type):
148         self.chal = chal
149         self.flag = flag
150         self.key_type = key_type
151 
152     def __repr__(self):
153         return "<Flag {0} for challenge {1}>".format(self.flag, self.chal)
154 
155 
156 class Teams(db.Model):
157     id = db.Column(db.Integer, primary_key=True)
158     name = db.Column(db.String(128), unique=True)
159     email = db.Column(db.String(128), unique=True)
160     password = db.Column(db.String(128))
161     website = db.Column(db.String(128))
162     affiliation = db.Column(db.String(128))
163     country = db.Column(db.String(32))
164     bracket = db.Column(db.String(32))
165     banned = db.Column(db.Boolean, default=False)
166     verified = db.Column(db.Boolean, default=False)
167     admin = db.Column(db.Boolean, default=False)
168     joined = db.Column(db.DateTime, default=datetime.datetime.utcnow)
169 
170     def __init__(self, name, email, password):
171         self.name = name
172         self.email = email
173         self.password = bcrypt_sha256.encrypt(str(password))
174 
175     def __repr__(self):
176         return '<team %r>' % self.name
177 
178     def score(self, admin=False):
179         score = db.func.sum(Challenges.value).label('score')
180         team = db.session.query(Solves.teamid, score).join(Teams).join(Challenges).filter(Teams.banned == False, Teams.id == self.id)
181         award_score = db.func.sum(Awards.value).label('award_score')
182         award = db.session.query(award_score).filter_by(teamid=self.id)
183 
184         if not admin:
185             freeze = Config.query.filter_by(key='freeze').first()
186             if freeze and freeze.value:
187                 freeze = int(freeze.value)
188                 freeze = datetime.datetime.utcfromtimestamp(freeze)
189                 team = team.filter(Solves.date < freeze)
190                 award = award.filter(Awards.date < freeze)
191 
192         team = team.group_by(Solves.teamid).first()
193         award = award.first()
194 
195         if team:
196             return int(team.score or 0) + int(award.award_score or 0)
197         else:
198             return 0
199 
200     def place(self, admin=False):
201         score = db.func.sum(Challenges.value).label('score')
202         quickest = db.func.max(Solves.date).label('quickest')
203         teams = db.session.query(Solves.teamid).join(Teams).join(Challenges).filter(Teams.banned == False)
204 
205         if not admin:
206             freeze = Config.query.filter_by(key='freeze').first()
207             if freeze and freeze.value:
208                 freeze = int(freeze.value)
209                 freeze = datetime.datetime.utcfromtimestamp(freeze)
210                 teams = teams.filter(Solves.date < freeze)
211 
212         teams = teams.group_by(Solves.teamid).order_by(score.desc(), quickest).all()
213 
214         # http://codegolf.stackexchange.com/a/4712
215         try:
216             i = teams.index((self.id,)) + 1
217             k = i % 10
218             return "%d%s" % (i, "tsnrhtdd"[(i / 10 % 10 != 1) * (k < 4) * k::4])
219         except ValueError:
220             return 0
221 
222 
223 class Solves(db.Model):
224     __table_args__ = (db.UniqueConstraint('chalid', 'teamid'), {})
225     id = db.Column(db.Integer, primary_key=True)
226     chalid = db.Column(db.Integer, db.ForeignKey('challenges.id'))
227     teamid = db.Column(db.Integer, db.ForeignKey('teams.id'))
228     ip = db.Column(db.String(46))
229     flag = db.Column(db.Text)
230     date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
231     team = db.relationship('Teams', foreign_keys="Solves.teamid", lazy='joined')
232     chal = db.relationship('Challenges', foreign_keys="Solves.chalid", lazy='joined')
233     # value = db.Column(db.Integer)
234 
235     def __init__(self, teamid, chalid, ip, flag):
236         self.ip = ip
237         self.chalid = chalid
238         self.teamid = teamid
239         self.flag = flag
240         # self.value = value
241 
242     def __repr__(self):
243         return '<solve {}, {}, {}, {}>'.format(self.teamid, self.chalid, self.ip, self.flag)
244 
245 
246 class WrongKeys(db.Model):
247     id = db.Column(db.Integer, primary_key=True)
248     chalid = db.Column(db.Integer, db.ForeignKey('challenges.id'))
249     teamid = db.Column(db.Integer, db.ForeignKey('teams.id'))
250     ip = db.Column(db.String(46))
251     date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
252     flag = db.Column(db.Text)
253     chal = db.relationship('Challenges', foreign_keys="WrongKeys.chalid", lazy='joined')
254 
255     def __init__(self, teamid, chalid, ip, flag):
256         self.ip = ip
257         self.teamid = teamid
258         self.chalid = chalid
259         self.flag = flag
260 
261     def __repr__(self):
262         return '<wrong {}, {}, {}, {}>'.format(self.teamid, self.chalid, self.ip, self.flag)
263 
264 
265 class Unlocks(db.Model):
266     id = db.Column(db.Integer, primary_key=True)
267     teamid = db.Column(db.Integer, db.ForeignKey('teams.id'))
268     date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
269     itemid = db.Column(db.Integer)
270     model = db.Column(db.String(32))
271 
272     def __init__(self, model, teamid, itemid):
273         self.model = model
274         self.teamid = teamid
275         self.itemid = itemid
276 
277     def __repr__(self):
278         return '<unlock %r>' % self.teamid
279 
280 
281 class Tracking(db.Model):
282     id = db.Column(db.Integer, primary_key=True)
283     ip = db.Column(db.String(46))
284     team = db.Column(db.Integer, db.ForeignKey('teams.id'))
285     date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
286 
287     def __init__(self, ip, team):
288         self.ip = ip
289         self.team = team
290 
291     def __repr__(self):
292         return '<ip %r>' % self.team
293 
294 
295 class Config(db.Model):
296     id = db.Column(db.Integer, primary_key=True)
297     key = db.Column(db.Text)
298     value = db.Column(db.Text)
299 
300     def __init__(self, key, value):
301         self.key = key
302         self.value = value
303
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/CTFd/models.py b/CTFd/models.py
--- a/CTFd/models.py
+++ b/CTFd/models.py
@@ -8,6 +8,7 @@
 from flask_sqlalchemy import SQLAlchemy
 from passlib.hash import bcrypt_sha256
 from sqlalchemy.exc import DatabaseError
+from sqlalchemy.sql.expression import union_all
 
 
 def sha512(string):
@@ -198,22 +199,44 @@
             return 0
 
     def place(self, admin=False):
-        score = db.func.sum(Challenges.value).label('score')
-        quickest = db.func.max(Solves.date).label('quickest')
-        teams = db.session.query(Solves.teamid).join(Teams).join(Challenges).filter(Teams.banned == False)
+        scores = db.session.query(
+            Solves.teamid.label('teamid'),
+            db.func.sum(Challenges.value).label('score'),
+            db.func.max(Solves.date).label('date')
+        ).join(Challenges).group_by(Solves.teamid)
+
+        awards = db.session.query(
+            Awards.teamid.label('teamid'),
+            db.func.sum(Awards.value).label('score'),
+            db.func.max(Awards.date).label('date')
+        ).group_by(Awards.teamid)
 
         if not admin:
             freeze = Config.query.filter_by(key='freeze').first()
             if freeze and freeze.value:
                 freeze = int(freeze.value)
                 freeze = datetime.datetime.utcfromtimestamp(freeze)
-                teams = teams.filter(Solves.date < freeze)
+                scores = scores.filter(Solves.date < freeze)
+                awards = awards.filter(Awards.date < freeze)
+
+        results = union_all(scores, awards).alias('results')
+
+        sumscore = db.func.sum(results.columns.score).label('sumscore')
+        quickest = db.func.max(results.columns.date).label('quickest')
+
+        standings_query = db.session.query(results.columns.teamid)\
+            .join(Teams)\
+            .group_by(results.columns.teamid)\
+            .order_by(sumscore.desc(), quickest)
+
+        if not admin:
+            standings_query = standings_query.filter(Teams.banned == False)
 
-        teams = teams.group_by(Solves.teamid).order_by(score.desc(), quickest).all()
+        standings = standings_query.all()
 
         # http://codegolf.stackexchange.com/a/4712
         try:
-            i = teams.index((self.id,)) + 1
+            i = standings.index((self.id,)) + 1
             k = i % 10
             return "%d%s" % (i, "tsnrhtdd"[(i / 10 % 10 != 1) * (k < 4) * k::4])
         except ValueError:

{"golden_diff": "diff --git a/CTFd/models.py b/CTFd/models.py\n--- a/CTFd/models.py\n+++ b/CTFd/models.py\n@@ -8,6 +8,7 @@\n from flask_sqlalchemy import SQLAlchemy\n from passlib.hash import bcrypt_sha256\n from sqlalchemy.exc import DatabaseError\n+from sqlalchemy.sql.expression import union_all\n \n \n def sha512(string):\n@@ -198,22 +199,44 @@\n             return 0\n \n     def place(self, admin=False):\n-        score = db.func.sum(Challenges.value).label('score')\n-        quickest = db.func.max(Solves.date).label('quickest')\n-        teams = db.session.query(Solves.teamid).join(Teams).join(Challenges).filter(Teams.banned == False)\n+        scores = db.session.query(\n+            Solves.teamid.label('teamid'),\n+            db.func.sum(Challenges.value).label('score'),\n+            db.func.max(Solves.date).label('date')\n+        ).join(Challenges).group_by(Solves.teamid)\n+\n+        awards = db.session.query(\n+            Awards.teamid.label('teamid'),\n+            db.func.sum(Awards.value).label('score'),\n+            db.func.max(Awards.date).label('date')\n+        ).group_by(Awards.teamid)\n \n         if not admin:\n             freeze = Config.query.filter_by(key='freeze').first()\n             if freeze and freeze.value:\n                 freeze = int(freeze.value)\n                 freeze = datetime.datetime.utcfromtimestamp(freeze)\n-                teams = teams.filter(Solves.date < freeze)\n+                scores = scores.filter(Solves.date < freeze)\n+                awards = awards.filter(Awards.date < freeze)\n+\n+        results = union_all(scores, awards).alias('results')\n+\n+        sumscore = db.func.sum(results.columns.score).label('sumscore')\n+        quickest = db.func.max(results.columns.date).label('quickest')\n+\n+        standings_query = db.session.query(results.columns.teamid)\\\n+            .join(Teams)\\\n+            .group_by(results.columns.teamid)\\\n+            .order_by(sumscore.desc(), quickest)\n+\n+        if not admin:\n+            standings_query = standings_query.filter(Teams.banned == False)\n \n-        teams = teams.group_by(Solves.teamid).order_by(score.desc(), quickest).all()\n+        standings = standings_query.all()\n \n         # http://codegolf.stackexchange.com/a/4712\n         try:\n-            i = teams.index((self.id,)) + 1\n+            i = standings.index((self.id,)) + 1\n             k = i % 10\n             return \"%d%s\" % (i, \"tsnrhtdd\"[(i / 10 % 10 != 1) * (k < 4) * k::4])\n         except ValueError:\n", "issue": "Awards is not accounted in `user.place()`\n[`user.place()`][user_place] is not accounting awards while [`get_standings()`][get_standings] does. This causes different ordering in scoreboard and team profile. Is this by design?\r\n\r\n[user_place]: https://github.com/CTFd/CTFd/blob/master/CTFd/models.py#L200\r\n[get_standings]: https://github.com/CTFd/CTFd/blob/master/CTFd/scoreboard.py#L11\r\n\n", "before_files": [{"content": "import datetime\nimport hashlib\nimport json\nimport netaddr\nfrom socket import inet_pton, inet_ntop, AF_INET, AF_INET6\nfrom struct import unpack, pack, error as struct_error\n\nfrom flask_sqlalchemy import SQLAlchemy\nfrom passlib.hash import bcrypt_sha256\nfrom sqlalchemy.exc import DatabaseError\n\n\ndef sha512(string):\n    return str(hashlib.sha512(string).hexdigest())\n\n\ndef ip2long(ip):\n    '''Converts a user's IP address into an integer/long'''\n    return int(netaddr.IPAddress(ip))\n\n\ndef long2ip(ip_int):\n    '''Converts a saved integer/long back into an IP address'''\n    return str(netaddr.IPAddress(ip_int))\n\n\ndb = SQLAlchemy()\n\n\nclass Pages(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    route = db.Column(db.String(80), unique=True)\n    html = db.Column(db.Text)\n\n    def __init__(self, route, html):\n        self.route = route\n        self.html = html\n\n    def __repr__(self):\n        return \"<Pages route {0}>\".format(self.route)\n\n\nclass Containers(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    name = db.Column(db.String(80))\n    buildfile = db.Column(db.Text)\n\n    def __init__(self, name, buildfile):\n        self.name = name\n        self.buildfile = buildfile\n\n    def __repr__(self):\n        return \"<Container ID:(0) {1}>\".format(self.id, self.name)\n\n\nclass Challenges(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    name = db.Column(db.String(80))\n    description = db.Column(db.Text)\n    max_attempts = db.Column(db.Integer, default=0)\n    value = db.Column(db.Integer)\n    category = db.Column(db.String(80))\n    type = db.Column(db.Integer)\n    hidden = db.Column(db.Boolean)\n\n    def __init__(self, name, description, value, category, type=0):\n        self.name = name\n        self.description = description\n        self.value = value\n        self.category = category\n        self.type = type\n        # self.flags = json.dumps(flags)\n\n    def __repr__(self):\n        return '<chal %r>' % self.name\n\n\nclass Hints(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    type = db.Column(db.Integer, default=0)\n    chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))\n    hint = db.Column(db.Text)\n    cost = db.Column(db.Integer, default=0)\n\n    def __init__(self, chal, hint, cost=0, type=0):\n        self.chal = chal\n        self.hint = hint\n        self.cost = cost\n        self.type = type\n\n    def __repr__(self):\n        return '<hint %r>' % self.hint\n\n\nclass Awards(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    teamid = db.Column(db.Integer, db.ForeignKey('teams.id'))\n    name = db.Column(db.String(80))\n    description = db.Column(db.Text)\n    date = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n    value = db.Column(db.Integer)\n    category = db.Column(db.String(80))\n    icon = db.Column(db.Text)\n\n    def __init__(self, teamid, name, value):\n        self.teamid = teamid\n        self.name = name\n        self.value = value\n\n    def __repr__(self):\n        return '<award %r>' % self.name\n\n\nclass Tags(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))\n    tag = db.Column(db.String(80))\n\n    def __init__(self, chal, tag):\n        self.chal = chal\n        self.tag = tag\n\n    def __repr__(self):\n        return \"<Tag {0} for challenge {1}>\".format(self.tag, self.chal)\n\n\nclass Files(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))\n    location = db.Column(db.Text)\n\n    def __init__(self, chal, location):\n        self.chal = chal\n        self.location = location\n\n    def __repr__(self):\n        return \"<File {0} for challenge {1}>\".format(self.location, self.chal)\n\n\nclass Keys(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))\n    key_type = db.Column(db.Integer)\n    flag = db.Column(db.Text)\n    data = db.Column(db.Text)\n\n    def __init__(self, chal, flag, key_type):\n        self.chal = chal\n        self.flag = flag\n        self.key_type = key_type\n\n    def __repr__(self):\n        return \"<Flag {0} for challenge {1}>\".format(self.flag, self.chal)\n\n\nclass Teams(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    name = db.Column(db.String(128), unique=True)\n    email = db.Column(db.String(128), unique=True)\n    password = db.Column(db.String(128))\n    website = db.Column(db.String(128))\n    affiliation = db.Column(db.String(128))\n    country = db.Column(db.String(32))\n    bracket = db.Column(db.String(32))\n    banned = db.Column(db.Boolean, default=False)\n    verified = db.Column(db.Boolean, default=False)\n    admin = db.Column(db.Boolean, default=False)\n    joined = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n\n    def __init__(self, name, email, password):\n        self.name = name\n        self.email = email\n        self.password = bcrypt_sha256.encrypt(str(password))\n\n    def __repr__(self):\n        return '<team %r>' % self.name\n\n    def score(self, admin=False):\n        score = db.func.sum(Challenges.value).label('score')\n        team = db.session.query(Solves.teamid, score).join(Teams).join(Challenges).filter(Teams.banned == False, Teams.id == self.id)\n        award_score = db.func.sum(Awards.value).label('award_score')\n        award = db.session.query(award_score).filter_by(teamid=self.id)\n\n        if not admin:\n            freeze = Config.query.filter_by(key='freeze').first()\n            if freeze and freeze.value:\n                freeze = int(freeze.value)\n                freeze = datetime.datetime.utcfromtimestamp(freeze)\n                team = team.filter(Solves.date < freeze)\n                award = award.filter(Awards.date < freeze)\n\n        team = team.group_by(Solves.teamid).first()\n        award = award.first()\n\n        if team:\n            return int(team.score or 0) + int(award.award_score or 0)\n        else:\n            return 0\n\n    def place(self, admin=False):\n        score = db.func.sum(Challenges.value).label('score')\n        quickest = db.func.max(Solves.date).label('quickest')\n        teams = db.session.query(Solves.teamid).join(Teams).join(Challenges).filter(Teams.banned == False)\n\n        if not admin:\n            freeze = Config.query.filter_by(key='freeze').first()\n            if freeze and freeze.value:\n                freeze = int(freeze.value)\n                freeze = datetime.datetime.utcfromtimestamp(freeze)\n                teams = teams.filter(Solves.date < freeze)\n\n        teams = teams.group_by(Solves.teamid).order_by(score.desc(), quickest).all()\n\n        # http://codegolf.stackexchange.com/a/4712\n        try:\n            i = teams.index((self.id,)) + 1\n            k = i % 10\n            return \"%d%s\" % (i, \"tsnrhtdd\"[(i / 10 % 10 != 1) * (k < 4) * k::4])\n        except ValueError:\n            return 0\n\n\nclass Solves(db.Model):\n    __table_args__ = (db.UniqueConstraint('chalid', 'teamid'), {})\n    id = db.Column(db.Integer, primary_key=True)\n    chalid = db.Column(db.Integer, db.ForeignKey('challenges.id'))\n    teamid = db.Column(db.Integer, db.ForeignKey('teams.id'))\n    ip = db.Column(db.String(46))\n    flag = db.Column(db.Text)\n    date = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n    team = db.relationship('Teams', foreign_keys=\"Solves.teamid\", lazy='joined')\n    chal = db.relationship('Challenges', foreign_keys=\"Solves.chalid\", lazy='joined')\n    # value = db.Column(db.Integer)\n\n    def __init__(self, teamid, chalid, ip, flag):\n        self.ip = ip\n        self.chalid = chalid\n        self.teamid = teamid\n        self.flag = flag\n        # self.value = value\n\n    def __repr__(self):\n        return '<solve {}, {}, {}, {}>'.format(self.teamid, self.chalid, self.ip, self.flag)\n\n\nclass WrongKeys(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    chalid = db.Column(db.Integer, db.ForeignKey('challenges.id'))\n    teamid = db.Column(db.Integer, db.ForeignKey('teams.id'))\n    ip = db.Column(db.String(46))\n    date = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n    flag = db.Column(db.Text)\n    chal = db.relationship('Challenges', foreign_keys=\"WrongKeys.chalid\", lazy='joined')\n\n    def __init__(self, teamid, chalid, ip, flag):\n        self.ip = ip\n        self.teamid = teamid\n        self.chalid = chalid\n        self.flag = flag\n\n    def __repr__(self):\n        return '<wrong {}, {}, {}, {}>'.format(self.teamid, self.chalid, self.ip, self.flag)\n\n\nclass Unlocks(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    teamid = db.Column(db.Integer, db.ForeignKey('teams.id'))\n    date = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n    itemid = db.Column(db.Integer)\n    model = db.Column(db.String(32))\n\n    def __init__(self, model, teamid, itemid):\n        self.model = model\n        self.teamid = teamid\n        self.itemid = itemid\n\n    def __repr__(self):\n        return '<unlock %r>' % self.teamid\n\n\nclass Tracking(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    ip = db.Column(db.String(46))\n    team = db.Column(db.Integer, db.ForeignKey('teams.id'))\n    date = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n\n    def __init__(self, ip, team):\n        self.ip = ip\n        self.team = team\n\n    def __repr__(self):\n        return '<ip %r>' % self.team\n\n\nclass Config(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    key = db.Column(db.Text)\n    value = db.Column(db.Text)\n\n    def __init__(self, key, value):\n        self.key = key\n        self.value = value\n", "path": "CTFd/models.py"}], "after_files": [{"content": "import datetime\nimport hashlib\nimport json\nimport netaddr\nfrom socket import inet_pton, inet_ntop, AF_INET, AF_INET6\nfrom struct import unpack, pack, error as struct_error\n\nfrom flask_sqlalchemy import SQLAlchemy\nfrom passlib.hash import bcrypt_sha256\nfrom sqlalchemy.exc import DatabaseError\nfrom sqlalchemy.sql.expression import union_all\n\n\ndef sha512(string):\n    return str(hashlib.sha512(string).hexdigest())\n\n\ndef ip2long(ip):\n    '''Converts a user's IP address into an integer/long'''\n    return int(netaddr.IPAddress(ip))\n\n\ndef long2ip(ip_int):\n    '''Converts a saved integer/long back into an IP address'''\n    return str(netaddr.IPAddress(ip_int))\n\n\ndb = SQLAlchemy()\n\n\nclass Pages(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    route = db.Column(db.String(80), unique=True)\n    html = db.Column(db.Text)\n\n    def __init__(self, route, html):\n        self.route = route\n        self.html = html\n\n    def __repr__(self):\n        return \"<Pages route {0}>\".format(self.route)\n\n\nclass Containers(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    name = db.Column(db.String(80))\n    buildfile = db.Column(db.Text)\n\n    def __init__(self, name, buildfile):\n        self.name = name\n        self.buildfile = buildfile\n\n    def __repr__(self):\n        return \"<Container ID:(0) {1}>\".format(self.id, self.name)\n\n\nclass Challenges(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    name = db.Column(db.String(80))\n    description = db.Column(db.Text)\n    max_attempts = db.Column(db.Integer, default=0)\n    value = db.Column(db.Integer)\n    category = db.Column(db.String(80))\n    type = db.Column(db.Integer)\n    hidden = db.Column(db.Boolean)\n\n    def __init__(self, name, description, value, category, type=0):\n        self.name = name\n        self.description = description\n        self.value = value\n        self.category = category\n        self.type = type\n        # self.flags = json.dumps(flags)\n\n    def __repr__(self):\n        return '<chal %r>' % self.name\n\n\nclass Hints(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    type = db.Column(db.Integer, default=0)\n    chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))\n    hint = db.Column(db.Text)\n    cost = db.Column(db.Integer, default=0)\n\n    def __init__(self, chal, hint, cost=0, type=0):\n        self.chal = chal\n        self.hint = hint\n        self.cost = cost\n        self.type = type\n\n    def __repr__(self):\n        return '<hint %r>' % self.hint\n\n\nclass Awards(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    teamid = db.Column(db.Integer, db.ForeignKey('teams.id'))\n    name = db.Column(db.String(80))\n    description = db.Column(db.Text)\n    date = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n    value = db.Column(db.Integer)\n    category = db.Column(db.String(80))\n    icon = db.Column(db.Text)\n\n    def __init__(self, teamid, name, value):\n        self.teamid = teamid\n        self.name = name\n        self.value = value\n\n    def __repr__(self):\n        return '<award %r>' % self.name\n\n\nclass Tags(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))\n    tag = db.Column(db.String(80))\n\n    def __init__(self, chal, tag):\n        self.chal = chal\n        self.tag = tag\n\n    def __repr__(self):\n        return \"<Tag {0} for challenge {1}>\".format(self.tag, self.chal)\n\n\nclass Files(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))\n    location = db.Column(db.Text)\n\n    def __init__(self, chal, location):\n        self.chal = chal\n        self.location = location\n\n    def __repr__(self):\n        return \"<File {0} for challenge {1}>\".format(self.location, self.chal)\n\n\nclass Keys(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))\n    key_type = db.Column(db.Integer)\n    flag = db.Column(db.Text)\n    data = db.Column(db.Text)\n\n    def __init__(self, chal, flag, key_type):\n        self.chal = chal\n        self.flag = flag\n        self.key_type = key_type\n\n    def __repr__(self):\n        return \"<Flag {0} for challenge {1}>\".format(self.flag, self.chal)\n\n\nclass Teams(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    name = db.Column(db.String(128), unique=True)\n    email = db.Column(db.String(128), unique=True)\n    password = db.Column(db.String(128))\n    website = db.Column(db.String(128))\n    affiliation = db.Column(db.String(128))\n    country = db.Column(db.String(32))\n    bracket = db.Column(db.String(32))\n    banned = db.Column(db.Boolean, default=False)\n    verified = db.Column(db.Boolean, default=False)\n    admin = db.Column(db.Boolean, default=False)\n    joined = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n\n    def __init__(self, name, email, password):\n        self.name = name\n        self.email = email\n        self.password = bcrypt_sha256.encrypt(str(password))\n\n    def __repr__(self):\n        return '<team %r>' % self.name\n\n    def score(self, admin=False):\n        score = db.func.sum(Challenges.value).label('score')\n        team = db.session.query(Solves.teamid, score).join(Teams).join(Challenges).filter(Teams.banned == False, Teams.id == self.id)\n        award_score = db.func.sum(Awards.value).label('award_score')\n        award = db.session.query(award_score).filter_by(teamid=self.id)\n\n        if not admin:\n            freeze = Config.query.filter_by(key='freeze').first()\n            if freeze and freeze.value:\n                freeze = int(freeze.value)\n                freeze = datetime.datetime.utcfromtimestamp(freeze)\n                team = team.filter(Solves.date < freeze)\n                award = award.filter(Awards.date < freeze)\n\n        team = team.group_by(Solves.teamid).first()\n        award = award.first()\n\n        if team:\n            return int(team.score or 0) + int(award.award_score or 0)\n        else:\n            return 0\n\n    def place(self, admin=False):\n        scores = db.session.query(\n            Solves.teamid.label('teamid'),\n            db.func.sum(Challenges.value).label('score'),\n            db.func.max(Solves.date).label('date')\n        ).join(Challenges).group_by(Solves.teamid)\n\n        awards = db.session.query(\n            Awards.teamid.label('teamid'),\n            db.func.sum(Awards.value).label('score'),\n            db.func.max(Awards.date).label('date')\n        ).group_by(Awards.teamid)\n\n        if not admin:\n            freeze = Config.query.filter_by(key='freeze').first()\n            if freeze and freeze.value:\n                freeze = int(freeze.value)\n                freeze = datetime.datetime.utcfromtimestamp(freeze)\n                scores = scores.filter(Solves.date < freeze)\n                awards = awards.filter(Awards.date < freeze)\n\n        results = union_all(scores, awards).alias('results')\n\n        sumscore = db.func.sum(results.columns.score).label('sumscore')\n        quickest = db.func.max(results.columns.date).label('quickest')\n\n        standings_query = db.session.query(results.columns.teamid)\\\n            .join(Teams)\\\n            .group_by(results.columns.teamid)\\\n            .order_by(sumscore.desc(), quickest)\n\n        if not admin:\n            standings_query = standings_query.filter(Teams.banned == False)\n\n        standings = standings_query.all()\n\n        # http://codegolf.stackexchange.com/a/4712\n        try:\n            i = standings.index((self.id,)) + 1\n            k = i % 10\n            return \"%d%s\" % (i, \"tsnrhtdd\"[(i / 10 % 10 != 1) * (k < 4) * k::4])\n        except ValueError:\n            return 0\n\n\nclass Solves(db.Model):\n    __table_args__ = (db.UniqueConstraint('chalid', 'teamid'), {})\n    id = db.Column(db.Integer, primary_key=True)\n    chalid = db.Column(db.Integer, db.ForeignKey('challenges.id'))\n    teamid = db.Column(db.Integer, db.ForeignKey('teams.id'))\n    ip = db.Column(db.String(46))\n    flag = db.Column(db.Text)\n    date = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n    team = db.relationship('Teams', foreign_keys=\"Solves.teamid\", lazy='joined')\n    chal = db.relationship('Challenges', foreign_keys=\"Solves.chalid\", lazy='joined')\n    # value = db.Column(db.Integer)\n\n    def __init__(self, teamid, chalid, ip, flag):\n        self.ip = ip\n        self.chalid = chalid\n        self.teamid = teamid\n        self.flag = flag\n        # self.value = value\n\n    def __repr__(self):\n        return '<solve {}, {}, {}, {}>'.format(self.teamid, self.chalid, self.ip, self.flag)\n\n\nclass WrongKeys(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    chalid = db.Column(db.Integer, db.ForeignKey('challenges.id'))\n    teamid = db.Column(db.Integer, db.ForeignKey('teams.id'))\n    ip = db.Column(db.String(46))\n    date = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n    flag = db.Column(db.Text)\n    chal = db.relationship('Challenges', foreign_keys=\"WrongKeys.chalid\", lazy='joined')\n\n    def __init__(self, teamid, chalid, ip, flag):\n        self.ip = ip\n        self.teamid = teamid\n        self.chalid = chalid\n        self.flag = flag\n\n    def __repr__(self):\n        return '<wrong {}, {}, {}, {}>'.format(self.teamid, self.chalid, self.ip, self.flag)\n\n\nclass Unlocks(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    teamid = db.Column(db.Integer, db.ForeignKey('teams.id'))\n    date = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n    itemid = db.Column(db.Integer)\n    model = db.Column(db.String(32))\n\n    def __init__(self, model, teamid, itemid):\n        self.model = model\n        self.teamid = teamid\n        self.itemid = itemid\n\n    def __repr__(self):\n        return '<unlock %r>' % self.teamid\n\n\nclass Tracking(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    ip = db.Column(db.String(46))\n    team = db.Column(db.Integer, db.ForeignKey('teams.id'))\n    date = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n\n    def __init__(self, ip, team):\n        self.ip = ip\n        self.team = team\n\n    def __repr__(self):\n        return '<ip %r>' % self.team\n\n\nclass Config(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    key = db.Column(db.Text)\n    value = db.Column(db.Text)\n\n    def __init__(self, key, value):\n        self.key = key\n        self.value = value\n", "path": "CTFd/models.py"}]}