Checking if exam has been previously done by the user or not
authoramit@thunder
Mon, 14 Jun 2010 01:00:59 +0530
changeset 3 34d0c21e3352
parent 2 654c583fd78e
child 4 4d5422e5a45d
Checking if exam has been previously done by the user or not
testappproj/.database.sqlite3
testappproj/settings.py
testappproj/settings.pyc
testappproj/templates/appjs.js
testappproj/templates/code.html
testappproj/templates/problems.html
testappproj/testapp/forms.py
testappproj/testapp/forms.pyc
testappproj/testapp/models.py
testappproj/testapp/models.pyc
testappproj/testapp/views.py
testappproj/testapp/views.pyc
testappproj/urls.py
testappproj/urls.pyc
Binary file testappproj/.database.sqlite3 has changed
--- a/testappproj/settings.py	Mon May 31 19:18:57 2010 +0530
+++ b/testappproj/settings.py	Mon Jun 14 01:00:59 2010 +0530
@@ -67,6 +67,12 @@
     'django.contrib.auth.middleware.AuthenticationMiddleware',
 )
 
+#Recaptcha Public and Private Keys
+RECAPTCHA_PUB_KEY = "6LdLqLoSAAAAAGJK1NLgRA2-Tv1jSSBLgaNn7Bib"
+RECAPTCHA_PRIVATE_KEY = "6LdLqLoSAAAAAMCgMusFP0A1PS4vRSpeQliGPhtu"
+
+
+
 
 # Our own Auth Profile Module so that we can change django registration
 AUTH_PROFILE_MODULE="testapp.Test_User"
Binary file testappproj/settings.pyc has changed
--- a/testappproj/templates/appjs.js	Mon May 31 19:18:57 2010 +0530
+++ b/testappproj/templates/appjs.js	Mon Jun 14 01:00:59 2010 +0530
@@ -3,8 +3,3 @@
 				 "/code/" + id + "/");
 
 }
-function loadcode(id) {
-  $("#solve_" + id).load(location.protocol + "//" + location.host +
-				 "/run/" );
-
-}
--- a/testappproj/templates/code.html	Mon May 31 19:18:57 2010 +0530
+++ b/testappproj/templates/code.html	Mon Jun 14 01:00:59 2010 +0530
@@ -1,8 +1,37 @@
 {# {%extends "base.html"%} #}
+<script type="text/javascript">
+function run_code(params){
+
+if (window.XMLHttpRequest)
+  {// code for IE7+, Firefox, Chrome, Opera, Safari
+   
+   xmlhttp=new XMLHttpRequest();
+  }
+else
+  {// code for IE6, IE5
+  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
+  }
+xmlhttp.onreadystatechange=function()
+  {
+  if (xmlhttp.readyState==4 && xmlhttp.status==200)
+    {
+ document.getElementById("code_form").innerHTML=xmlhttp.responseText;
+    }
+  }
+xmlhttp.open("POST","/run/",true);
+xmlhttp.send(params);
+}
+function process_form(element) {
+      
+      var poststr = "user_code=" + encodeURI( document.getElementById("code-area").value ) +
+                    "&problem_id=" + encodeURI( document.getElementById("problem_id").value );
+      run_code(poststr);
+   }
+
+</script>
 {%block body%}
 <h2>{{ problem.name }}</h2>
 
- 
 {% comment %}
 {% load pykata_extras %}
 {% autoescape off %}
@@ -12,21 +41,19 @@
 {% endautoescape %}
 {% endcomment %}
 
-<h3>Examples</h3>
 <pre>
 {{ problem.examples }}
 </pre>
-
-  <form method="post" action="/run/">
+  <div id="code_form">
+    <form method="post" action="javascript:process_form(document.getElementById('code_form'));">
     <p><strong>Enter your solution here:</strong></p>
     <p><textarea id="code-area" name="user_code" rows="22" cols="80">
 {% ifequal pu.classname "ProblemUser" %}{{ pu.solution }}{% else %}{{ problem.skeleton }}{% endifequal %}
-
     </textarea></p>
-    <input type="hidden" name="problem_id" value="{{ problem.id }}" />
-    <p><input type="submit" name="submit" value="Run" /></p>
+    <input id="problem_id" type="hidden" name="problem_id" value="{{ problem.id }}" />
+    <p><input type="submit" name="submit" value="Done" ></p>
   </form>
-
+</div>
   <script language="javascript" type="text/javascript" src="/static/edit_area_full.js"></script>
   <script language="javascript" type="text/javascript">
     editAreaLoader.init({
@@ -34,9 +61,10 @@
       syntax: "python",
       start_highlight: true,
       allow_resize: "both",
+      cursor_position: "begin",
       font_size: 14,
       toolbar: "new_document, select_font, |, help",
       replace_tab_by_spaces: 4
     });
   </script>
-{%endblock%}
+  {%endblock%}
--- a/testappproj/templates/problems.html	Mon May 31 19:18:57 2010 +0530
+++ b/testappproj/templates/problems.html	Mon Jun 14 01:00:59 2010 +0530
@@ -24,7 +24,12 @@
 </table>
 
 <p>
-{% if user %}<a href="{% url testapp.views.new_edit %}">Create new problem</a>{% endif %}
+<form action="/completed" method="GET">
+<div>
+<input type="submit", value="Finished Exam">
+</div>
+</form>
 </p>
 
+
 {%endblock%}
--- a/testappproj/testapp/forms.py	Mon May 31 19:18:57 2010 +0530
+++ b/testappproj/testapp/forms.py	Mon Jun 14 01:00:59 2010 +0530
@@ -42,16 +42,18 @@
 
 class Test_UserForm(RegistrationForm):
 
-  fullname = forms.CharField(widget=forms.TextInput(attrs=attrs_dict))
+  Fullname = forms.CharField(widget=forms.TextInput(attrs=attrs_dict))
+  Address =  forms.CharField(widget=forms.TextInput(attrs=attrs_dict))
+  
   class Meta:
-        exclude = ('special_user',)
+        exclude = ('special_user','exam_done')
 
 
   def save(self, profile_callback=None):
     new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
                                                                 password=self.cleaned_data['password1'],
                                                                 email=self.cleaned_data['email'])
