Example #1
0
def create_challenge(challenge: Challenge) -> JSONResponse:
    """
    Adds a new challenge.
    :param challenge: the challenge information
    :return: status code and response data
    """
    db = _get_db()
    challenge.challenge_id = db["challenges"].find().count() + 1
    db["challenges"].insert_one(challenge.to_dict())
    return JSONResponse(status_code=status.HTTP_201_CREATED, content=dumps([]))
Example #2
0
def edit(request):
    if request.method == 'POST':
        title = request.POST['title']
        desc = request.POST['desc']

        ch = Challenge(title = title, desc = desc)
        ch.save()

        return HttpResponseRedirect(reverse('challenges'))

    return render(request, 'edit_form.html')
Example #3
0
def make_challenge(request, username):
    user = get_user(username)
    done = False
    while not done:
        try:
            challenge = Challenge(destination=user)
            challenge.save()
            done = True
        except IntegrityError:
            pass
    # occasional cleanup
    if challenge.code[1] == "0":
        Challenge.objects.filter(valid_until__lt=datetime.now()).delete()
    return HttpResponse(challenge.code)
Example #4
0
 def post(self, *args, **kwargs):
     user = User.by_user_name(self.session.data['user_name'])
     try:
         token = self.get_argument("token")
         challenge = Challenge.get_by_id(self.get_argument("challenge"))
     except:
         self.render("user/error.html", operation = "Submit Challenge", errors = "Please enter a token")    
     if user.team != None:
         if not challenge in user.team.challenges:
             if token == challenge.token:
                 action = Action(
                     classification = unicode("Challenge Completed"),
                     description = unicode(user.user_name+" has succesfully completed "+challenge.name+" !"),
                     value = challenge.value,
                     user_id = user.id
                 )
                 challenge.teams.append(user.team)
                 self.dbsession.add(challenge)
                 self.dbsession.add(action)
                 self.dbsession.flush()
                 self.redirect('/challenge')
             else:
                 self.render("user/error.html", operation = "Submit Challenge", errors = "Invalid Token")
         else:
             self.render("user/error.html", operation = "Submit Challenge", errors = "This challenge was already completed")
     else:
         self.render("user/error.html", operation = "Submit Challenge", errors = "You're not on a team")
Example #5
0
def launch(request, to_id):
    user_to = get_object_or_404(Player, pk=to_id)

    user_to = user_to.get_extension(ChallengeUser)

    user_from = request.user.get_profile().get_extension(ChallengeUser)

    if ChallengeGame.disabled():
        return do_result(request, error='Provocarile sunt dezactivate')

    if (not user_to.is_eligible()) or (not user_from.is_eligible()):
        return do_result(request, error='Ne pare rau, doar studentii de anul I pot provoca/fi provocati')

    if not user_from.can_launch():
        return do_result(request, _('You cannot launch another challenge today.'))

    if not user_from.has_enough_points():
        return do_result(request, _('You need at least 30 points to launch a challenge'))

    if user_from.can_challenge(user_to):
        try:
            chall = Challenge.create(user_from=user_from, user_to=user_to)
        except ChallengeException as e:
            # Some error occurred during question fetch. Clean up, and display error
            return do_result(request, e.message)
        #Checking if user_to is stored in session
        PREFIX = "_user:"******"multiple-login"
        if (PREFIX + user_to.user.username) in request.session:
            from wouso.interface.activity.signals import addActivity
            addActivity.send(sender=None, user_to=user_to, user_from=user_from, action=action_msg,
                             game=None, public=False)
        return do_result(request, message=_('Successfully challenged'))
    else:
        return do_result(request, _('This user cannot be challenged.'))
Example #6
0
def launch(request, to_id):
    user_to = get_object_or_404(Player, pk=to_id)

    user_to = user_to.get_extension(ChallengeUser)

    user_from = request.user.get_profile().get_extension(ChallengeUser)

    if ChallengeGame.disabled():
        return do_result(request, error='Provocarile sunt dezactivate')

    if (not user_to.is_eligible()) or (not user_from.is_eligible()):
        return do_result(request, error='Ne pare rau, doar studentii de anul I pot provoca/fi provocati')

    if not user_from.can_launch():
        return do_result(request, _('You cannot launch another challenge today.'))

    if not user_from.has_enough_points():
        return do_result(request, _('You need at least 30 points to launch a challenge'))

    if user_from.can_challenge(user_to):
        try:
            chall = Challenge.create(user_from=user_from, user_to=user_to)
        except ChallengeException as e:
            # Some error occurred during question fetch. Clean up, and display error
            return do_result(request, e.message)
        return do_result(request, message=_('Successfully challenged'))
    else:
        return do_result(request, _('This user cannot be challenged.'))
