Commit 85e8b3a2 by Piotr Mitros

Wiki now supports circuits, modulo bugs

parent 510dd854
from django.db import models
from django.contrib.auth.models import User
import uuid
class ServerCircuit(models.Model):
# Later, add owner, who can edit, part of what app, etc.
name = models.CharField(max_length=32, unique=True, db_index=True)
schematic = models.TextField(blank=True)
def __unicode__(self):
return self.name+":"+self.schematic[:8]
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
from djangomako.shortcuts import render_to_response, render_to_string
from django.shortcuts import redirect
import os
from django.conf import settings
from django.http import Http404
from models import ServerCircuit
import json
import xml.etree.ElementTree
from django.http import HttpResponse
def circuit_line(circuit):
if not circuit.isalnum():
raise Http404()
try:
sc = ServerCircuit.objects.get(name=circuit)
schematic = sc.schematic
print "Got"
except:
schematic = ''
print "not got"
print "X", schematic
circuit_line = xml.etree.ElementTree.Element('input')
circuit_line.set('type', 'hidden')
circuit_line.set('class', 'schematic')
circuit_line.set('width', '640')
circuit_line.set('height', '480')
circuit_line.set('name', 'schematic')
circuit_line.set('id', 'schematic_'+circuit)
circuit_line.set('value', schematic) # We do it this way for security -- guarantees users cannot put funny stuff in schematic.
return xml.etree.ElementTree.tostring(circuit_line)
def edit_circuit(request, circuit):
try:
sc = ServerCircuit.objects.get(name=circuit)
except:
sc = None
if not circuit.isalnum():
raise Http404()
response = render_to_response('edit_circuit.html', {'name':circuit,
'circuit_line':circuit_line(circuit)})
response['Cache-Control'] = 'no-cache'
return response
def save_circuit(request, circuit):
if not circuit.isalnum():
raise Http404()
print dict(request.POST)
schematic = request.POST['schematic']
print schematic
try:
sc = ServerCircuit.objects.get(name=circuit)
except:
sc = ServerCircuit()
sc.name = circuit
sc.schematic = schematic
print ":", sc.schematic
sc.save()
json_str = json.dumps({'results': 'success'})
response = HttpResponse(json_str, mimetype='application/json')
response['Cache-Control'] = 'no-cache'
return response
...@@ -116,3 +116,4 @@ if __name__=='__main__': ...@@ -116,3 +116,4 @@ if __name__=='__main__':
print evaluator({'a': 2.2997471478310274, 'k': 9, 'm': 8, 'x': 0.66009498411213041}, {}, "5") print evaluator({'a': 2.2997471478310274, 'k': 9, 'm': 8, 'x': 0.66009498411213041}, {}, "5")
print evaluator({},{}, "-1") print evaluator({},{}, "-1")
print evaluator({},{}, "-(7+5)") print evaluator({},{}, "-(7+5)")
print evaluator({},{}, "QWSEKO")
...@@ -162,6 +162,7 @@ class LoncapaModule(XModule): ...@@ -162,6 +162,7 @@ class LoncapaModule(XModule):
return json.dumps({"error":"Past due date"}) return json.dumps({"error":"Past due date"})
elif dispatch=='problem_check': elif dispatch=='problem_check':
response = self.check_problem(get) response = self.check_problem(get)
print response
elif dispatch=='problem_reset': elif dispatch=='problem_reset':
response = self.reset_problem(get) response = self.reset_problem(get)
elif dispatch=='problem_save': elif dispatch=='problem_save':
...@@ -231,19 +232,27 @@ class LoncapaModule(XModule): ...@@ -231,19 +232,27 @@ class LoncapaModule(XModule):
print "cpdr" print "cpdr"
raise Http404 raise Http404
self.attempts = self.attempts + 1
self.lcp.done=True
answers=dict() answers=dict()
# input_resistor_1 ==> resistor_1 # input_resistor_1 ==> resistor_1
for key in get: for key in get:
answers['_'.join(key.split('_')[1:])]=get[key] answers['_'.join(key.split('_')[1:])]=get[key]
correct_map = self.lcp.grade_answers(answers) try:
ocm = lcp.correct_map
oa = lcp.answers
correct_map = self.lcp.grade_answers(answers)
except:
lcp.correct_map = ocm # HACK: Reset state
lcp.answers = oa
return json.dumps({'success':'syntax'})
self.attempts = self.attempts + 1
self.lcp.done=True
success = True success = 'finished'
for i in correct_map: for i in correct_map:
if correct_map[i]!='correct': if correct_map[i]!='correct':
success = False success = 'errors'
js=json.dumps({'correct_map' : correct_map, js=json.dumps({'correct_map' : correct_map,
'success' : success}) 'success' : success})
......
...@@ -6,7 +6,8 @@ from xml.dom.minidom import parse, parseString ...@@ -6,7 +6,8 @@ from xml.dom.minidom import parse, parseString
from calc import evaluator from calc import evaluator
def strip_dict(d): def strip_dict(d):
''' Takes a dict. Returns an identical dict, with all non-word keys stripped out. ''' ''' Takes a dict. Returns an identical dict, with all non-word
keys stripped out. '''
d=dict([(k, float(d[k])) for k in d if type(k)==str and \ d=dict([(k, float(d[k])) for k in d if type(k)==str and \
k.isalnum() and \ k.isalnum() and \
(type(d[k]) == float or type(d[k]) == int) ]) (type(d[k]) == float or type(d[k]) == int) ])
......
...@@ -107,6 +107,7 @@ INSTALLED_APPS = ( ...@@ -107,6 +107,7 @@ INSTALLED_APPS = (
'staticbook', 'staticbook',
'simplewiki', 'simplewiki',
'track', 'track',
'circuit',
# Uncomment the next line to enable the admin: # Uncomment the next line to enable the admin:
# 'django.contrib.admin', # 'django.contrib.admin',
# Uncomment the next line to enable admin documentation: # Uncomment the next line to enable admin documentation:
...@@ -192,7 +193,7 @@ if ASKBOT_ENABLED: ...@@ -192,7 +193,7 @@ if ASKBOT_ENABLED:
'south', 'south',
'askbot.deps.livesettings', 'askbot.deps.livesettings',
'askbot', 'askbot',
'keyedcache', #'keyedcache', # TODO: Main askbot tree has this installed, but we get intermittent errors if we include it.
'robots', 'robots',
'django_countries', 'django_countries',
'djcelery', 'djcelery',
......
# Source: django-simplewiki. GPL license.
import sys, os import sys, os
# allow mdx_* parsers to be just dropped in the simplewiki folder # allow mdx_* parsers to be just dropped in the simplewiki folder
......
# Source: django-simplewiki. GPL license.
from django.contrib import admin from django.contrib import admin
from django import forms from django import forms
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
...@@ -56,4 +58,4 @@ class PermissionAdmin(admin.ModelAdmin): ...@@ -56,4 +58,4 @@ class PermissionAdmin(admin.ModelAdmin):
admin.site.register(Article, ArticleAdmin) admin.site.register(Article, ArticleAdmin)
admin.site.register(Revision, RevisionAdmin) admin.site.register(Revision, RevisionAdmin)
admin.site.register(Permission, PermissionAdmin) admin.site.register(Permission, PermissionAdmin)
admin.site.register(ArticleAttachment, AttachmentAdmin) admin.site.register(ArticleAttachment, AttachmentAdmin)
\ No newline at end of file
#!/usr/bin/env python #!/usr/bin/env python
print "Hello"
''' '''
WikiLink Extention for Python-Markdown WikiLink Extention for Python-Markdown
====================================== ======================================
......
#!/usr/bin/env python
'''
Image Circuit Extension for Python-Markdown
======================================
circuit:name becomes the circuit.
'''
import simplewiki.settings as settings
import markdown
from markdown import etree_loader
from djangomako.shortcuts import render_to_response, render_to_string
ElementTree=etree_loader.importETree()
class CircuitExtension(markdown.Extension):
def __init__(self, configs):
for key, value in configs :
self.setConfig(key, value)
def add_inline(self, md, name, klass, re):
pattern = klass(re)
pattern.md = md
pattern.ext = self
md.inlinePatterns.add(name, pattern, "<reference")
def extendMarkdown(self, md, md_globals):
print "Here"
self.add_inline(md, 'circuit', CircuitLink, r'^circuit:(?P<name>[a-zA-Z0-9]*)$')
class CircuitLink(markdown.inlinepatterns.Pattern):
def handleMatch(self, m):
name = m.group('name')
if not name.isalnum():
return ElementTree.fromstring("<div>Circuit name must be alphanumeric</div>")
return ElementTree.fromstring(render_to_string('show_circuit.html', {'name':name}))
def makeExtension(configs=None) :
print "Here"
return CircuitExtension(configs=configs)
# Source: https://github.com/mayoff/python-markdown-mathjax # Source: https://github.com/mayoff/python-markdown-mathjax
print "Hello"
import markdown import markdown
class MathJaxPattern(markdown.inlinepatterns.Pattern): class MathJaxPattern(markdown.inlinepatterns.Pattern):
......
...@@ -247,6 +247,7 @@ class Revision(models.Model): ...@@ -247,6 +247,7 @@ class Revision(models.Model):
# Create pre-parsed contents - no need to parse on-the-fly # Create pre-parsed contents - no need to parse on-the-fly
ext = WIKI_MARKDOWN_EXTENSIONS ext = WIKI_MARKDOWN_EXTENSIONS
print "Waka", WIKI_MARKDOWN_EXTENSIONS
ext += ["wikilinks(base_url=%s/)" % reverse('wiki_view', args=('',))] ext += ["wikilinks(base_url=%s/)" % reverse('wiki_view', args=('',))]
self.contents_parsed = markdown(self.contents, self.contents_parsed = markdown(self.contents,
extensions=ext, extensions=ext,
......
...@@ -91,9 +91,10 @@ WIKI_MARKDOWN_EXTENSIONS = getattr(settings, 'SIMPLE_WIKI_MARKDOWN_EXTENSIONS', ...@@ -91,9 +91,10 @@ WIKI_MARKDOWN_EXTENSIONS = getattr(settings, 'SIMPLE_WIKI_MARKDOWN_EXTENSIONS',
'mathjax', 'mathjax',
'camelcase', # CamelCase-style wikilinks 'camelcase', # CamelCase-style wikilinks
'video', # In-line embedding for YouTube, etc. 'video', # In-line embedding for YouTube, etc.
#'image' # In-line embedding for images - too many bugs. It has a failed REG EXP. 'circuit'
]) ])
print WIKI_MARKDOWN_EXTENSIONS
WIKI_IMAGE_EXTENSIONS = getattr(settings, WIKI_IMAGE_EXTENSIONS = getattr(settings,
'SIMPLE_WIKI_IMAGE_EXTENSIONS', 'SIMPLE_WIKI_IMAGE_EXTENSIONS',
......
...@@ -9,6 +9,11 @@ ...@@ -9,6 +9,11 @@
<link rel="stylesheet" href="/static/css/local.css" type="text/css" media="all" /> <link rel="stylesheet" href="/static/css/local.css" type="text/css" media="all" />
<link href="/static/css/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css"/> <link href="/static/css/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="/static/simplewiki/js/bsn.AutoSuggest_c_2.0.js"></script> <script type="text/javascript" src="/static/simplewiki/js/bsn.AutoSuggest_c_2.0.js"></script>
<script type="text/javascript" src="/static/js/schematic.js"></script>
<script type="text/javascript" src="/static/lib/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="/static/js/video_player.js"></script>
<script type="text/javascript"> <script type="text/javascript">
function set_related_article_id(s) { function set_related_article_id(s) {
document.getElementById('wiki_related_input_id').value = s.id; document.getElementById('wiki_related_input_id').value = s.id;
...@@ -35,6 +40,24 @@ ...@@ -35,6 +40,24 @@
displayMath: [ ['$$','$$'], ["\\[","\\]"]]} displayMath: [ ['$$','$$'], ["\\[","\\]"]]}
}); });
</script> <script type="text/javascript" src="/static/lib/mathjax/MathJax.js?config=TeX-AMS_HTML-full"></script> </script> <script type="text/javascript" src="/static/lib/mathjax/MathJax.js?config=TeX-AMS_HTML-full"></script>
<script>
$(function(){
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
$(".div_wiki_circuit").each(function(d,e) {
id = $(this).attr("id");
name = id.substring(17);
//alert(name);
$("#"+id).load("/edit_circuit/"+name);
f=this;
});
update_schematics();});
</script>
{% block wiki_head %} {% block wiki_head %}
{% endblock %} {% endblock %}
</head> </head>
......
...@@ -37,6 +37,9 @@ urlpatterns = ('', ...@@ -37,6 +37,9 @@ urlpatterns = ('',
name='auth_password_reset_complete'), name='auth_password_reset_complete'),
url(r'^password_reset_done/$',django.contrib.auth.views.password_reset_done, url(r'^password_reset_done/$',django.contrib.auth.views.password_reset_done,
name='auth_password_reset_done'), name='auth_password_reset_done'),
# url(r'^show_circuit/(?P<circuit>[^/]*)$', 'circuit.views.show_circuit'),
url(r'^edit_circuit/(?P<circuit>[^/]*)$', 'circuit.views.edit_circuit'),
url(r'^save_circuit/(?P<circuit>[^/]*)$', 'circuit.views.save_circuit'),
) )
if settings.ASKBOT_ENABLED: if settings.ASKBOT_ENABLED:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment