We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Update seed script to add challenge slug
## Current Behaviour:
Currently, when the challenge is created using the seed script, the `slug` field is not populated.

## Expected Behaviour:
When the seed script is run, the `slug` field must be populated with the challenge title and it must include a year in the name to keep it unique like `abc-challenge-2019`

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `scripts/seed.py`
Content:
```
1 # Command to run : python manage.py shell  < scripts/seed.py
2 import os
3 import random
4 import string
5 
6 from datetime import timedelta
7 
8 from django.conf import settings
9 from django.contrib.auth.models import User
10 from django.core.files.uploadedfile import SimpleUploadedFile
11 from django.utils import timezone
12 
13 from allauth.account.models import EmailAddress
14 from faker import Factory
15 
16 from challenges.models import Challenge, ChallengePhase, DatasetSplit, Leaderboard, ChallengePhaseSplit
17 from hosts.models import ChallengeHostTeam, ChallengeHost
18 from participants.models import Participant, ParticipantTeam
19 
20 fake = Factory.create()
21 
22 NUMBER_OF_CHALLENGES = 1
23 NUMBER_OF_PHASES = 2
24 NUMBER_OF_DATASET_SPLITS = 2
25 DATASET_SPLIT_ITERATOR = 0
26 
27 try:
28     xrange          # Python 2
29 except NameError:
30     xrange = range  # Python 3
31 
32 
33 def check_database():
34     if len(EmailAddress.objects.all()) > 0:
35         print("Are you sure you want to wipe the existing development database and reseed it? (Y/N)")
36         if settings.TEST or input().lower() == "y":
37             destroy_database()
38             return True
39         else:
40             return False
41     else:
42         return True
43 
44 
45 def destroy_database():
46     print("Destroying existing database...")
47     print("Destroying Participant objects...")
48     Participant.objects.all().delete()
49     print("Destroying ParticipantTeam objects...")
50     ParticipantTeam.objects.all().delete()
51     print("Destroying ChallengePhaseSplit objects...")
52     ChallengePhaseSplit.objects.all().delete()
53     print("Destroying DatasetSplit objects...")
54     DatasetSplit.objects.all().delete()
55     print("Destroying ChallengePhase objects...")
56     ChallengePhase.objects.all().delete()
57     print("Destroying Leaderboard objects...")
58     Leaderboard.objects.all().delete()
59     print("Destroying Challenge objects...")
60     Challenge.objects.all().delete()
61     print("Destroying ChallengeHostTeam objects...")
62     ChallengeHostTeam.objects.all().delete()
63     print("Destroying ChallengeHost objects...")
64     ChallengeHost.objects.all().delete()
65     print("Destroying User objects...")
66     User.objects.all().delete()
67     print("Destroying EmailAddress objects...")
68     EmailAddress.objects.all().delete()
69     return True
70 
71 
72 def create_user(is_admin, username=""):
73     """
74     Creates superuser, participant user, host user and returns it.
75     """
76     if is_admin:
77         username = "admin"
78         email = "admin@example.com"
79     else:
80         email = "%s@example.com" % (username)
81     user = User.objects.create_user(
82         email=email,
83         username=username,
84         password="password",
85         is_staff=is_admin,
86         is_superuser=is_admin,
87     )
88     EmailAddress.objects.create(user=user, email=email, verified=True, primary=True)
89     print("{} was created with username: {} password: password".format("Super user" if is_admin else "User", username))
90     return user
91 
92 
93 def create_challenge_host_team(user):
94     """
95     Creates challenge host team and returns it.
96     """
97     team_name = "{} Host Team".format(fake.city())
98     team = ChallengeHostTeam.objects.create(
99         team_name=team_name,
100         created_by=user,
101     )
102     print("Challenge Host Team created with team_name: {} created_by: {}".format(team_name, user.username))
103     ChallengeHost.objects.create(user=user, team_name=team, status=ChallengeHost.SELF, permissions=ChallengeHost.ADMIN)
104     print("Challenge Host created with user: {} team_name: {}".format(user.username, team_name))
105     return team
106 
107 
108 def create_challenges(number_of_challenges, host_team=None):
109     """
110     Creates past challenge, on-going challenge and upcoming challenge.
111     """
112     for i in xrange(number_of_challenges):
113         if (i % 3 == 0):
114             create_challenge("{} Challenge".format(fake.first_name()),
115                              timezone.now() - timedelta(days=100),
116                              timezone.now() + timedelta(days=500),
117                              host_team
118                              )
119         elif (i % 3 == 1):
120             create_challenge("{} Challenge".format(fake.first_name()),
121                              timezone.now() - timedelta(days=500),
122                              timezone.now() - timedelta(days=100),
123                              host_team
124                              )
125         elif (i % 3 == 2):
126             create_challenge("{} Challenge".format(fake.first_name()),
127                              timezone.now() + timedelta(days=100),
128                              timezone.now() + timedelta(days=500),
129                              host_team
130                              )
131 
132 
133 def create_challenge(title, start_date, end_date, host_team):
134     """
135     Creates a challenge.
136     """
137     evaluation_script = open(
138         os.path.join(settings.BASE_DIR, 'examples', 'example1', 'sample_evaluation_script.zip'), 'rb')
139     queue = ''.join(random.choice(string.ascii_letters) for _ in range(75))
140     Challenge.objects.create(
141         title=title,
142         short_description=fake.paragraph(),
143         description=fake.paragraph(),
144         terms_and_conditions=fake.paragraph(),
145         submission_guidelines=fake.paragraph(),
146         evaluation_details=fake.paragraph(),
147         evaluation_script=SimpleUploadedFile(evaluation_script.name, evaluation_script.read()),
148         approved_by_admin=True,
149         creator=host_team,
150         published=True,
151         enable_forum=True,
152         anonymous_leaderboard=False,
153         start_date=start_date,
154         end_date=end_date,
155         queue=queue,
156     )
157     print("Challenge created with title: {} creator: {} start_date: {} end_date: {}".format(title,
158                                                                                             host_team.team_name,
159                                                                                             start_date, end_date))
160 
161 
162 def create_challenge_phases(challenge, number_of_phases=1):
163     """
164     Creates challenge phases for the created challenges and returns it.
165     """
166     challenge_phases = []
167     for i in range(number_of_phases):
168         name = "{} Phase".format(fake.first_name())
169         with open(os.path.join(settings.BASE_DIR, 'examples', 'example1', 'test_annotation.txt'), 'rb') as data_file:
170             data = data_file.read()
171         data = data or None
172         challenge_phase = ChallengePhase.objects.create(
173             name=name,
174             description=fake.paragraph(),
175             leaderboard_public=True,
176             is_public=True,
177             start_date=challenge.start_date,
178             end_date=challenge.end_date,
179             challenge=challenge,
180             test_annotation=SimpleUploadedFile(fake.file_name(extension="txt"), data, content_type="text/plain"),
181             codename="{}{}".format("phase", i + 1),
182         )
183         challenge_phases.append(challenge_phase)
184         print("Challenge Phase created with name: {} challenge: {}".format(name, challenge.title))
185     return challenge_phases
186 
187 
188 def create_leaderboard():
189     """
190     Creates Leaderboard schema and returns it.
191     """
192     schema = {
193         'labels': ['score', ],
194         'default_order_by': 'score',
195     }
196     leaderboard = Leaderboard.objects.create(
197         schema=schema
198     )
199     print("Leaderboard created")
200     return leaderboard
201 
202 
203 def create_dataset_splits(number_of_splits):
204     """
205     Creates dataset splits and returns it.
206     """
207     dataset_splits = []
208     for i in range(number_of_splits):
209         global DATASET_SPLIT_ITERATOR
210         name = "Split {}".format(DATASET_SPLIT_ITERATOR + 1)
211         codename = "{}{}".format('split', DATASET_SPLIT_ITERATOR + 1)
212         dataset_split = DatasetSplit.objects.create(
213             name=name,
214             codename=codename,
215         )
216         dataset_splits.append(dataset_split)
217         DATASET_SPLIT_ITERATOR += 1
218         print("Dataset Split created with name: {} codename: {}".format(name, codename))
219     return dataset_splits
220 
221 
222 def create_challenge_phase_splits(challenge_phase, leaderboard, dataset_split):
223     """
224     Creates a challenge phase split.
225     """
226     ChallengePhaseSplit.objects.create(
227         challenge_phase=challenge_phase,
228         leaderboard=leaderboard,
229         dataset_split=dataset_split,
230         visibility=ChallengePhaseSplit.PUBLIC
231     )
232     print("Challenge Phase Split created with challenge_phase: {} dataset_split: {}".format(challenge_phase.name,
233                                                                                             dataset_split.name))
234 
235 
236 def create_participant_team(user):
237     """
238     Creates participant team and returns it.
239     """
240     team_name = "{} Participant Team".format(fake.city())
241     team = ParticipantTeam.objects.create(
242         team_name=team_name,
243         created_by=user,
244     )
245     print("Participant Team created with team_name: {} created_by: {}".format(team_name, user.username))
246     Participant.objects.create(user=user, team=team, status="Self")
247     print("Participant created with user: {} team_name: {}".format(user.username, team_name))
248     return team
249 
250 
251 def run(*args):
252     NUMBER_OF_CHALLENGES = int(args[0])
253     status = check_database()
254     if status is False:
255         print("Seeding aborted.")
256         return 0
257     print("Seeding...")
258     # Create superuser
259     create_user(is_admin=True)
260     # Create host user
261     host_user = create_user(is_admin=False, username="host")
262     # Create challenge host team with challenge host
263     challenge_host_team = create_challenge_host_team(user=host_user)
264     # Create challenge
265     create_challenges(number_of_challenges=NUMBER_OF_CHALLENGES, host_team=challenge_host_team)
266 
267     # Fetch all the created challenges
268     challenges = Challenge.objects.all()
269     for challenge in challenges:
270         # Create a leaderboard object for each challenge
271         leaderboard = create_leaderboard()
272         # Create Phases for a challenge
273         challenge_phases = create_challenge_phases(challenge, number_of_phases=NUMBER_OF_PHASES)
274         # Create Dataset Split for each Challenge
275         dataset_splits = create_dataset_splits(number_of_splits=NUMBER_OF_DATASET_SPLITS)
276         # Create Challenge Phase Split for each Phase and Dataset Split
277         for challenge_phase in challenge_phases:
278             for dataset_split in dataset_splits:
279                 create_challenge_phase_splits(challenge_phase, leaderboard, dataset_split)
280     participant_user = create_user(is_admin=False, username="participant")
281     create_participant_team(user=participant_user)
282     print('Database successfully seeded.')
283
```
--- 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/scripts/seed.py b/scripts/seed.py
--- a/scripts/seed.py
+++ b/scripts/seed.py
@@ -1,4 +1,5 @@
 # Command to run : python manage.py shell  < scripts/seed.py
