--- a/testappproj/testapp/views.py Mon May 31 19:18:57 2010 +0530
+++ b/testappproj/testapp/views.py Mon Jun 14 01:00:59 2010 +0530
@@ -6,8 +6,8 @@
import random
import StringIO
import sys
+import json
-# # AppEngine imports
from django.contrib.auth.models import User
@@ -15,12 +15,6 @@
from django.http import HttpResponse
-
-# Django imports
-#from django.conf import settings
-#settings._target = None
-#os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
-#import django
from django import http
from django import shortcuts
from django.template import Context ,RequestContext
@@ -36,15 +30,7 @@
from django.contrib.auth.decorators import login_required
from models import Score
import time
-
-
-# def handle_uploaded_file(f):
-# print f
-# destination = open('some/file/name.txt', 'wb+')
-# for chunk in f.chunks():
-# destination.write(chunk)
-# destination.close()
-
+import sandbox
def respond(request, user,template, params=None):
@@ -75,6 +61,27 @@
template += '.html'
return shortcuts.render_to_response(template, params)
+
+
+def check_examination_done(f):
+ def wrap(request, *args, **kwargs):
+ #this check the session if userid key exist, if not it will redirect to login page
+ user= Test_User.objects.get(user=request.user)
+
+ if user.exam_done==True:
+ return HttpResponse("You have given the exam before")
+ return f(request, *args, **kwargs)
+ return wrap
+
+
+
+
+
+
+
+
+
+
def execute_plotting_test_cases(user_code , solution_image,problem_id , username):
print user_code
@@ -92,12 +99,12 @@
codeErr = StringIO.StringIO()
-
+
# capture output and errors
sys.stdout = codeOut
sys.stderr = codeErr
- exec code
+ sandbox.execute(code)
# restore stdout and stderr
sys.stdout = sys.__stdout__
@@ -130,9 +137,9 @@
return solved,errors
def execute_test_cases(code , solution):
+
+
- print code
- print "solution"+solution
solved=False
@@ -140,20 +147,22 @@
codeOut = StringIO.StringIO()
codeErr = StringIO.StringIO()
+
# capture output and errors
sys.stdout = codeOut
+
sys.stderr = codeErr
-
- exec code
+ print "aaaklamnsldnlndskn"
+ sandbox.execute(code)
# restore stdout and stderr
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
-
+ print "xs zc sdc"
s = codeOut.getvalue()
@@ -179,6 +188,17 @@
return solved,errors
+def complete(request):
+ print request.user
+ user= Test_User.objects.get(user=request.user)
+ user.exam_done=True
+ user.save()
+
+ return respond(request, request.user ,'submit')
+
+
+
+
def index(request):
""" need to change user in the django.contrib way"""
@@ -187,80 +207,19 @@
return respond(request , user, 'index')
-# def contribution(request):
-# # user = users.get_current_user()
-# return respond(request, user, 'contribution')
-
-# def help(request):
-# # user = users.get_current_user()
-# return respond(request, user, 'help')
-
-# def about(request):
-# # user = users.get_current_user()
-# return respond(request, user, 'about')
-
-# def vision(request):
-# # user = users.get_current_user()
-# return respond(request, user, 'vision')
-
-# def statements(request):
-# # user = users.get_current_user()
-# return respond(request, user, 'statements')
-
+
-def get_pu(problem):
- '''
- returns:
- - "USER_NOT_SIGNED_IN": user not signed in. returning this to prevent saving anonymous user's potentially crappy solution and display it to every anonymous visitor
- - "PU_NOT_FOUND": for signed in users when no solution has been attempted.
- - ProblemUser: for signed in users when a solution has been attempted
-
- '''
-# user = users.get_current_user()
-# if not user:
-# return "USER_NOT_SIGNED_IN"
- pu_query = models.ProblemUser.all().filter('problem = ', problem).filter('user =', users.get_current_user())
- pu_results = pu_query.fetch(1)
- if pu_results:
- return pu_results[0]
- return "PU_NOT_FOUND"
-
-# def is_solved(problem):
-# pu = get_pu(problem)
-# if pu == "PU_NOT_FOUND" or pu == "USER_NOT_SIGNED_IN": return False
-# return pu.solved
@login_required(function=None, redirect_field_name='next')
+@check_examination_done
def problems(request, category=None):
user = request.user
-
- # if category is None:
- # problems = db.GqlQuery('SELECT * FROM Problem ORDER BY created DESC')
- # else:
- # problems = db.GqlQuery('SELECT * FROM Problem WHERE categories = :1 ORDER BY created DESC', category)
-
+
+ entries=[]
+ all_sessions=set([element.session for element in Problem.objects.all()])
-
- # entries = []
- # for problem in problems:
- # e = dict(problem=problem,
- # username=problem.author.nickname().partition('@')[0],
- # solved=is_solved(problem))
- # entries.append(e)
- # problems = entries
- entries=[]
- all_sessions=set([element.session for element in Problem.objects.all()])
- print all_sessions
-
- # for problem in problems:
- # e = dict(problem=problem.description,
- # username=user.username,
- # problem_id=problem.id
-
- # )
- # entries.append(e)
-# print entries
+
#get problems to solve from each session.
@@ -288,91 +247,64 @@
return http.HttpResponseNotFound('No such problem.')
-# pu = get_pu(problem)
-# if pu == "PU_NOT_FOUND": # user is attempting problem for the first time
-# pu = models.ProblemUser(problem=problem, user=users.get_current_user(), solution='', solved=False)
-# pu.put()
-# pu = None
print problem.id
return respond(request, request.user ,'code' ,{'problem' : problem } )
def run(request):
- user = request.user
- print request.POST
- problem_id = request.POST.get('problem_id')
+ user = request.user
+ print user
+ problem_id = request.POST.get('problem_id')
- if problem_id:
- problem = Problem.objects.get(id=int(problem_id))
+ if problem_id:
+ problem = Problem.objects.get(id=int(problem_id))
- if problem is None:
- return http.HttpResponseNotFound('No such problem.')
-
- user_code = request.POST.get('user_code')
+ if problem is None:
+ return http.HttpResponse('There is no problem like this are you sure you solved it')
- if not user_code:
- return http.HttpResponse('bad request')
+ user_code = request.POST.get('user_code')
+
+
+ if user_code == '':
+ return http.HttpResponse('No solution')
- # pu = get_pu(problem)
- # # update ProblemUser object for this user
- # if (pu.__class__ == models.ProblemUser):
- # pu.solution = user_code
- # pu.put()
+
+ user_code = user_code.replace('\r\n', '\n')
+ user_code += '\n\n'
- user_code = user_code.replace('\r\n', '\n')
- user_code += '\n\n'
-
- errors = ''
+ errors = ''
- # try:
- # print user_code
- # compiled = compile(user_code, 'error_file', 'exec')
- # g = {}
- # exec compiled in g
+ print "ksmdlnjdns"
-# s = problem.tests.replace('\r\n', '\n')
-# s += '\n\n'
- # test_cases = doctest.DocTestParser().get_examples(s)
- solved,errors = execute_test_cases(user_code,problem.solution)
- # if solved:
- # pu = get_pu(problem)
- # if pu.__class__ == models.ProblemUser:
- # pu.solved = True
- # pu.put()
- # else:
- # pu = get_pu(problem)
- # if pu.__class__ == models.ProblemUser:
- # pu.solved = False
- # pu.put()
-
-
-
+ solved,errors = execute_test_cases(user_code,problem.solution)
+
+
+ if solved==True:
+
+ #user is answering his first question
+ try:
+ print user.id
+ score_for_user= Score.objects.get(user=user)
+ score_for_user.total_credits+=problem.credit
+ score_for_user.save()
+
+ # user has answered questions previously
+ except Score.DoesNotExist:
- if solved==True:
-
- #user is answering his first question
- try:
- # print user.id
- score_for_user= Score.objects.get(user=user)
- score_for_user.total_credits+=problem.credit
- score_for_user.save()
-
- # user has answered questions previously
- except Score.DoesNotExist:
-# print user.id
- score_new_user=user.id
- score_total_credits=problem.credit
- score=Score(user_id=user.id,total_credits=score_total_credits)
- score.save()
+ score_new_user=user.id
+ score_total_credits=problem.credit
+ score=Score(user_id=user.id,total_credits=score_total_credits)
+ score.save()
- else:
- print "oops"
- results=solved
-
- return respond(request, request.user, 'run', {'results': results})
+ else:
+ http.HttpResponse('Wrong Answer')
+
+
+ return http.HttpResponse("Right Answer")
+
@permission_required('testapp.add_problem' , login_url="/code/1234")
@@ -467,77 +399,5 @@
return http.HttpResponseRedirect('/problems')
-def upload(request):
- """ upload handler, validates the form and calls handle_uploaded_file
- for processing further
- """
- user = request.user
- if user is None:
- return http.HttpResponseForbidden('You must be an signed in to create/edit a problem.')
-
- if request.method == 'POST':
- form = UploadForm(request.POST, request.FILES)
- if form.is_valid():
- submission_report = handle_uploaded_file(request)
- print "testing"
- print submission_report
-
- return respond(request, user, 'upload', {'report':submission_report})
- else:
- return http.HttpResponseForbidden('Oops something went wrong with the upload')
-
-def handle_uploaded_file(request):
- """ Handles uploaded data, pushes it to existing problem creating code
- TODO: 1. make efficient by putting actual database code Here
- 2. Add more security and validation
- """
- submission_data = request.FILES['file'].read()
- if '#---' in submission_data:
- all_submissions = submission_data.split('#---')[1:-1]
- # ^^ ignoring the first null and last __main__ code
- all_submissions = [ pykataupload.Submission(x) for x in all_submissions ]
- report = []
-
- for key,each_submission in enumerate(all_submissions):
- # TODO: handle these later by TaskQueues to avoid timeouts on big uploads
- # a good way would be to have ajax based status coming back to this page
- # about each problem in the uploaded file, their status, progress etc.
- each_submission.parse()
- request.POST.clear()
- request.POST.update (each_submission.data_dict)
- upload_status, upload_response = new_edit(request, internal=True)
-
- report.append ({'status':upload_status, 'name':each_submission['name'],
- 'upload_response':upload_response})
-
- # Yay this hack works :D
- return report
- else:
- return http.HttpResponseForbidden('The file you uploaded is not in appropriate format.')
-
-def shell(request):
- """ need to change user in the django.contrib way"""
-
- user = request.user
- statement=request.GET.get('statement','')
- if statement is not '':
-
- # the python compiler doesn't like network line endings
- statement = statement.replace('\r\n', '\n')
-
- # add a couple newlines at the end of the statement. this makes
- # single-line expressions such as 'class Foo: pass' evaluate happily.
- statement += '\n\n'
- print "statement"+statement
- # log and compile the statement up front
- try:
- logging.info('Compiling and evaluating:\n%s' % statement)
- compiled = compile(statement, '<string>', 'single')
- except:
- return HttpResponse(traceback.format_exc(),mimetype="text/plain")
-# pass
- return HttpResponse("",mimetype="text/plain")
- else:
- return respond(request, user, 'shell')