Skip to content

Commit

Permalink
Merge pull request #2 from HarpinderJotSingh/master
Browse files Browse the repository at this point in the history
Update Fork
  • Loading branch information
aarjavjain1 committed Jan 7, 2020
2 parents 08b9f8d + 97ae086 commit a0023f2
Show file tree
Hide file tree
Showing 15 changed files with 327 additions and 131 deletions.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
- [X] Timer is not working properly, fix it
- [X] When user gets a question correct, automatically redirect to next question
- [X] Add a live leaderboard
- [ ] Change frontend
- [ ] Add details in about section
- [ ] Cursor does not goes up in the editor, fix it
- [X] Change frontend - Leaderboard opening animation is inserted, might require to change other background colors and stuff later.
- [X] Add details in about section
- [X] Cursor does not goes up in the editor, fix it
- [ ] Do Backend stuff - do not put keys as it is within the files
- [ ] Add feature to show code for sometime, say 5-10 seconds once per question
- [X] Add feature to show code for sometime, say 5-10 seconds once per question
- [ ] Disable run button for the time compiler runs the code and returns the result to prevent multiple compiler runs
- [ ] Limit number of runs per question per user
- [X] Limit number of runs per question per user - feature not needed anymore
4 changes: 2 additions & 2 deletions blind_coding/blind_coding/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,5 +137,5 @@
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(REPOSITORY_ROOT, 'media/')

clientId: "222a2ef84f6881409d32ae21369d1a32"
clientSecret:"67872757630a355db890ee74b6b20926cb9e025dbb444182df2bd2700fc64af1"
clientId = "222a2ef84f6881409d32ae21369d1a32"
clientSecret = "67872757630a355db890ee74b6b20926cb9e025dbb444182df2bd2700fc64af1"
Binary file modified blind_coding/db.sqlite3
Binary file not shown.
Binary file not shown.
Binary file not shown.
3 changes: 2 additions & 1 deletion blind_coding/main_app/admin.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from __future__ import unicode_literals
from django.contrib import admin
from .models import Question,Userdata
from .models import Question,Userdata,Time_Penalty

# Register your models here.
admin.site.register(Question)
admin.site.register(Userdata)
admin.site.register(Time_Penalty)
43 changes: 43 additions & 0 deletions blind_coding/main_app/migrations/0002_auto_20200104_1324.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Generated by Django 2.2.7 on 2020-01-04 07:54

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('main_app', '0001_initial'),
]

operations = [
migrations.AddField(
model_name='question',
name='weight',
field=models.IntegerField(default=10),
preserve_default=False,
),
migrations.AddField(
model_name='userdata',
name='total_penalty',
field=models.IntegerField(default=0),
),
migrations.CreateModel(
name='Time_Penalty',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('time_penalty', models.IntegerField(default=0)),
('no_wa', models.IntegerField(default=0)),
('player', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='main_app.Userdata')),
('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='questions', to='main_app.Question')),
],
options={
'unique_together': {('player', 'question')},
},
),
migrations.AddField(
model_name='question',
name='time_penalty',
field=models.ManyToManyField(blank=True, null=True, through='main_app.Time_Penalty', to='main_app.Userdata'),
),
]
18 changes: 18 additions & 0 deletions blind_coding/main_app/migrations/0003_auto_20200104_1332.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 2.2.7 on 2020-01-04 08:02

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('main_app', '0002_auto_20200104_1324'),
]

operations = [
migrations.AlterField(
model_name='question',
name='weight',
field=models.IntegerField(default=20),
),
]
17 changes: 16 additions & 1 deletion blind_coding/main_app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@ class Userdata(models.Model):
score = models.IntegerField(default = 0)
answerGiven = models.CharField(max_length = 10, default="00000")
timeElapsed = models.IntegerField(default = 0)

total_penalty=models.IntegerField(default = 0)

def __str__(self):
return str(self.user_id.username)

class Question(models.Model):
qno=models.IntegerField(default=0)
weight = models.IntegerField(default=20)
text = models.CharField(max_length=45000)
time_penalty = models.ManyToManyField(Userdata, through="Time_Penalty",blank=True,null=True)
testcaseno=models.IntegerField(default=0)
samplein = models.CharField(max_length=45000,default='')
sampleout = models.CharField(max_length=45000,default='')
Expand All @@ -27,3 +30,15 @@ class Question(models.Model):