+import datetime
 import os
 import random
 import string
@@ -137,6 +138,9 @@
     evaluation_script = open(
         os.path.join(settings.BASE_DIR, 'examples', 'example1', 'sample_evaluation_script.zip'), 'rb')
     queue = ''.join(random.choice(string.ascii_letters) for _ in range(75))
+    year = datetime.date.today().year
+    slug = '{t}-{y}'.format(t=title, y=year)
+    slug = slug.lower().replace(" ", "-")
     Challenge.objects.create(
         title=title,
         short_description=fake.paragraph(),
@@ -150,6 +154,7 @@
         published=True,
         enable_forum=True,
         anonymous_leaderboard=False,
+        slug=slug,
         start_date=start_date,
         end_date=end_date,
         queue=queue,

{"golden_diff": "diff --git a/scripts/seed.py b/scripts/seed.py\n--- a/scripts/seed.py\n+++ b/scripts/seed.py\n@@ -1,4 +1,5 @@\n # Command to run : python manage.py shell  < scripts/seed.py\n+import datetime\n import os\n import random\n import string\n@@ -137,6 +138,9 @@\n     evaluation_script = open(\n         os.path.join(settings.BASE_DIR, 'examples', 'example1', 'sample_evaluation_script.zip'), 'rb')\n     queue = ''.join(random.choice(string.ascii_letters) for _ in range(75))\n+    year = datetime.date.today().year\n+    slug = '{t}-{y}'.format(t=title, y=year)\n+    slug = slug.lower().replace(\" \", \"-\")\n     Challenge.objects.create(\n         title=title,\n         short_description=fake.paragraph(),\n@@ -150,6 +154,7 @@\n         published=True,\n         enable_forum=True,\n         anonymous_leaderboard=False,\n+        slug=slug,\n         start_date=start_date,\n         end_date=end_date,\n         queue=queue,\n", "issue": "Update seed script to add challenge slug\n## Current Behaviour:\r\nCurrently, when the challenge is created using the seed script, the `slug` field is not populated.\r\n\r\n## Expected Behaviour:\r\nWhen the seed script is run, the `slug` field must be populated with the challenge title and it must include a year in the name to keep it unique like `abc-challenge-2019`\n", "before_files": [{"content": "# Command to run : python manage.py shell  < scripts/seed.py\nimport os\nimport random\nimport string\n\nfrom datetime import timedelta\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.utils import timezone\n\nfrom allauth.account.models import EmailAddress\nfrom faker import Factory\n\nfrom challenges.models import Challenge, ChallengePhase, DatasetSplit, Leaderboard, ChallengePhaseSplit\nfrom hosts.models import ChallengeHostTeam, ChallengeHost\nfrom participants.models import Participant, ParticipantTeam\n\nfake = Factory.create()\n\nNUMBER_OF_CHALLENGES = 1\nNUMBER_OF_PHASES = 2\nNUMBER_OF_DATASET_SPLITS = 2\nDATASET_SPLIT_ITERATOR = 0\n\ntry:\n    xrange          # Python 2\nexcept NameError:\n    xrange = range  # Python 3\n\n\ndef check_database():\n    if len(EmailAddress.objects.all()) > 0:\n        print(\"Are you sure you want to wipe the existing development database and reseed it? (Y/N)\")\n        if settings.TEST or input().lower() == \"y\":\n            destroy_database()\n            return True\n        else:\n            return False\n    else:\n        return True\n\n\ndef destroy_database():\n    print(\"Destroying existing database...\")\n    print(\"Destroying Participant objects...\")\n    Participant.objects.all().delete()\n    print(\"Destroying ParticipantTeam objects...\")\n    ParticipantTeam.objects.all().delete()\n    print(\"Destroying ChallengePhaseSplit objects...\")\n    ChallengePhaseSplit.objects.all().delete()\n    print(\"Destroying DatasetSplit objects...\")\n    DatasetSplit.objects.all().delete()\n    print(\"Destroying ChallengePhase objects...\")\n    ChallengePhase.objects.all().delete()\n    print(\"Destroying Leaderboard objects...\")\n    Leaderboard.objects.all().delete()\n    print(\"Destroying Challenge objects...\")\n    Challenge.objects.all().delete()\n    print(\"Destroying ChallengeHostTeam objects...\")\n    ChallengeHostTeam.objects.all().delete()\n    print(\"Destroying ChallengeHost objects...\")\n    ChallengeHost.objects.all().delete()\n    print(\"Destroying User objects...\")\n    User.objects.all().delete()\n    print(\"Destroying EmailAddress objects...\")\n    EmailAddress.objects.all().delete()\n    return True\n\n\ndef create_user(is_admin, username=\"\"):\n    \"\"\"\n    Creates superuser, participant user, host user and returns it.\n    \"\"\"\n    if is_admin:\n        username = \"admin\"\n        email = \"admin@example.com\"\n    else:\n        email = \"%s@example.com\" % (username)\n    user = User.objects.create_user(\n        email=email,\n        username=username,\n        password=\"password\",\n        is_staff=is_admin,\n        is_superuser=is_admin,\n    )\n    EmailAddress.objects.create(user=user, email=email, verified=True, primary=True)\n    print(\"{} was created with username: {} password: password\".format(\"Super user\" if is_admin else \"User\", username))\n    return user\n\n\ndef create_challenge_host_team(user):\n    \"\"\"\n    Creates challenge host team and returns it.\n    \"\"\"\n    team_name = \"{} Host Team\".format(fake.city())\n    team = ChallengeHostTeam.objects.create(\n        team_name=team_name,\n        created_by=user,\n    )\n    print(\"Challenge Host Team created with team_name: {} created_by: {}\".format(team_name, user.username))\n    ChallengeHost.objects.create(user=user, team_name=team, status=ChallengeHost.SELF, permissions=ChallengeHost.ADMIN)\n    print(\"Challenge Host created with user: {} team_name: {}\".format(user.username, team_name))\n    return team\n\n\ndef create_challenges(number_of_challenges, host_team=None):\n    \"\"\"\n    Creates past challenge, on-going challenge and upcoming challenge.\n    \"\"\"\n    for i in xrange(number_of_challenges):\n        if (i % 3 == 0):\n            create_challenge(\"{} Challenge\".format(fake.first_name()),\n                             timezone.now() - timedelta(days=100),\n                             timezone.now() + timedelta(days=500),\n                             host_team\n                             )\n        elif (i % 3 == 1):\n            create_challenge(\"{} Challenge\".format(fake.first_name()),\n                             timezone.now() - timedelta(days=500),\n                             timezone.now() - timedelta(days=100),\n                             host_team\n                             )\n        elif (i % 3 == 2):\n            create_challenge(\"{} Challenge\".format(fake.first_name()),\n                             timezone.now() + timedelta(days=100),\n                             timezone.now() + timedelta(days=500),\n                             host_team\n                             )\n\n\ndef create_challenge(title, start_date, end_date, host_team):\n    \"\"\"\n    Creates a challenge.\n    \"\"\"\n    evaluation_script = open(\n        os.path.join(settings.BASE_DIR, 'examples', 'example1', 'sample_evaluation_script.zip'), 'rb')\n    queue = ''.join(random.choice(string.ascii_letters) for _ in range(75))\n    Challenge.objects.create(\n        title=title,\n        short_description=fake.paragraph(),\n        description=fake.paragraph(),\n        terms_and_conditions=fake.paragraph(),\n        submission_guidelines=fake.paragraph(),\n        evaluation_details=fake.paragraph(),\n        evaluation_script=SimpleUploadedFile(evaluation_script.name, evaluation_script.read()),\n        approved_by_admin=True,\n        creator=host_team,\n        published=True,\n        enable_forum=True,\n        anonymous_leaderboard=False,\n        start_date=start_date,\n        end_date=end_date,\n        queue=queue,\n    )\n    print(\"Challenge created with title: {} creator: {} start_date: {} end_date: {}\".format(title,\n                                                                                            host_team.team_name,\n                                                                                            start_date, end_date))\n\n\ndef create_challenge_phases(challenge, number_of_phases=1):\n    \"\"\"\n    Creates challenge phases for the created challenges and returns it.\n    \"\"\"\n    challenge_phases = []\n    for i in range(number_of_phases):\n        name = \"{} Phase\".format(fake.first_name())\n        with open(os.path.join(settings.BASE_DIR, 'examples', 'example1', 'test_annotation.txt'), 'rb') as data_file:\n            data = data_file.read()\n        data = data or None\n        challenge_phase = ChallengePhase.objects.create(\n            name=name,\n            description=fake.paragraph(),\n            leaderboard_public=True,\n            is_public=True,\n            start_date=challenge.start_date,\n            end_date=challenge.end_date,\n            challenge=challenge,\n            test_annotation=SimpleUploadedFile(fake.file_name(extension=\"txt\"), data, content_type=\"text/plain\"),\n            codename=\"{}{}\".format(\"phase\", i + 1),\n        )\n        challenge_phases.append(challenge_phase)\n        print(\"Challenge Phase created with name: {} challenge: {}\".format(name, challenge.title))\n    return challenge_phases\n\n\ndef create_leaderboard():\n    \"\"\"\n    Creates Leaderboard schema and returns it.\n    \"\"\"\n    schema = {\n        'labels': ['score', ],\n        'default_order_by': 'score',\n    }\n    leaderboard = Leaderboard.objects.create(\n        schema=schema\n    )\n    print(\"Leaderboard created\")\n    return leaderboard\n\n\ndef create_dataset_splits(number_of_splits):\n    \"\"\"\n    Creates dataset splits and returns it.\n    \"\"\"\n    dataset_splits = []\n    for i in range(number_of_splits):\n        global DATASET_SPLIT_ITERATOR\n        name = \"Split {}\".format(DATASET_SPLIT_ITERATOR + 1)\n        codename = \"{}{}\".format('split', DATASET_SPLIT_ITERATOR + 1)\n        dataset_split = DatasetSplit.objects.create(\n            name=name,\n            codename=codename,\n        )\n        dataset_splits.append(dataset_split)\n        DATASET_SPLIT_ITERATOR += 1\n        print(\"Dataset Split created with name: {} codename: {}\".format(name, codename))\n    return dataset_splits\n\n\ndef create_challenge_phase_splits(challenge_phase, leaderboard, dataset_split):\n    \"\"\"\n    Creates a challenge phase split.\n    \"\"\"\n    ChallengePhaseSplit.objects.create(\n        challenge_phase=challenge_phase,\n        leaderboard=leaderboard,\n        dataset_split=dataset_split,\n        visibility=ChallengePhaseSplit.PUBLIC\n    )\n    print(\"Challenge Phase Split created with challenge_phase: {} dataset_split: {}\".format(challenge_phase.name,\n                                                                                            dataset_split.name))\n\n\ndef create_participant_team(user):\n    \"\"\"\n    Creates participant team and returns it.\n    \"\"\"\n    team_name = \"{} Participant Team\".format(fake.city())\n    team = ParticipantTeam.objects.create(\n        team_name=team_name,\n        created_by=user,\n    )\n    print(\"Participant Team created with team_name: {} created_by: {}\".format(team_name, user.username))\n    Participant.objects.create(user=user, team=team, status=\"Self\")\n    print(\"Participant created with user: {} team_name: {}\".format(user.username, team_name))\n    return team\n\n\ndef run(*args):\n    NUMBER_OF_CHALLENGES = int(args[0])\n    status = check_database()\n    if status is False:\n        print(\"Seeding aborted.\")\n        return 0\n    print(\"Seeding...\")\n    # Create superuser\n    create_user(is_admin=True)\n    # Create host user\n    host_user = create_user(is_admin=False, username=\"host\")\n    # Create challenge host team with challenge host\n    challenge_host_team = create_challenge_host_team(user=host_user)\n    # Create challenge\n    create_challenges(number_of_challenges=NUMBER_OF_CHALLENGES, host_team=challenge_host_team)\n\n    # Fetch all the created challenges\n    challenges = Challenge.objects.all()\n    for challenge in challenges:\n        # Create a leaderboard object for each challenge\n        leaderboard = create_leaderboard()\n        # Create Phases for a challenge\n        challenge_phases = create_challenge_phases(challenge, number_of_phases=NUMBER_OF_PHASES)\n        # Create Dataset Split for each Challenge\n        dataset_splits = create_dataset_splits(number_of_splits=NUMBER_OF_DATASET_SPLITS)\n        # Create Challenge Phase Split for each Phase and Dataset Split\n        for challenge_phase in challenge_phases:\n            for dataset_split in dataset_splits:\n                create_challenge_phase_splits(challenge_phase, leaderboard, dataset_split)\n    participant_user = create_user(is_admin=False, username=\"participant\")\n    create_participant_team(user=participant_user)\n    print('Database successfully seeded.')\n", "path": "scripts/seed.py"}], "after_files": [{"content": "# Command to run : python manage.py shell  < scripts/seed.py\nimport datetime\nimport os\nimport random\nimport string\n\nfrom datetime import timedelta\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.utils import timezone\n\nfrom allauth.account.models import EmailAddress\nfrom faker import Factory\n\nfrom challenges.models import Challenge, ChallengePhase, DatasetSplit, Leaderboard, ChallengePhaseSplit\nfrom hosts.models import ChallengeHostTeam, ChallengeHost\nfrom participants.models import Participant, ParticipantTeam\n\nfake = Factory.create()\n\nNUMBER_OF_CHALLENGES = 1\nNUMBER_OF_PHASES = 2\nNUMBER_OF_DATASET_SPLITS = 2\nDATASET_SPLIT_ITERATOR = 0\n\ntry:\n    xrange          # Python 2\nexcept NameError:\n    xrange = range  # Python 3\n\n\ndef check_database():\n    if len(EmailAddress.objects.all()) > 0:\n        print(\"Are you sure you want to wipe the existing development database and reseed it? (Y/N)\")\n        if settings.TEST or input().lower() == \"y\":\n            destroy_database()\n            return True\n        else:\n            return False\n    else:\n        return True\n\n\ndef destroy_database():\n    print(\"Destroying existing database...\")\n    print(\"Destroying Participant objects...\")\n    Participant.objects.all().delete()\n    print(\"Destroying ParticipantTeam objects...\")\n    ParticipantTeam.objects.all().delete()\n    print(\"Destroying ChallengePhaseSplit objects...\")\n    ChallengePhaseSplit.objects.all().delete()\n    print(\"Destroying DatasetSplit objects...\")\n    DatasetSplit.objects.all().delete()\n    print(\"Destroying ChallengePhase objects...\")\n    ChallengePhase.objects.all().delete()\n    print(\"Destroying Leaderboard objects...\")\n    Leaderboard.objects.all().delete()\n    print(\"Destroying Challenge objects...\")\n    Challenge.objects.all().delete()\n    print(\"Destroying ChallengeHostTeam objects...\")\n    ChallengeHostTeam.objects.all().delete()\n    print(\"Destroying ChallengeHost objects...\")\n    ChallengeHost.objects.all().delete()\n    print(\"Destroying User objects...\")\n    User.objects.all().delete()\n    print(\"Destroying EmailAddress objects...\")\n    EmailAddress.objects.all().delete()\n    return True\n\n\ndef create_user(is_admin, username=\"\"):\n    \"\"\"\n    Creates superuser, participant user, host user and returns it.\n    \"\"\"\n    if is_admin:\n        username = \"admin\"\n        email = \"admin@example.com\"\n    else:\n        email = \"%s@example.com\" % (username)\n    user = User.objects.create_user(\n        email=email,\n        username=username,\n        password=\"password\",\n        is_staff=is_admin,\n        is_superuser=is_admin,\n    )\n    EmailAddress.objects.create(user=user, email=email, verified=True, primary=True)\n    print(\"{} was created with username: {} password: password\".format(\"Super user\" if is_admin else \"User\", username))\n    return user\n\n\ndef create_challenge_host_team(user):\n    \"\"\"\n    Creates challenge host team and returns it.\n    \"\"\"\n    team_name = \"{} Host Team\".format(fake.city())\n    team = ChallengeHostTeam.objects.create(\n        team_name=team_name,\n        created_by=user,\n    )\n    print(\"Challenge Host Team created with team_name: {} created_by: {}\".format(team_name, user.username))\n    ChallengeHost.objects.create(user=user, team_name=team, status=ChallengeHost.SELF, permissions=ChallengeHost.ADMIN)\n    print(\"Challenge Host created with user: {} team_name: {}\".format(user.username, team_name))\n    return team\n\n\ndef create_challenges(number_of_challenges, host_team=None):\n    \"\"\"\n    Creates past challenge, on-going challenge and upcoming challenge.\n    \"\"\"\n    for i in xrange(number_of_challenges):\n        if (i % 3 == 0):\n            create_challenge(\"{} Challenge\".format(fake.first_name()),\n                             timezone.now() - timedelta(days=100),\n                             timezone.now() + timedelta(days=500),\n                             host_team\n                             )\n        elif (i % 3 == 1):\n            create_challenge(\"{} Challenge\".format(fake.first_name()),\n                             timezone.now() - timedelta(days=500),\n                             timezone.now() - timedelta(days=100),\n                             host_team\n                             )\n        elif (i % 3 == 2):\n            create_challenge(\"{} Challenge\".format(fake.first_name()),\n                             timezone.now() + timedelta(days=100),\n                             timezone.now() + timedelta(days=500),\n                             host_team\n                             )\n\n\ndef create_challenge(title, start_date, end_date, host_team):\n    \"\"\"\n    Creates a challenge.\n    \"\"\"\n    evaluation_script = open(\n        os.path.join(settings.BASE_DIR, 'examples', 'example1', 'sample_evaluation_script.zip'), 'rb')\n    queue = ''.join(random.choice(string.ascii_letters) for _ in range(75))\n    year = datetime.date.today().year\n    slug = '{t}-{y}'.format(t=title, y=year)\n    slug = slug.lower().replace(\" \", \"-\")\n    Challenge.objects.create(\n        title=title,\n        short_description=fake.paragraph(),\n        description=fake.paragraph(),\n        terms_and_conditions=fake.paragraph(),\n        submission_guidelines=fake.paragraph(),\n        evaluation_details=fake.paragraph(),\n        evaluation_script=SimpleUploadedFile(evaluation_script.name, evaluation_script.read()),\n        approved_by_admin=True,\n        creator=host_team,\n        published=True,\n        enable_forum=True,\n        anonymous_leaderboard=False,\n        slug=slug,\n        start_date=start_date,\n        end_date=end_date,\n        queue=queue,\n    )\n    print(\"Challenge created with title: {} creator: {} start_date: {} end_date: {}\".format(title,\n                                                                                            host_team.team_name,\n                                                                                            start_date, end_date))\n\n\ndef create_challenge_phases(challenge, number_of_phases=1):\n    \"\"\"\n    Creates challenge phases for the created challenges and returns it.\n    \"\"\"\n    challenge_phases = []\n    for i in range(number_of_phases):\n        name = \"{} Phase\".format(fake.first_name())\n        with open(os.path.join(settings.BASE_DIR, 'examples', 'example1', 'test_annotation.txt'), 'rb') as data_file:\n            data = data_file.read()\n        data = data or None\n        challenge_phase = ChallengePhase.objects.create(\n            name=name,\n            description=fake.paragraph(),\n            leaderboard_public=True,\n            is_public=True,\n            start_date=challenge.start_date,\n            end_date=challenge.end_date,\n            challenge=challenge,\n            test_annotation=SimpleUploadedFile(fake.file_name(extension=\"txt\"), data, content_type=\"text/plain\"),\n            codename=\"{}{}\".format(\"phase\", i + 1),\n        )\n        challenge_phases.append(challenge_phase)\n        print(\"Challenge Phase created with name: {} challenge: {}\".format(name, challenge.title))\n    return challenge_phases\n\n\ndef create_leaderboard():\n    \"\"\"\n    Creates Leaderboard schema and returns it.\n    \"\"\"\n    schema = {\n        'labels': ['score', ],\n        'default_order_by': 'score',\n    }\n    leaderboard = Leaderboard.objects.create(\n        schema=schema\n    )\n    print(\"Leaderboard created\")\n    return leaderboard\n\n\ndef create_dataset_splits(number_of_splits):\n    \"\"\"\n    Creates dataset splits and returns it.\n    \"\"\"\n    dataset_splits = []\n    for i in range(number_of_splits):\n        global DATASET_SPLIT_ITERATOR\n        name = \"Split {}\".format(DATASET_SPLIT_ITERATOR + 1)\n        codename = \"{}{}\".format('split', DATASET_SPLIT_ITERATOR + 1)\n        dataset_split = DatasetSplit.objects.create(\n            name=name,\n            codename=codename,\n        )\n        dataset_splits.append(dataset_split)\n        DATASET_SPLIT_ITERATOR += 1\n        print(\"Dataset Split created with name: {} codename: {}\".format(name, codename))\n    return dataset_splits\n\n\ndef create_challenge_phase_splits(challenge_phase, leaderboard, dataset_split):\n    \"\"\"\n    Creates a challenge phase split.\n    \"\"\"\n    ChallengePhaseSplit.objects.create(\n        challenge_phase=challenge_phase,\n        leaderboard=leaderboard,\n        dataset_split=dataset_split,\n        visibility=ChallengePhaseSplit.PUBLIC\n    )\n    print(\"Challenge Phase Split created with challenge_phase: {} dataset_split: {}\".format(challenge_phase.name,\n                                                                                            dataset_split.name))\n\n\ndef create_participant_team(user):\n    \"\"\"\n    Creates participant team and returns it.\n    \"\"\"\n    team_name = \"{} Participant Team\".format(fake.city())\n    team = ParticipantTeam.objects.create(\n        team_name=team_name,\n        created_by=user,\n    )\n    print(\"Participant Team created with team_name: {} created_by: {}\".format(team_name, user.username))\n    Participant.objects.create(user=user, team=team, status=\"Self\")\n    print(\"Participant created with user: {} team_name: {}\".format(user.username, team_name))\n    return team\n\n\ndef run(*args):\n    NUMBER_OF_CHALLENGES = int(args[0])\n    status = check_database()\n    if status is False:\n        print(\"Seeding aborted.\")\n        return 0\n    print(\"Seeding...\")\n    # Create superuser\n    create_user(is_admin=True)\n    # Create host user\n    host_user = create_user(is_admin=False, username=\"host\")\n    # Create challenge host team with challenge host\n    challenge_host_team = create_challenge_host_team(user=host_user)\n    # Create challenge\n    create_challenges(number_of_challenges=NUMBER_OF_CHALLENGES, host_team=challenge_host_team)\n\n    # Fetch all the created challenges\n    challenges = Challenge.objects.all()\n    for challenge in challenges:\n        # Create a leaderboard object for each challenge\n        leaderboard = create_leaderboard()\n        # Create Phases for a challenge\n        challenge_phases = create_challenge_phases(challenge, number_of_phases=NUMBER_OF_PHASES)\n        # Create Dataset Split for each Challenge\n        dataset_splits = create_dataset_splits(number_of_splits=NUMBER_OF_DATASET_SPLITS)\n        # Create Challenge Phase Split for each Phase and Dataset Split\n        for challenge_phase in challenge_phases:\n            for dataset_split in dataset_splits:\n                create_challenge_phase_splits(challenge_phase, leaderboard, dataset_split)\n    participant_user = create_user(is_admin=False, username=\"participant\")\n    create_participant_team(user=participant_user)\n    print('Database successfully seeded.')\n", "path": "scripts/seed.py"}]}