Example #7
0
def launch(request, to_id):
    user_to = get_object_or_404(Player, pk=to_id)

    user_to = user_to.get_extension(ChallengeUser)

    user_from = request.user.get_profile().get_extension(ChallengeUser)

    if ChallengeGame.disabled():
        return do_result(request, error='Provocarile sunt dezactivate')

    if (not user_to.is_eligible()) or (not user_from.is_eligible()):
        return do_result(request, error=_('Sorry, challenge failed.'))

    if not user_from.can_launch():
        return do_result(request, _('You cannot launch another challenge today.'))

    if not user_from.has_enough_points():
        return do_result(request, _('You need at least 30 points to launch a challenge'))

    if user_from.can_challenge(user_to):
        try:
            chall = Challenge.create(user_from=user_from, user_to=user_to)
        except ChallengeException as e:
            # Some error occurred during question fetch. Clean up, and display error
            return do_result(request, e.message)
        #Checking if user_to is stored in session
        PREFIX = "_user:"******"multiple-login"
        if (PREFIX + user_to.user.username) in request.session:
            from wouso.core.signals import addActivity
            addActivity.send(sender=None, user_to=user_to, user_from=user_from, action=action_msg,
                             game=None, public=False)
        return do_result(request, message=_('Successfully challenged'))
    else:
        return do_result(request, _('This user cannot be challenged.'))
Example #8
0
def launch(request, to_id):
    user_to = get_object_or_404(Player, pk=to_id)

    user_to = user_to.get_extension(ChallengeUser)

    user_from = request.user.get_profile().get_extension(ChallengeUser)

    if (not user_to.is_eligible()) or (not user_from.is_eligible()):
        return do_result(request, error='Ne pare rau, doar studentii de anul I pot provoca/fi provocati')

    if not user_from.can_launch():
        return do_result(request, _('You cannot launch another challenge today.'))

    if not user_from.has_enough_points():
        return do_result(request, _('You need at least 30 points to launch a challenge'))

    if user_from.can_challenge(user_to):
        try:
            chall = Challenge.create(user_from=user_from, user_to=user_to)
        except ValueError as e:
            # Some error occurred during question fetch. Clean up, and display error
            return do_result(request, e.message)
        return do_result(request, message=_('Successfully challenged'))
    else:
        return do_result(request, _('This user cannot be challenged.'))
Example #9
0
    def test_challengeUpdateCompletedOperation(self):

        # check that error raised when record does not exist
        print('--- check that error raised when record does not exist')
        self.assertRaises(ErrorWithCode, challengeUpdateCompletedOperation, 1,
                          2, 2, 1)

        # adding challenge
        challenge = Challenge(1, 2, 2)
        db.session.add(challenge)
        db.session.commit()

        # check that when successful, result returned by function is of the correct type
        print(
            '--- check that when successful, result returned by function is of the correct type'
        )
        challenge = Challenge.query.filter_by(from_student_id=1).filter_by(
            to_student_id=2).filter_by(quiz_id=1).first()
        self.assertEqual(challenge.is_completed, False)
        self.assertIsNone(challenge.winner_id)

        challengeUpdateCompletedOperation(1, 2, 1, 1)
        challenge = Challenge.query.filter_by(from_student_id=1).filter_by(
            to_student_id=2).filter_by(quiz_id=1).first()
        self.assertEqual(challenge.is_completed, True)
        self.assertEqual(challenge.winner_id, 1)
Example #10
0
def challenge_list_json(request):
    challenges = []
    for challenge in Challenge.current_challenges():
        challenges.append({'id': challenge.id,
                           'name': challenge.name,
                           'short_name': challenge.short_name})
    return JsonResponse({'challenges': challenges})
Example #11
0
	def get(self):
		user = users.get_current_user()
		if(user):
			userQuery = User.query(User.userid == user.user_id())

			userEntity = None

			for thisUser in userQuery:
				userEntity = thisUser
				formCheck(self, user)
				missedLectureCheck(user)
				if userEntity.email is None:
					userEntity.email = user.email()
					userEntity.put()

			if userEntity is None:
				userEntity = User(
					userid=user.user_id(),
					score=0,
					streak=0,
					count=0,
					history=[],
					email = user.email())

				module1Query = Module.query(Module.code == 'GENG0013')
				for module in module1Query:
					for lecture in module.lectures:
						userEntity.lectures.append(lecture)

				module2Query = Module.query(Module.code == 'GENG0002')
				for module in module2Query:
					for lecture in module.lectures:
						userEntity.lectures.append(lecture)

				challengeQuery = Challenge.query().order(Challenge.challengeid)
				for challenge in challengeQuery:
					userEntity.challenges.append(challenge)

				userEntity.put()
				self.redirect('/info')

			completedChalls = []

			for challenge in userEntity.challenges:
				if challenge.complete:
					completedChalls.append(challenge)

			template_values = {
				'username' : userEntity.username,
				'logout' : users.create_logout_url(self.request.uri),
				'score' : userEntity.score,
				'count' : userEntity.count,
				'streak' : userEntity.streak,
				'completedChalls' : completedChalls
			}
			template = JINJA_ENVIRONMENT.get_template('/assets/home.html')
			self.response.write(template.render(template_values))

		else:
			self.redirect(users.create_login_url(self.request.uri))