def __str__(self):
return str(self.pk)

class Time_Penalty(models.Model):
player = models.ForeignKey(Userdata, on_delete=models.CASCADE)
question = models.ForeignKey(Question, on_delete=models.CASCADE,related_name='questions')
time_penalty = models.IntegerField(default=0)
no_wa = models.IntegerField(default=0)

class Meta:
unique_together = ("player", "question")

def __str__(self):
return "{} : {}".format(self.player.name, self.question.qno)
32 changes: 19 additions & 13 deletions blind_coding/main_app/templates/loggedIn.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
</head>
<body>
Expand Down Expand Up @@ -60,20 +61,23 @@
</div>
<div class="backdrop">
</div>
<div class="about">
<div id="close" onclick="closeAbout()">
<div class="instructions">
<div id="close" onclick="closeInstructions()">
<span class="horiz"></span>
<span class="verti"></span>
</div>
<h3>About</h3>
<h5>1. What is Lorem Ipsum?</h5>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<h5>2. Where does it come from?</h5>
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested.</p>
</div>
<h3>Instructions</h3>
<h5>- There are five questions of varying difficulties and points associated with them. <br> Score associated are 20, 30, 40, 50, 60 points respectively.</h5>
<h5>- For every question, the first time you submit the correct answer, you are awarded points corresponding to that question and the time penalty is
also calculated which takes into consideration the time taken until last successful solve together with the number of wrong attempts</h5>
<h5>- Standings will be based on the points scored and in cases of clashes, time penalties are compared and one with lesser time penalty is better ranker</h5>
<h5>- Every time you give a correct answer, the question is automatically changed and code editor is reset.</h5>
<h5>- You have only two attempts throughout the event to see the code you have written. To see the code, press Show Code button near Run button.</h5>
<h5>- Don't try to open up the console or changing the window/tab. You'll be logged out immediately</h5>
</div>
<nav id="header">
<ul>
<li onclick="showAbout()">About</li>
<li onclick="showInstructions()">Instructions</li>
<li>Contact</li>
<a href="/logout"><li>Logout</li></a>
</ul>
Expand All @@ -82,20 +86,20 @@ <h3 class="title">Blind Coding</h3>
<div id="main">
<div class="left">
<h5>Question 1</h5>
You have C=100,000 cakes, numbered 1 through C. Each cake has an integer height; initially, the height of each cake is 0. There are N operations. In each operation, you are given two integers L and R, and you should increase by 1 the height of each of the cakes L,L+1,…,R. One of these N operations should be removed and the remaining N−1 operations are then performed. Chef wants to remove one operation in such a way that after the remaining N−1 operations are performed, the number of cakes with height exactly K is maximum possible. Since Chef is a bit busy these days, he has asked for your help. You need to find the maximum number of cakes with height exactly K that can be achieved by removing one operation.
Loading.....
</div>
<div class="right">

<div class="language">
<div class="input-field col s12">
<select id="langSelect">
<option value="" disabled selected class="blue-text text-darken-2">Choose your language</option>
<option value="c">C</option>
<!-- <option value="c">C</option>
<option value="java">Java</option>
<option value='cpp'>C++</option>
<option value='cpp14'>C++14</option>
<option value='python2'>Python2</option>
<option value='python3'>Python3</option>
<option value='python3'>Python3</option> -->
</select>
</div>
</div>
Expand All @@ -109,7 +113,9 @@ <h5>Question 1</h5>
</div>

<div class="options">
<button class="run" onclick="runCode()">Run</button>
<button class="bttn" onclick="runCode()">Run</button>
<button class="bttn" id="showCode">Show Code</button>
<!-- <div class="time-left">10</div> -->
</div>

</div>
Expand Down
98 changes: 64 additions & 34 deletions blind_coding/main_app/views.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
from django.shortcuts import render,redirect
import requests

# Create your views here.
def default(request):
return render(request,'loggedIn.html')

def index(request):
return render(request,'index.html')
#
#def login(request):
# pass
from django.shortcuts import render
from django.http import JsonResponse,HttpResponseRedirect,HttpResponse
from .models import Userdata,Question
from .models import Userdata,Question,Time_Penalty
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required

import json
import requests
import base64
import time
import blind_coding.settings as settings

from django.contrib.auth.decorators import login_required
def default(request):
return render(request,'loggedIn.html')

def index(request):
return render(request,'index.html')