-    new_profile = Test_User(user=new_user, fullname=self.cleaned_data[fullname])
+    new_profile = Test_User(user=new_user, fullname=self.cleaned_data['Fullname'],address=self.cleaned_data['Address'])
     new_profile.save()
     return new_user
 
Binary file testappproj/testapp/forms.pyc has changed
--- a/testappproj/testapp/models.py	Mon May 31 19:18:57 2010 +0530
+++ b/testappproj/testapp/models.py	Mon Jun 14 01:00:59 2010 +0530
@@ -3,22 +3,6 @@
 from django.contrib.auth.models import Group, Permission
 
 
-
-# class ProblemPermission(models.Model):
-#     """Abstract page permissions
-#     """
-#     #who
-#     user = models.ForeignKey(User)
-#     #what
-#     can_change = models.BooleanField("can edit", default=False)
-#     can_add = models.BooleanField("can add", default=False)
-#     can_delete = models.BooleanField("can delete", default=False)
-
-    
-#     class Meta:
-#         abstract = True
-#         app_label = 'testapp'
-
 PROBLEM_CHOICES=(
     ('P', 'Plotting'),
     ('S', 'Scripting'),
@@ -54,8 +38,9 @@
 class Test_User(models.Model):
   #problem = models.ForeignKey('Problem')
   user = models.ForeignKey(User, unique=True)
-  fullname=models.CharField(max_length=255)
-
+  fullname=models.CharField(max_length=255,unique=True,blank=False)
+  address=models.CharField(max_length=255,unique=True,blank=False)
+  exam_done=models.BooleanField(default=False)
   
 class Score(models.Model):
   user = models.ForeignKey(User, unique=True)
Binary file testappproj/testapp/models.pyc has changed
--- 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')
 
   
Binary file testappproj/testapp/views.pyc has changed
--- a/testappproj/urls.py	Mon May 31 19:18:57 2010 +0530
+++ b/testappproj/urls.py	Mon Jun 14 01:00:59 2010 +0530
@@ -34,11 +34,10 @@
                        (r'^new/$', 'testappproj.testapp.views.new_edit'),
                        (r'^problems/$', 'testappproj.testapp.views.problems'),
                        (r'^run/$', 'testappproj.testapp.views.run'),
-                       (r'^upload/$', 'testappproj.testapp.views.upload'),
                        (r'^static/(?P<path>.*)$', 'django.views.static.serve',
      		      {'document_root': os.path.realpath(os.path.dirname(
         		sys.modules[__name__].__file__) + '/static/')}),
-                       (r'^shell/$', 'testappproj.testapp.views.shell')
+                       (r'^completed/$','testappproj.testapp.views.complete')
 
 )
                         
Binary file testappproj/urls.pyc has changed