Example #12
0
 def get(self, *args, **kwargs):
     user = User.by_user_name(self.session.data['user_name'])
     all_challenges = Challenge.get_all()
     correct_challenges = []
     for challenge in all_challenges:
         if user.team != None:
             if not challenge in user.team.challenges:
                 correct_challenges.append(challenge)          
     self.render("user/challenge.html", challenges = correct_challenges)
Example #13
0
def login(request):
    if 'key' in request.COOKIES:
        try:
            user = User.objects.get(sessionID=request.COOKIES['key'])
            return HttpResponseRedirect("/main")
        except User.DoesNotExist:
            pass
    rkey = randomkey()
    key = Challenge(key=rkey, ip=request.META['REMOTE_ADDR'])
    key.save()
    message = ""
    if 'msg' in request.GET:
        message = msgdict[request.GET['msg']]
    t = loader.get_template('aponurho/login.html')
    c = RequestContext(request, {
            'challenge': rkey,
            'message': message
            })
    return HttpResponse(t.render(c))
Example #14
0
def api_get_challenge_create():
    """
    创建新挑战,返回挑战id

    """
    max_level = db.session.query(func.max(Challenge.level)).one_or_none()[0]
    challenge = Challenge(level=(1 if not max_level else max_level + 1))
    db.session.add(challenge)
    db.session.commit()
    return make_response(0, id=challenge.id)
Example #15
0
def create_challenge():
    dat = json.loads(request.data)
    text = dat.get("text")
    GIPHY_SEARCH_PARAMETERS = {
        'api_key': GIPHY_API_KEY,
        'limit': 1,
        # default
        'q': text
    }
    giphy_dat = requests.get(GIPHY_SEARCH_URL,
                             params=GIPHY_SEARCH_PARAMETERS).json()
    challenge = Challenge(
        text=text,
        imgURL=giphy_dat['data'][0]['images']['fixed_height']['url'],
        timeToFinish=dat.get("timeToFinish"))
    db.session.add(challenge)
    db.session.commit()
    res = {'success': True, 'data': challenge.serialize()}

    return json.dumps(res), 201
Example #16
0
    def setUp(self):
        print('\r')
        # drop all tables in the database
        db.session.remove()
        db.drop_all()
        # crete all tables in the database
        db.create_all()

        # adding users
        user_1 = User('*****@*****.**', encrypt('password'), 'student_1')
        student_1 = Student(user_1, 'U00000000A')
        db.session.add(student_1)

        user_2 = User('*****@*****.**', encrypt('password'), 'student_2')
        student_2 = Student(user_2, 'U00000000B')
        db.session.add(student_2)

        user_3 = User('*****@*****.**', encrypt('password'), 'teacher_1')
        staff_1 = Staff(user_3)
        db.session.add(staff_1)

        # adding topics
        topic = Topic(name='seng')
        db.session.add(topic)

        # adding lessons
        lesson = Lesson(1, 1, 'lesson_1', 'content')
        db.session.add(lesson)

        # adding quizzes
        quiz_1 = Quiz(3, 'quiz_1', True, '2020-03-30', '2020-03-31')
        db.session.add(quiz_1)

        quiz_2 = Quiz(3, 'quiz_2', True, '2020-03-30', '2020-03-31')
        db.session.add(quiz_2)

        # adding questions
        question_1 = Question(1, 1, 'question_1')
        db.session.add(question_1)

        question_2 = Question(1, 1, 'question_2')
        db.session.add(question_2)

        question_3 = Question(1, 1, 'question_3')
        db.session.add(question_3)

        question_4 = Question(1, 1, 'question_4')
        db.session.add(question_4)

        # adding challenges
        challenge = Challenge(1, 2, 1)
        db.session.add(challenge)

        db.session.commit()
Example #17
0
def update_challenge(challenge: Challenge) -> JSONResponse:
    """
    Updates a challenge.
    :param challenge: the challenge information
    :return: status code and response data
    """
    _get_db()["challenges"].update_one(
        {"challenge_id": challenge.challenge_id},
        {"$set": challenge.to_dict()})
    return JSONResponse(status_code=status.HTTP_204_NO_CONTENT,
                        content=dumps([]))