def login(request):
# if request.POST:
Expand Down Expand Up @@ -48,58 +45,91 @@ def question(request):
print('hi')
print(res['userScore'])
return HttpResponse(json.dumps(res))

def runCode(request):
postData = json.loads( request.body.decode('utf-8') )
url = 'https://api.jdoodle.com/execute/'
print(postData)
url = 'https://api.judge0.com/submissions?base64_encoded=false&wait=false'
que = Question.objects.get(qno=postData['qNo'])
postData['stdin'] = '3'+'\n'+que.test_case1+'\n'+que.test_case2+'\n'+que.test_case3
postData['clientId'] = settings.clientId
postData['clientSecret'] = settings.clientSecret
stdin = '3'+'\n'+que.test_case1+'\n'+que.test_case2+'\n'+que.test_case3
# postData['stdin'] = str(base64.b64encode(stdin.encode("utf-8")))
postData['stdin'] = stdin
# postData['source_code'] = str(base64.b64encode(postData['source_code'].encode('utf-8')))
print(postData)

response = requests.post(url,json=postData)
resp = response.json()
# resp = json.loads(resp)
# resp = json.loads(resp)
print('qNo',postData['qNo'])
print('jdoodle response json object: ',resp)
print('jdoodle output response: ',resp['output'])
print('response token: ',resp['token'])

url2 = 'https://api.judge0.com/submissions/'+resp['token']+'?base64_encoded=false'
time.sleep(1)
resp = requests.get(url2).json()
if 'status' in resp:
if resp['status']['description'] == "Processing":
while resp['status']['description'] == "Processing":
resp = requests.get(url2).json()
print(resp)
# print('exit_code ',resp['exit_code'])
# print('exit_signal ',resp['exit_signal'])
# print( str(base64.b64decode(resp['stderr'].encode('utf-8').strip()), "utf-8") )
# print('output response: ',resp['stdout'])
res = {}
#Get current user
currUser = Userdata.objects.get(user_id = request.user)

if resp['output'].find('error') != -1:
res['output'] = resp['output']
if 'error' in resp:
res['stdout'] = 'error'
elif resp['status']['description'] != "Accepted":
if resp['stderr'] is not None:
res['stdout'] = resp['stderr']
elif resp['compile_output'] is not None:
res['stdout'] = resp['compile_output']
else:
res['stdout'] = 'error'
else:
quesNo = postData['qNo']
quesData = Question.objects.get(qno= quesNo)
answer = quesData.test_case1_sol+'\n'+quesData.test_case2_sol+'\n'+quesData.test_case3_sol+'\n'
print(answer)
currUser.timeElapsed += int(postData['timeElapsed'])
if answer == resp['output']:
if answer == resp['stdout']:
print('hurray')
res['output'] = 'Correct Answer'
res['stdout'] = 'Correct Answer'
print(currUser.answerGiven)
lst = list(currUser.answerGiven)
print(lst)
if(lst[quesNo] == '0'): # if the question is being answered first time
print('Updating score for question no', )
lst[quesNo] = '1'
currUser.answerGiven="".join(lst)
currUser.score+=10
timepenalty , status =Time_Penalty.objects.get_or_create(player=currUser,question=que)
timepenalty.time_penalty=int(postData['timeElapsed'])+(0.2*timepenalty.no_wa*que.weight)
currUser.score+=que.weight
currUser.total_penalty+=timepenalty.time_penalty
timepenalty.save()
currUser.save()
else:
res['output'] = 'Wrong answer..'

currUser.save()
timepenalty , status = Time_Penalty.objects.get_or_create(player=currUser,question=que)
print('hiii')
print('hola: ',timepenalty)
print('timepenalty_player',timepenalty.player)
timepenalty.no_wa+=1
res['stdout'] = 'Wrong answer..'
timepenalty.save()
currUser.save()
res['score'] = currUser.score
if currUser.answerGiven == "11111":
res['completedGame'] = 'true'
else:
res['completedGame'] = 'false'
return HttpResponse(json.dumps(res))

def l_out(request):
logout(request)
return render(request,'index.html')
logout(request)
return render(request,'index.html')

def leaderboard(request):
leaderboard = Userdata.objects.order_by('-score')
leaderboard = Userdata.objects.order_by('-score','total_penalty')
print(leaderboard)
username = []
score = []
Expand Down
Loading

0 comments on commit a0023f2

Please sign in to comment.