# -*- coding: utf-8
# -*- Mode: Python; py-indent-offset: 4 -*-
""" Inline Choice type """
__version__ = "$Revision:33$"[11:-2]
import Globals
from AccessControl import ClassSecurityInfo
from OFS.SimpleItem import SimpleItem
import re
from zope.interface import implements
from Products.QTAuthor.common import commons
from Products.QTAuthor.BaseQuestion import BaseQuestion
from Products.QTAuthor.Permissions import *
from Products.QTAuthor.interfaces import IBaseQuestion, IQuestionAuthoring
class InlineChoiceType(BaseQuestion):
""" """
meta_type = 'inline_choice_type'
security = ClassSecurityInfo()
security.declareObjectPublic()
implements(IBaseQuestion, IQuestionAuthoring)
manage_options = SimpleItem.manage_options
def __init__(self, id):
self.id=id
self.gapvariants = {}
BaseQuestion.__init__(self)
security.declarePrivate('manage_afterAdd')
def manage_afterAdd(self, item, container):
self.index_object()
security.declareProtected(perm_view_question, 'getType')
def getType(self):
return 'inline_choice_type'
security.declareProtected(perm_edit_question, 'setVariants')
def setVariants(self, gapvariants):
self.gapvariants = gapvariants
security.declareProtected(perm_view_question, 'getVariants')
def getVariants(self):
""" """
return self.gapvariants
security.declareProtected(perm_view_question, 'getMaxPoints')
def getMaxPoints(self):
return 1.0
security.declareProtected(perm_edit_question, 'changeQuestion')
def changeQuestion(self, REQUEST):
""" """
self.setCommonData(REQUEST)
# CHECKME: findall vs. finditer
allgaps = re.findall('\[.*?\]', self.getQuestion(REQUEST))
gapscount = len(allgaps)
self.reindex_object()
message = []
# display message if at least one gap [] is empty
for gap in allgaps:
# check is that gap empty
if gap == "[]":
message.append("You have to write correct answer into each gap.")
break;
if gapscount == 0:
message.append("Mark words which will be replaced with choice menu!")
# if everything is correct
if len(message) == 0:
return REQUEST.RESPONSE.redirect(self.absolute_url()+'/inline_choice2.html')
return REQUEST.RESPONSE.redirect(self.absolute_url() +'/edit?message='+'
'.join(message))
security.declareProtected(perm_edit_question, 'setGapsCount')
def setGapsCount(self, gapscount):
self.gapscount = gapscount
security.declareProtected(perm_view_question, 'getGapsCount')
def getGapsCount(self):
return self.gapscount
def replace(self, txt):
x = re.findall('\[.*?\]', txt)
i = 1
gapvariants = self.getVariants()
try:
for k in x:
suva = u'\n'
for j in range(1, 100):
cv = gapvariants.get('gap'+str(i)+'_'+str(j))
if cv != None and cv != "":
if not isinstance(cv, unicode):
cv = cv.decode('utf-8')
suva += ''+cv+'\n'
suva += '\n'
i += 1
txt = txt.replace(k, suva, 1)
except (UnicodeDecodeError, UnicodeEncodeError), u:
print "txt::", txt
print "k::", k
print "suva::", suva
print "gv::", gapvariants
raise u
return txt
security.declareProtected(perm_edit_question, 'setTextGaps')
def setTextGaps(self):
txt = self.getQuestion()
allgaps = re.findall('\[.*?\]', txt)
textgaps = {}
i = 1
for gap in allgaps:
textgaps['gap'+str(i)] = gap
i += 1
self.textgaps = textgaps
security.declareProtected(perm_view_question, 'getTextGaps')
def getTextGaps(self):
return self.textgaps
def gaps(self):
""" """
txt = self.getQuestion().decode('utf-8')
allgaps = re.finditer('\[.*?\]', txt)
allgaps1 = re.findall('\[.*?\]', txt)
correctanswer = {}
self.textgaps = {}
p = None
table = '
'
self._p_changed = True
return table
def add_variants(self, REQUEST):
""" """
# save variants
gapvariants = {}
gapscount = self.getGapsCount()
for i in range(1, gapscount + 1):
counter = 1
for j in range(1, 100):
if REQUEST.has_key('gap'+str(i)+'_'+str(j)):
if REQUEST.get('gap'+str(i)+'_'+str(j)) != '':
gapvariants['gap'+str(i)+'_'+str(counter)] = REQUEST.get('gap'+str(i)+'_'+str(j)) #.decode('utf-8')
counter = counter + 1
self.setVariants(gapvariants)
# send to waramu if needed
self._sendToWaramu()
return REQUEST.RESPONSE.redirect(self.absolute_url())
security.declareProtected(perm_view_question, 'getGapstext')
def getGapstext(self): #kõik lüngad, variandid ja punktid tabelina
""" """
i = 1
table = u''+self.utranslate('Gaps')+' | '
table += ''+self.utranslate('Choices')+' |
'
gapvariants = self.getVariants()
textgaps = self.getTextGaps()
gapscount = self.getGapsCount()
while i < gapscount + 1:
try:
table += ''+textgaps.get('gap'+str(i))+' | '
except UnicodeDecodeError:
table += '
'+textgaps.get('gap'+str(i)).decode('utf-8')+' | '
table += '1. '+gapvariants.get('gap'+str(i)+'_1').decode('utf-8')+' | '
for j in range(2, 100):
gapvariant = gapvariants.get('gap'+str(i)+'_'+str(j))
if gapvariant != '' and gapvariant != None:
table += '
| '+str(j)+'. '+gapvariant.decode('utf-8')+' | '
j += 1
i += 1
table += '
'
return table
def xml2(self, fullURLs=False):
""" """
xml = u'\n'
xml += '\n'
for i in range(1, self.gapscount + 1):
xml=xml+ '\n'
xml=xml+ '\n'
xml=xml+ 'v1\n'
xml=xml+ '\n'
xml=xml+ '\n'
xml += '\n' % i
xml=xml+ '\n'
xml=xml+ '\n'
question = self.getQuestion()
if not isinstance(question, unicode):
question = question.decode('utf-8')
if fullURLs:
from xml.sax.saxutils import escape
question = escape(question)
question = self.replace(question)
if not fullURLs:
question = self.replaceImageurl(question)
xml = xml + question
xml=xml+ '
\n'
xml=xml+ '\n'
# response processing for all the gaps
xml += '\n'
for i in range(1, self.gapscount + 1):
xml += '\n'
xml += '\n'
xml += '\n'
xml += '\n' % (i, self.getId())
xml += '\n' % (i, self.getId())
xml += '\n'
xml += '\n' % i
xml += '1\n'
xml += '\n'
xml += '\n'
xml += '\n'
xml += '\n' % i
xml += '0\n'
xml += '\n'
xml += '\n'
xml += '\n'
xml=xml+ '\n'
xml=xml+ '\n'
return xml
security.declareProtected('QTAuthor: View question', 'getInteractionType')
def getInteractionType(self):
""" """
return "inlineChoiceInteraction"
def importQuestion(self, data, dom):
""" """
additionalFiles = {}
questext = data.split('')
questext = questext[1].split('')
questext = questext[0]
images = re.findall('src\=".*?\"', questext)
url = self.get_root().absolute_url()
for im in images:
z = im
im = im.split('"')
im = im[1]
new_img_id = self.random_generator('image_')
additionalFiles[im] = new_img_id
questext = questext.replace(z, 'src="'+url+'/images/'+new_img_id+'"', 1)
# def recukrsiivne(self, element, quetionText=""):
#
# for node in idemBody.childNodes:
# if node is text node:
# questionText += node.nodeValue
# if node is 'interaction' bla bla:
# quesitontext += "[vairant]"
# if node is tavaline node:
# questionText += self.recurksriine(node)
#
# return qustionText
# itemBody = getElement('itembody')
# questonText = self.recukrsiivne(itemBody, "")
allvariants = {}
gapvariants = {}
rightanswers = []
responseDeclarations = dom.getElementsByTagName("responseDeclaration")
for res in responseDeclarations:
correctresponse = res.getElementsByTagName("correctResponse")
correctanswer = correctresponse[0].getElementsByTagName("value")
correct = correctanswer[0].childNodes[0].data
rightanswers.append(correct)
interactions = dom.getElementsByTagName("inlineChoiceInteraction")
for i in range(1, len(interactions)+1):
variants = interactions[i-1].getElementsByTagName("inlineChoice")
for j in range(1, len(variants)+1):
varIdentifier = variants[j-1].getAttribute("identifier")
var = variants[j-1].childNodes
vartext = var[0].data
allvariants[varIdentifier] = vartext
gapvariants['gap'+str(i)+'_'+str(j)] = vartext.encode('utf-8')
#kuna findall-ga (ega finditer-ga) otsing ei taha toimida, siis ajutiselt niimoodi, et vähemalt oma küsimuste import toimiks.
vartext = ''+vartext+''
if j == 1:
questext = questext.replace(vartext.encode('utf-8'),'['+vartext.encode('utf-8')+']')
else:
questext = questext.replace(vartext.encode('utf-8'), '')
questext = questext.replace('', '')
questext = questext.replace('', '')
x = re.findall('\', questext)
for k in x:
index = x.index(k)
correct = rightanswers[index]
var = allvariants.get(correct)
questext = questext.replace(k, '['+var+']', 1)
self.setQuestion(questext)
self.setTextGaps()
self.setGapsCount(len(interactions))
self.setVariants(gapvariants)
self.setWhichImages(questext)
return additionalFiles
def getQuestionStats(self):
""" """
table = 'Gaps | Frequencies |
'
variants = self.getVariants()
query = {'getQuesId': self.getId(),}
results = self.cat_answers(query)
array = {}
for result in results:
ans_obj = result.getObject()
ans_send = ans_obj.getAnswerSend()
pairs = re.findall('\.*?\<\/pair\>', ans_send)
for pair in pairs:
pair_index = pairs.index(pair)
cm = re.compile('(.*?)', re.S)
val = cm.search(ans_send).group(1)
val = val.replace('v','')
var = variants.get('gap'+str(pair_index+1)+'_'+val)
gap = 'gap'+str(pair_index+1)
if gap in array:
gaparray = array.get(gap)
else:
gaparray = []
gaparray.append(var)
array[gap] = gaparray
for i in range(1, len(array)+1):
table += 'gap'+str(i)+' | '
gapanswers = array.get('gap'+str(i))
for j in range(1, 100):
if variants.get('gap'+str(i)+'_'+str(j)) != None:
variant = variants.get('gap'+str(i)+'_'+str(j))
varcount = gapanswers.count(variant)
table += variant + '=' +str(varcount) +' '
table += ' |
'
return table
def getCSVstats(self, ans_send, frequencies):
import re
text = ""
ques_id = self.getId()
if ques_id in frequencies:
array = frequencies.get(ques_id)
else:
array = {}
pairs = re.findall('\.*?\<\/pair\>', ans_send)
variants = self.getVariants()
for pair in pairs:
pair_index = pairs.index(pair)
cm = re.compile('(.*?)', re.S)
val = cm.search(pair).group(1)
val = val.replace('v','')
var = variants.get('gap'+str(pair_index+1)+'_'+val)
text += var + ';'
gap = 'gap'+str(pair_index+1)
if gap in array:
gaparray = array.get(gap)
else:
gaparray = []
gaparray.append(var)
array[gap] = gaparray
frequencies[ques_id] = array
return {'csvtext': text, 'frequencies': frequencies}
Globals.InitializeClass(InlineChoiceType)
# EOF