Example #18
0
def new_challenge():
    if request.method == 'POST' and len(request.form) >= 6:
        if logged_in():
            errors = []
            #try:
            eid = request.form['eid']
            name = request.form['name']
            category = request.form['category']
            value = int(request.form['value'])
            desc = request.form['description']
            #except:

            if len(errors) > 0:
                return "Failed to add challenge [2]"
            else:
                new_chal = Challenge(eid, name, category, desc, value)
                db.session.add(new_chal)
                db.session.commit()

                cid = new_chal.cid
                #try:
                files = request.files.getlist('file[]')
                if files and len(files) > 0:
                    for f in files:
                        if f and len(f.filename) > 0:
                            #try:
                            upload_file(f)
                            new_file = File(cid, f.filename)
                            db.session.add(new_file)
                            db.session.commit()
                            #except:
                        #errors.append("Something went wrong")
                        else:
                            errors.append(
                                "Error: something wrong with the file or filename"
                            )
                    #except:
                    #    errors.append("No files recieved")

                db.session.close()
                return redirect('/event/{}'.format(eid))
        else:
            flash('Must be logged in to create challenges')
            return redirect(url_for('auth.login'))
    else:
        return "Failed to add challenge"
Example #19
0
    def test_challengeUpdate(self):

        # create a new Challenge object and add it to the database
        challenge = Challenge(1, 2, 1)
        db.session.add(challenge)
        db.session.commit()

        # update value of Topic object
        Challenge.query.filter_by(from_student_id=1).filter_by(
            to_student_id=2).filter_by(quiz_id=1).first().is_completed = True
        challengeUpdate()

        # check if value of Topic object has been updated
        print('--- check if value of Topic object has been updated')
        self.assertEqual(
            Challenge.query.filter_by(from_student_id=1).filter_by(
                to_student_id=2).filter_by(quiz_id=1).first().is_completed,
            True)
Example #20
0
def create_challenge(jwt):
    data = request.get_json()
    error = False
    try:
        challenge = Challenge(task_id=data["task_id"],
                              series_id=data["series_id"])
        isTest = False
        if "isTest" in data:
            isTest = data["isTest"]
        DBHelper.insert(challenge)
    except:
        DBHelper.rollback()
        error = True
    finally:
        DBHelper.close()
    if error:
        abort(404)
    return jsonify({"success": True})
Example #21
0
    def test_challengeCreate(self):

        # create a new Challenge object
        challenge = Challenge(1, 2, 1)

        # add Challenge object to the database
        challengeCreate(challenge)

        # check that the number of record added is correct
        print('--- check that the number of record added is correct')
        self.assertEqual(len(Challenge.query.all()), 1)

        # check that object cannot be added to database if already exist
        print(
            '--- check that object cannot be added to database if already exist'
        )
        challengeCreate(challenge)
        self.assertEqual(len(Challenge.query.all()), 1)
Example #22
0
    def test_challengeRead(self):

        # check that function returns the right number of result (= 0)
        print(
            '--- check that function returns the right number of result (= 0)')
        self.assertEqual(len(challengeRead(None, None, None, None)), 0)
        self.assertEqual(len(challengeRead(1, 2, 1, None)), 0)

        # create a new Challenge object and add to database
        challenge = Challenge(1, 2, 1)
        db.session.add(challenge)
        db.session.commit()

        # check that function returns the right number of result (= 1)
        print(
            '--- check that function returns the right number of result (= 1)')
        self.assertEqual(len(challengeRead(None, None, None, None)), 1)
        self.assertEqual(len(challengeRead(1, 2, 1, None)), 1)
        self.assertEqual(len(challengeRead(1, 2, None, None)), 1)
Example #23
0
def challenge(request):
    if request.is_ajax():
        challenge_bot_id = json.loads(request.body)['msg']
        challenge_bot = Bot.objects.get(pk=challenge_bot_id)

        # get the user current bot
        user_prof = UserProfile.objects.get(user=request.user)
        if not user_prof.current_bot:
            print "Can not challenge if does not have a bot!"
            return HttpResponse("Error")
        if challenge_bot.owner == user_prof:
            print "[CHEATING!] - wrong challenge bot!"
            return HttpResponse("Error")

        # challenged bot must be the owners current bot
        if not challenge_bot.is_current_bot:
            print "[CHEATING!] - wrong challenge bot!, must be the owners current bot!."
            return HttpResponse("Error")

        print "Got a challenge for bot: ", challenge_bot

        # Get pending challenges for this user
        challenges = Challenge.objects.filter(requested_by=user_prof, played=False, canceled=False)
        if challenges.count() > 0:
            # has pending challenges, must wait.
            return HttpResponse("Can not challenge more than one bot at a time")

        # Check if these bots haven't already played.
        #played_challs = Challenge.objects.filter(challenger_bot=user_prof.current_bot,
        #    challenged_bot=challenge_bot, played=True)

        #if played_challs.count() > 0:
        #    # has already played against this bot, must upload a new one
        #    return HttpResponse("Already played against this bot!. Upload a new one.")
        if (user_prof.current_bot.valid != Bot.READY
                or challenge_bot.valid != Bot.READY):
            return JsonResponse({'success': False, 'msg': 'One of the bot is not READY' })

        new_challengue = Challenge()
        new_challengue.requested_by = user_prof
        new_challengue.challenger_bot = user_prof.current_bot
        new_challengue.challenged_bot = challenge_bot
        new_challengue.save()

        return JsonResponse({'success': True})
Example #24
0
def challenge(request):
    if request.is_ajax():
        challenge_bot_id = json.loads(request.body)['msg']
        challenge_bot = Bot.objects.get(pk=challenge_bot_id)

        # get the user current bot
        user_prof = UserProfile.objects.get(user=request.user)
        if not user_prof.current_bot:
            print "Can not challenge if does not have a bot!"
            return HttpResponse("Error")
        if challenge_bot.owner == user_prof:
            print "[CHEATING!] - wrong challenge bot!"
            return HttpResponse("Error")

        # challenged bot must be the owners current bot
        if not challenge_bot.is_current_bot:
            print "[CHEATING!] - wrong challenge bot!, must be the owners current bot!."
            return HttpResponse("Error")

        print "Got a challenge for bot: ", challenge_bot

        # Get pending challenges for this user
        challenges = Challenge.objects.filter(requested_by=user_prof, played=False, canceled=False)
        if challenges.count() > 0:
            # has pending challenges, must wait.
            return HttpResponse("Can not challenge more than one bot at a time")

        # Check if these bots haven't already played.
        #played_challs = Challenge.objects.filter(challenger_bot=user_prof.current_bot,
        #    challenged_bot=challenge_bot, played=True)

        #if played_challs.count() > 0:
        #    # has already played against this bot, must upload a new one
        #    return HttpResponse("Already played against this bot!. Upload a new one.")
        if (user_prof.current_bot.valid != Bot.READY
                or challenge_bot.valid != Bot.READY):
            return JsonResponse({'success': False, 'msg': 'One of the bot is not READY' })

        new_challengue = Challenge()
        new_challengue.requested_by = user_prof
        new_challengue.challenger_bot = user_prof.current_bot
        new_challengue.challenged_bot = challenge_bot
        new_challengue.save()

        return JsonResponse({'success': True})
Example #25
0
def challenge(request):
    if request.is_ajax():
        challenge_bot_id = json.loads(request.body)['msg']
        challenge_bot = Bot.objects.get(pk=challenge_bot_id)

        # get the user current bot
        user_prof = UserProfile.objects.get(user=request.user)
        if not user_prof.current_bot:
            print "Can not challenge if does not have a bot!"
            return HttpResponse("Error")
        if challenge_bot.owner == user_prof:
            print "[CHEATING!] - wrong challenge bot!"
            return HttpResponse("Error")

        # challenged bot must be the owners current bot
        if not challenge_bot.is_current_bot:
            print "[CHEATING!] - wrong challenge bot!, must be the owners current bot!."
            return HttpResponse("Error")

        print "Got a challenge for bot: ", challenge_bot

        # Get pending challenges for this user
        challenges = Challenge.objects.filter(requested_by=user_prof, played=False)
        if challenges.count() > 0:
            # has pending challenges, must wait.
            return HttpResponse("Can not challenge more than one bot at a time")

        # Check if these bots haven't already played.
        played_challs = Challenge.objects.filter(challenger_bot=user_prof.current_bot,
            challenged_bot=challenge_bot, played=True)

        if played_challs.count() > 0:
            # has already played against this bot, must upload a new one
            return HttpResponse("Already played against this bot!. Upload a new one.")

        new_chall = Challenge()
        new_chall.requested_by = user_prof
        new_chall.challenger_bot = user_prof.current_bot
        new_chall.challenged_bot = challenge_bot
        new_chall.save()

        return HttpResponse(json.dumps({'success' : True}), mimetype='application/json')
def create(request):
    challenge = Challenge(creator=request.user)
    return _edit(request, challenge)
Example #27
0
def delete_challenge(Challenge):
    Challenge.delete_instance()
Example #28
0
def create_challenge(name, language, steps=1):
    Challenge.create(name=name, language=language, steps=steps)
Example #29
0
 def createChallenge(self):
     task = self.createTask()
     series = self.createSeries()
     challenge = Challenge(task_id=task["id"], series_id=series["id"])
     return self.createEntity(challenge)
Example #30
0
def search_challenges(name, language):
    return Challenge.select().where(Challenge.name.contains(name),
                                    Challenge.language == language)
Example #31
0
        if run_result.code != 0:
            return ChallengeError('Error in running the code', run_result)
        validate_result = challenge_execution.run_step('bash', 'validate', 'scripts/validate.sh', timeout=10)

        if validate_result.code != 0:
            return ChallengeError('Error in validating the result', validate_result)

        challenge_execution.run_step('bash', 'cleanup', 'scripts/cleanup.sh')
        return ChallengeResult(build_result, run_result, validate_result)


if __name__ == '__main__':
    with open('participants.yml') as participants_stream:
        participants = yaml.load(participants_stream, Loader=yaml.FullLoader)

    with open('challenges.yml') as challenges_stream:
        challenges = yaml.load(challenges_stream, Loader=yaml.FullLoader)

    for challenge_dict in challenges:
        challenge = Challenge.from_dict(challenge_dict)
        round_id = int(time.time())
        reporter.start_round(round_id, challenge.name)
        for p in participants:
            repository = p['repository']
            nickname = p['nickname']
            ce = ChallengeExecution(challenge, p['repository'])
            result = run_challenge(ce)
            reporter.report(nickname, challenge.name, round_id, result)
            print(result)
        reporter.finish_round(round_id, challenge.name)
Example #32
0
 def get_queryset(self):
     return Challenge.current_challenges()
Example #33
0
#
#  Created by Dulio Denis on 1/1/19.
#  Copyright (c) 2019 ddApps. All rights reserved.
# ------------------------------------------------
#  Challenge 2: First Queries
# ------------------------------------------------
#  Challenge Task 1 of 4
#  Import the Challenge class from models.py.
from models import Challenge

# ------------------------------------------------
#  Challenge Task 2 of 4
#  Now, create a variable named all_challenges.
#  It should select all of the available challenges
#  from the database.
all_challenges = Challenge.select()

# ------------------------------------------------
#  Challenge Task 3 of 4
#  Next, create a new Challenge.
#  The language should be "Ruby", the name should be "Booleans".
Challenge.create(language='Ruby', name='Booleans')

# ------------------------------------------------
#  Challenge Task 4 of 4
#  Finally, make a variable named sorted_challenges
#  that is all of the Challenge records, ordered by
#  the steps attribute on the model.
#  The order should be ascending, which is the default direction.
sorted_challenges = Challenge.select().order_by(Challenge.steps)
Example #34
0
def loadChallenges():
	currentTime = time.time()

	chall1 = Challenge(challengeid=1, title='First Step', description='Check in to 1 lecture', complete=False, expiresat=currentTime+864000, badge=Badge(iconName='/img/firststeps.png'), points=10)
	chall2 = Challenge(challengeid=2, title='Not Bad', description='Check in to 5 lectures', complete=False, expiresat=currentTime+1382400, badge=Badge(iconName='/img/notbad.png'), points=30)
	chall3 = Challenge(challengeid=3, title='Golden Student', description='Check in to 10 lectures', complete=False, expiresat=currentTime+2592000, badge=Badge(iconName='/img/goldenstudent.png'), points=50)
	chall4 = Challenge(challengeid=4, title='Gotta Go Fast', description='Be the first in your class to check in to a lecture', complete=False, expiresat=currentTime+2592000, badge=Badge(iconName='/img/gottagofast.png'), points=30)
	chall5 = Challenge(challengeid=5, title='Hat-trick', description='Check in to 3 consecutive lectures', complete=False, expiresat=currentTime+1382400, badge=Badge(iconName='/img/hattrick.png'), points=30) 
	chall6 = Challenge(challengeid=6, title='Unstoppable', description='Check in to 5 consecutive lectures', complete=False, expiresat=currentTime+2592000, badge=Badge(iconName='/img/unstoppable.png'), points=50)
	chall7 = Challenge(challengeid=7, title='Perfect Week', description='Attend every lecture in a week', complete=False, expiresat=currentTime+2592000, badge=Badge(iconName='/img/perfectweek.png'), points=20)
	chall8 = Challenge(challengeid=8, title='Selective Attendance', description='Attend the same lecture 3 weeks in a row', complete=False, expiresat=currentTime+2592000, badge=Badge(iconName='/img/selectiveattendance.png'), points=30)
	chall9 = Challenge(challengeid=9, title='Early Bird', description='Make it to a 9am lecture', complete=False, expiresat=currentTime+1382400, badge=Badge(iconName='/img/earlybird.png'), points=10)
	chall10 = Challenge(challengeid=10, title='Long day', description='Check in to 4 lectures in the same day', complete=False, expiresat=currentTime+1987200, badge=Badge(iconName='/img/longday.png'), points=30)

	chall1.put()
	chall2.put()
	chall3.put()
	chall4.put()
	chall5.put()
	chall6.put()
	chall7.put()
	chall8.put()
	chall9.put()
	chall10.put()
Example #35
0
def get_challenge_or_404(slug):
    """Return a challenge or 404"""
    challenge = Challenge.get(slug)
    if not challenge:
        abort(404)
    return challenge
Example #36
0
def launch(request, to_id):
    lock = challengeLock.lock()
    logging.info("Locked.")

    flush_transaction()
    user_to = get_object_or_404(Player, pk=to_id)
    user_to = user_to.get_extension(ChallengeUser)
    user_from = request.user.get_profile().get_extension(ChallengeUser)


    if ChallengeGame.disabled():
        messages.error(request, _('Provocarile sunt dezactivate'))
        logging.info("Ready to unlock (disabled).")
        lock.unlock()
        return redirect('challenge_index_view')

    if (not user_to.is_eligible()) or (not user_from.is_eligible()):
        messages.error(request, _('Sorry, challenge failed.'))
        logging.info("Ready to unlock (is eligible).")
        lock.unlock()
        return redirect('challenge_index_view')

    if not user_from.can_launch():
        messages.error(request, _('You cannot launch another challenge today.'))
        logging.info("Ready to unlock (cannot launch today).")
        lock.unlock()
        return redirect('challenge_index_view')

    if not user_from.in_same_division(user_to):
        messages.error(request, _('You are not in the same division'))
        logging.info("Ready to unlock (not in same divission).")
        lock.unlock()
        return redirect('challenge_index_view')

    if not user_from.has_enough_points():
        messages.error(request, _('You need at least 30 points to launch a challenge'))
        logging.info("Ready to unlock (not enough points).")
        lock.unlock()
        return redirect('challenge_index_view')

    if user_from.can_challenge(user_to):
        try:
            chall = Challenge.create(user_from=user_from, user_to=user_to)
            logging.info("Created challenge: %s" %(chall))
        except ChallengeException as e:
            # Some error occurred during question fetch. Clean up, and display error
            messages.error(request, e.message)
            lock.unlock()
            return redirect('challenge_index_view')
        #Checking if user_to is stored in session
        PREFIX = "_user:"******"multiple-login"
        if (PREFIX + user_to.user.username) in request.session:
            from wouso.core.signals import addActivity
            addActivity.send(sender=None, user_to=user_to, user_from=user_from, action=action_msg,
                             game=None, public=False)
        messages.success(request, _('Successfully challenged'))
        logging.info("Ready to unlock (save).")
        lock.unlock()
        return redirect('challenge_index_view')
    else:
        messages.error(request, _('This user cannot be challenged.'))
        logging.info("Ready to unlock (no user challenge).")
        lock.unlock()
        return redirect('challenge_index_view')
Example #37
0
def initializeChallenge(from_student_id, to_student_id, quiz_id):
    return Challenge(from_student_id, to_student_id, quiz_id)
Example #38
0
    def setUp(self):
        print('\r')
        # drop all tables in the database
        db.session.remove()
        db.drop_all()
        # crete all tables in the database
        db.create_all()

        self.maxDiff = None

        self.app = app.test_client()

        # adding students
        user_1 = User('*****@*****.**', encrypt('password'), 'student_1')
        student_1 = Student(user_1, 'U00000000A')
        db.session.add(student_1)
        user_2 = User('student_2gmail.com', encrypt('password'), 'student_2')
        student_2 = Student(user_2, 'U00000000B')
        db.session.add(student_2)

        # adding staff
        user_3 = User('*****@*****.**', encrypt('password'), 'staff_1')
        staff_1 = Staff(user_3)
        db.session.add(staff_1)

        # adding topics
        topic_1 = Topic(name='topic_1')
        db.session.add(topic_1)
        topic_2 = Topic(name='topic_2')
        db.session.add(topic_2)

        # adding lessons
        lesson_1 = Lesson(topic_id=1, id=1, name='lesson_1', content='content')
        db.session.add(lesson_1)
        lesson_2 = Lesson(topic_id=1, id=2, name='lesson_2', content='content')
        db.session.add(lesson_2)
        lesson_3 = Lesson(topic_id=1, id=3, name='lesson_3', content='content')
        db.session.add(lesson_3)
        lesson_4 = Lesson(topic_id=2, id=1, name='lesson_4', content='content')
        db.session.add(lesson_4)

        # adding quizzes
        quiz_1 = Quiz(3, 'quiz_1', True, '2020-03-30', '2020-03-31')
        db.session.add(quiz_1)
        quiz_2 = Quiz(3, 'quiz_2', True, '2020-03-30', '2020-03-31')
        db.session.add(quiz_2)
        quiz_3 = Quiz(3, 'quiz_3', True, '2020-03-30', '2020-03-31')
        db.session.add(quiz_3)

        # adding questions
        question_1 = Question(1, 1, 'description_1')
        db.session.add(question_1)
        question_2 = Question(1, 1, 'description_2')
        db.session.add(question_2)
        question_3 = Question(1, 3, 'description_3')
        db.session.add(question_3)
        question_4 = Question(1, 3, 'description_4')
        db.session.add(question_4)
        question_5 = Question(1, 3, 'description_5')
        db.session.add(question_5)

        # assign questions to quiz
        rs_1 = Rs_quiz_question_contain(1, 1)
        db.session.add(rs_1)
        rs_2 = Rs_quiz_question_contain(3, 3)
        db.session.add(rs_2)
        rs_3 = Rs_quiz_question_contain(3, 4)
        db.session.add(rs_3)
        rs_4 = Rs_quiz_question_contain(3, 5)
        db.session.add(rs_4)

        # add attempts to questions
        question_attempt_1 = QuestionAttempt(1, 1, True, 10)
        db.session.add(question_attempt_1)
        question_attempt_2 = QuestionAttempt(1, 1, False, 20)
        db.session.add(question_attempt_2)
        question_attempt_3 = QuestionAttempt(1, 2, True, 30)
        db.session.add(question_attempt_3)
        question_attempt_4 = QuestionAttempt(1, 3, False, 40)
        db.session.add(question_attempt_4)

        # add question choices to questions
        qc_1 = QuestionChoice(1, 1, 'choice_1', True)
        db.session.add(qc_1)
        qc_2 = QuestionChoice(1, 2, 'choice_2', True)
        db.session.add(qc_2)
        qc_3 = QuestionChoice(1, 3, 'choice_3', True)
        db.session.add(qc_3)

        # adding quiz attempts
        quiz_attempt_1 = QuizAttempt(1, 1, 0)
        db.session.add(quiz_attempt_1)
        quiz_attempt_2 = QuizAttempt(2, 3, 2)
        db.session.add(quiz_attempt_2)
        quiz_attempt_3 = QuizAttempt(1, 3, 3)
        db.session.add(quiz_attempt_3)

        # adding quizzes to lessons
        rs_lesson_quiz_contain_1 = Rs_lesson_quiz_contain(1, 1, 1)
        db.session.add(rs_lesson_quiz_contain_1)
        rs_lesson_quiz_contain_2 = Rs_lesson_quiz_contain(1, 1, 2)
        db.session.add(rs_lesson_quiz_contain_2)
        rs_lesson_quiz_contain_3 = Rs_lesson_quiz_contain(1, 3, 3)
        db.session.add(rs_lesson_quiz_contain_3)

        # adding courses
        course = Course('cz1005')
        db.session.add(course)

        # enrol students into courses
        enrol_1 = Rs_student_course_enrol(1, 'cz1005')
        db.session.add(enrol_1)
        enrol_2 = Rs_student_course_enrol(2, 'cz1005')
        db.session.add(enrol_2)

        # make staff teach course
        teach_1 = Rs_staff_course_teach(3, 'cz1005')
        db.session.add(teach_1)

        # adding quizzes to courses
        Rs_quiz_course_assign_1 = Rs_quiz_course_assign(1, 'cz1005')
        db.session.add(Rs_quiz_course_assign_1)
        Rs_quiz_course_assign_2 = Rs_quiz_course_assign(2, 'cz1005')
        db.session.add(Rs_quiz_course_assign_2)
        Rs_quiz_course_assign_3 = Rs_quiz_course_assign(3, 'cz1005')
        db.session.add(Rs_quiz_course_assign_3)

        # adding challenges
        challenge_1 = Challenge(1, 2, 1)
        db.session.add(challenge_1)
        challenge_2 = Challenge(1, 2, 2)
        db.session.add(challenge_2)
        challenge_3 = Challenge(2, 1, 1)
        db.session.add(challenge_3)

        db.session.commit()
Example #39
0
# Import the Challenge class from models.py
from models import Challenge

# Now create a variable named all_challenges. It should select all of the available challenges from the database.
all_challenges = Challenge.select()

# Next create a new Challenge. The language should be 'Ruby', the name should be 'Booleans'.
Challenge.create(language='Ruby', name='Booleans')

# Finally make a variable named sorted_challenges that is all of the Challenge records, ordered by the steps attribute on the model
# The order should be ascending, which is the default direction.
sorted_challenges = all_challenges.order_by(Challenge.steps)
Example #40
0
        database = db


# ============= Part 2 =============

# Task 1 of 4
# Import the Challenge class from models.py.

from models import Challenge

# Task 2 of 4
# Now, create a variable named all_challenges. It should select all of the available challenges from the database.

from models import Challenge

all_challenges = Challenge.select()

# Task 3 of 4
# Next, create a new Challenge. The language should be "Ruby", the name should be "Booleans".

from models import Challenge

all_challenges = Challenge.select()

Challenge.create(language="Ruby", name="Booleans")

# Task 4 of 4
# Finally, make a variable named sorted_challenges that is all of the Challenge records, ordered by the steps attribute on the model. The order should be ascending, which is the default direction.

from models import Challenge
Example #41
0
def get_challenge_or_404(slug):
    """Return a challenge or 404"""
    challenge = Challenge.get(slug)
    if not challenge:
        abort(404)
    return challenge