def test_clones_questions_in_the_questionnaire_with_their_order_objects(self): question3 = Question.objects.create(text='B. Number of cases tested', UID=Question.next_uid(), answer_type='Number') question4 = Question.objects.create(text='C. Number of cases positive', UID=Question.next_uid(), answer_type='Number') QuestionGroupOrder.objects.create(order=1, question_group=self.parent10, question=self.primary_question) QuestionGroupOrder.objects.create(order=2, question_group=self.parent10, question=self.question1) QuestionGroupOrder.objects.create(order=3, question_group=self.parent10, question=self.question2) QuestionGroupOrder.objects.create(order=4, question_group=self.parent120, question=question3) QuestionGroupOrder.objects.create(order=5, question_group=self.parent120, question=question4) self.assertEqual(5, Question.objects.all().count()) self.parent10.question.add(question3, question4, self.question1, self.question1) new, old = QuestionnaireClonerService(self.questionnaire).clone() self.assertEqual(5, Question.objects.all().count()) self.assertEqual(5, len(old.get_all_questions())) self.assertEqual(5, len(new.get_all_questions()))
def save(self, commit=True): question = super(QuestionForm, self).save(commit=False) question.UID = Question.next_uid() if commit: question.save() self._save_options_if_multichoice(question) return question
def map(request, json_req=None): user = request.user player = Player.objects.get(user=user) country = player.country ct = dict() #ct['alpha3'] = ["gmb", "afg", "cub", "hun", "mng", "swe", "alb", "cyp", "ind", "mrt", "syr", "arg", "cze", "irn", "ner", "tcd", "aut", "deu", "irq", "nga", "tha", "bdi", "dnk", "isr", "nic", "tun", "bel", "dza", "ita", "nld", "tur", "bgr", "egy", "jor", "nor", "tza", "bih", "eri", "kaz", "pak", "uga", "bra", "esp", "ken", "pol", "ukr", "caf", "eth", "lbn", "rou", "usa", "can", "fin", "lby", "rus", "ven", "che", "fra", "mar", "sdn", "vnm", "chn", "gbr", "mex", "sen", "xxk", "civ", "gib", "mkd", "som", "yem", "cmr", "grc", "mli", "srb", "zaf", "cod", "gtm", "mlt", "ssd", "col", "hrv", "mmr", "svn"] ct['alpha3'] = [ "aaaaaa", "cpv", "ind", "moz", "ssd", "afg", "cri", "iot", "mrt", "sssss", "ago", "cub", "irl", "msr", "stp", "aia", "cym", "irn", "mus", "sur", "alb", "cyp", "irq", "mwi", "svk", "and", "cze", "isl", "mys", "svn", "are", "deu", "isr", "nam", "swe", "arg", "dji", "ita", "ner", "swz", "arm", "dma", "jam", "nga", "syc", "atg", "dnk", "jey", "nic", "syr", "aus", "dom", "jjjjj", "niu", "tca", "aut", "dza", "jor", "nld", "tcd", "aze", "ecu", "jpn", "nor", "tgo", "bbbbb", "egy", "kaz", "npl", "tha", "bdi", "eri", "ken", "nru", "tjk", "bel", "esp", "kgz", "nzl", "tkl", "ben", "est", "khm", "omn", "tkm", "bfa", "eth", "kir", "ooooo", "tls", "bgd", "fin", "kna", "pak", "ton", "bgr", "fji", "kor", "pan", "tto", "bhr", "flk", "kwt", "pcn", "ttttt", "bhs", "fra", "lao", "per", "tun", "bih", "fro", "lbn", "phl", "tur", "blr", "fsm", "lbr", "plw", "tuv", "blz", "gab", "lby", "png", "twn", "bmu", "gbr", "lca", "pol", "tza", "bol", "ggy", "lie", "prk", "uga", "bra", "gha", "lka", "prt", "ukr", "brb", "gib", "lso", "pry", "ury", "brn", "gin", "ltu", "qat", "usa", "btn", "gmb", "lux", "rou", "bwa", "gnb", "lva", "rus", "uzb", "caf", "gnq", "mar", "rwa", "vat", "can", "grc", "mco", "sau", "vct", "che", "grd", "mdg", "sdn", "ven", "chl", "grl", "mdv", "sen", "vgb", "chn", "gtm", "mex", "sgp", "vnm", "civ", "guy", "mhl", "shn", "vut", "cmr", "hnd", "mkd", "slb", "wsm", "cod", "hrv", "mli", "sle", "xxk", "cog", "hti", "mlt", "slv", "yem", "c*k", "hun", "mmr", "smr", "zaf", "col", "idn", "mne", "som", "zmb", "com", "imn", "mng", "srb", "zwe" ] if json_req == "restart": qs = Question.get_questions(country) q_list = list() game = Game(player=player) game.save() for q in qs: answers = q.get_mix_answers() aq = AnsweredQuestion(question=q, game=game) aq.option1 = answers[0] aq.option2 = answers[1] aq.option3 = answers[2] aq.option4 = answers[3] aq.save() qd = q.to_dict() qd['answers'] = answers qd['cnt_list'] = ast.literal_eval(q.cnt_list) qd['ans_cnt_names'] = [] if q._type == 'MB': for c in qd['answers']: qd['ans_cnt_names'].append(Country.get_country(c)) qd['game_id'] = game.id if q._type == 'MB': qd['answer_code'] = q.answer_code q_list.append(qd) ct['questions'] = q_list return JsonResponse(ct) return render(request, 'map.html', context=ct)
def test_get_next_uid_given_given_largest_uid_is_9th(self): Question.objects.create(text='question 3', UID='C00009', answer_type='Number') self.assertEqual('00010', Question.next_uid())
def test_get_next_uid_given_given_largest_uid_question(self): self.assertEqual('00004', Question.next_uid())
def test_child_question_uid_is_parent_question_uid(self): parent_question = Question.objects.create(text='question text', UID='abc123', answer_type='Text') child_question_with_same_uid = Question(text='revised text', UID='abc123', answer_type='Text', parent=parent_question) child_question_with_same_uid.save() self.failUnless(child_question_with_same_uid.id)
def __handleQuestion(self, type, row, type_Column, level_number_column, text_question_Column, _questions_rows, _choices_array, qNumber, questionset, log, _checks, _debug, questionnaire, mode=EXACT_MATCH, percentage=0.75, infer_function=None): try: slug = None text_en = None if level_number_column.value.startswith('h'): text_en = str(level_number_column.value) + '. ' + str( text_question_Column.value) else: level = len(level_number_column.value.split('.')) - 1 text_en = 'h%s. %s' % (str(level), str(text_question_Column.value)) dataType_column = None if type == self.CATEGORY: dataType_column = CommentPlaceholder() else: dataType_column = row[3] if row[7].value: slug = row[7].value else: slug = convert_text_to_slug(str(row[1].value)[:50]) slug = self.get_slug(slug, questionnaire) if row[5].value: helpText = row[5].value else: helpText = '' _tooltip = False if row[6].value: if str(row[6].value).lower() == 'yes': _tooltip = True #If has dependencies if row[8].value: try: dependencies_list = row[8] list_dep_aux = dependencies_list.value.split('|') question_num_parent = None try: question_num_parent = _questions_rows.get( list_dep_aux[0]).number except AttributeError: ''' If this is a merge, the dependant question can already be on the questionset, lets try looking for it ''' try: question = Question.objects.get( slug_fk__slug1=list_dep_aux[0], questionset=questionset) _questions_rows[ list_dep_aux[0]] = question_num_parent question_num_parent = question.number _choices_array[ list_dep_aux[0]] = self.__getChoices(question) except Question.DoesNotExist: raise Exception( 'The dependant with slug %s does not exist.' % (list_dep_aux[0])) index_aux = int(str(list_dep_aux[1])) - 1 choice_parent_list = _choices_array.get(list_dep_aux[0]) choice_parent = choice_parent_list[index_aux] _checks = 'dependent=\"%s,%s\"' % ( str(question_num_parent), str(choice_parent)) except: raise try: questionNumber = self.__handleQuestionNumber( level_number_column.value, qNumber, questionset) except: if type == self.QUESTION: log += "\n%s - Error to create question number %s" % ( type_Column.row, text_en) elif type == self.CATEGORY: log += "\n%s - Error to create Category number %s" % ( type_Column.row, text_en) self.writeLog(log) raise #print slug #Create or load slug slugs = Slugs.objects.filter(slug1=slug, description=text_en) if len(slugs) <= 0: slug_db = Slugs(slug1=slug, description=text_en) slug_db.save() else: slug_db = slugs[0] visible_default = False if row[10].value: if str(row[10].value).lower() == 'visible': visible_default = True is_category = None is_stats = None if type == self.QUESTION: is_stats = True is_category = False elif type == self.CATEGORY: is_stats = False is_category = True try: question = Question.objects.get(slug_fk__slug1=slug_db.slug1, questionset=questionset) question.text_en = text_en question.number = str(questionNumber) question.type = dataType_column.value question.help_text = helpText question.stats = is_stats question.category = is_category question.tooltip = _tooltip question.checks = _checks question.visible_default = visible_default except Question.DoesNotExist: question = Question(questionset=questionset, text_en=text_en, number=str(questionNumber), type=dataType_column.value, help_text=helpText, slug=slug, slug_fk=slug_db, stats=is_stats, category=is_category, tooltip=_tooltip, checks=_checks, visible_default=visible_default, disposition=self.__processDisposition( row[11].value.lower())) if dataType_column.value in ['open-validated']: ardict = {} if row[4].value: # some basic types dont need regex known_validations = { "integer": "[+-]?\d+", "decimal": "[+-]?\d*([.]\d*)?", "scientific": "[+-]?\d*([.]\d*)?e[+-]?\d*([.]\d*)?", "range": "[+\-]?\d*([.]\d*);[+\-]?\d*([.]\d*)", "date": "\d{2}/\d{2}/\d{4}", "time": "\d{2}:\d{2}:\d{2}", "datetime": "\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}", "text": ".*" } try: ardict['regex'] = known_validations[row[4].value] ardict['base'] = row[4].value except KeyError: # If this is not known, try to validate it as a regex try: re.compile(row[4].value) ardict['regex'] = row[4].value except re.error: raise Exception( "--ERROR: The regex on row %d, column 4 is not valid" % (type_Column.row)) if row[5].value: split = row[5].value.split('|') lensplit = len(split) if lensplit == 1: ardict['unit'] = split[0] question.help_text = "" elif lensplit == 2: ardict['unit'] = split[0] ardict['unit_desc'] = split[1] question.help_text = "" elif lensplit == 3: ardict['unit'] = split[0] ardict['unit_desc'] = split[1] question.help_text = split[2] else: raise Exception( "-- ERROR: Invalid number of segments on help text row %d, column 5. Max syntax is unit|desc|help_text" % (type_Column.row)) question.metadata = json.dumps(ardict) if not _debug: question.save() if type == self.QUESTION: log += '\n%s - Question created %s ' % (type_Column.row, question) elif type == self.CATEGORY: log += '\n%s - Category created %s ' % (type_Column.row, question) _questions_rows[slug] = question if type == self.QUESTION: if dataType_column.value in [ 'choice', 'choice-freeform', 'choice-multiple', 'choice-multiple-freeform' ]: _choices_array_aux = [] # Parse of values list values_list = row[4] if (values_list != None and values_list.value != None): list_aux = values_list.value.split('|') _choices_array[slug] = self.__processChoices( type_Column.row, question, list_aux, log, debug=_debug, mode=mode, match_percentage=percentage, infer_function=infer_function) if dataType_column.value in [ 'choice-yesno', 'choice-yesnodontknow' ]: _choices_array[slug] = ['yes', 'no', 'dontknow'] except: log += "\n%s - Error to save question %s" % (type_Column.row, text_en) self.writeLog(log) raise
#coding=utf-8 import sys sys.path.append("../") from questionnaire.models import Choice, Question import pandas as pd df = pd.read_csv("data.csv") for i in df.index: print(i) q = Question(qid=df.loc[i, "ID"], qcontent=df.loc[i, "content"], qclass=df.loc[i, "class"]) q.save() print("import Question completed") for i in df.index: print(i) q = Question.objects.get(qid=i + 1) c = Choice(question=q, ccontent='是', votes=0) c.save() c = Choice(question=q, ccontent='否', votes=0) c.save() print("import Choice completed")
def setUp(self): self.questionnaire = Questionnaire.objects.create( name="JRF 2013 Core English", status=Questionnaire.FINALIZED, year=2013) self.section_1 = Section.objects.create( title= "Reported Cases of Selected Vaccine Preventable Diseases (VPDs)", order=1, questionnaire=self.questionnaire, name="Reported Cases") self.section_2 = Section.objects.create( title="Cured Cases of Measles", order=1, questionnaire=self.questionnaire, name="Cured Cases") self.sub_section1 = SubSection.objects.create( title="Reported cases for the year 2013", order=1, section=self.section_1) self.sub_section2 = SubSection.objects.create( title="Reported cases for the year", order=2, section=self.section_1) self.sub_section3 = SubSection.objects.create( title="Reported cures 2014", order=1, section=self.section_2) self.sub_section4 = SubSection.objects.create(title="Reported cures", order=2, section=self.section_2) self.primary_question = Question.objects.create( text='Disease', UID='C00003', answer_type='MultiChoice', is_primary=True) self.option = QuestionOption.objects.create( text="Measles", question=self.primary_question, UID="QO1") self.option2 = QuestionOption.objects.create( text="TB", question=self.primary_question, UID="QO2") self.question1 = Question.objects.create( text='B. Number of cases tested', UID='C00004', answer_type='Number') self.question2 = Question.objects.create( text='C. Number of cases positive', instructions=""" Include only those cases found positive for the infectious agent. """, UID='C00005', answer_type='Number') self.parent10 = QuestionGroup.objects.create( subsection=self.sub_section1, order=1) self.parent12 = QuestionGroup.objects.create( subsection=self.sub_section1, order=2) self.question3 = Question.objects.create( text='B. Number of cases tested', UID=Question.next_uid(), answer_type='Number') self.question4 = Question.objects.create( text='C. Number of cases positive', UID=Question.next_uid(), answer_type='Number') QuestionGroupOrder.objects.create(order=1, question_group=self.parent10, question=self.primary_question) QuestionGroupOrder.objects.create(order=2, question_group=self.parent10, question=self.question1) QuestionGroupOrder.objects.create(order=3, question_group=self.parent10, question=self.question2) QuestionGroupOrder.objects.create(order=4, question_group=self.parent12, question=self.question3) QuestionGroupOrder.objects.create(order=5, question_group=self.parent12, question=self.question4) self.parent10.question.add(self.question3, self.question4, self.question2, self.question1, self.primary_question) self.client = Client() self.user, self.country = self.create_user_with_no_permissions() self.assign('can_view_users', self.user) self.client.login(username=self.user.username, password='******')
def setUp(self): self.questionnaire = Questionnaire.objects.create(name="JRF 2013 Core English", status=Questionnaire.FINALIZED, year=2013) self.section_1 = Section.objects.create(title="Reported Cases of Selected Vaccine Preventable Diseases (VPDs)", order=1, questionnaire=self.questionnaire, name="Reported Cases") self.section_2 = Section.objects.create(title="Cured Cases of Measles", order=1, questionnaire=self.questionnaire, name="Cured Cases") self.sub_section1 = SubSection.objects.create(title="Reported cases for the year 2013", order=1, section=self.section_1) self.sub_section2 = SubSection.objects.create(title="Reported cases for the year", order=2, section=self.section_1) self.sub_section3 = SubSection.objects.create(title="Reported cures 2014", order=1, section=self.section_2) self.sub_section4 = SubSection.objects.create(title="Reported cures", order=2, section=self.section_2) self.primary_question = Question.objects.create(text='Disease', UID='C00003', answer_type='MultiChoice', is_primary=True) self.option = QuestionOption.objects.create(text="Measles", question=self.primary_question, UID="QO1") self.option2 = QuestionOption.objects.create(text="TB", question=self.primary_question, UID="QO2") self.question1 = Question.objects.create(text='B. Number of cases tested', UID='C00004', answer_type='Number') self.question2 = Question.objects.create(text='C. Number of cases positive', instructions=""" Include only those cases found positive for the infectious agent. """, UID='C00005', answer_type='Number') self.parent10 = QuestionGroup.objects.create(subsection=self.sub_section1, order=1) self.parent12 = QuestionGroup.objects.create(subsection=self.sub_section1, order=2) self.question3 = Question.objects.create(text='B. Number of cases tested', UID=Question.next_uid(), answer_type='Number') self.question4 = Question.objects.create(text='C. Number of cases positive', UID=Question.next_uid(), answer_type='Number') QuestionGroupOrder.objects.create(order=1, question_group=self.parent10, question=self.primary_question) QuestionGroupOrder.objects.create(order=2, question_group=self.parent10, question=self.question1) QuestionGroupOrder.objects.create(order=3, question_group=self.parent10, question=self.question2) QuestionGroupOrder.objects.create(order=4, question_group=self.parent12, question=self.question3) QuestionGroupOrder.objects.create(order=5, question_group=self.parent12, question=self.question4) self.parent10.question.add(self.question3, self.question4, self.question2, self.question1, self.primary_question) self.client = Client() self.user, self.country = self.create_user_with_no_permissions() self.assign('can_view_users', self.user) self.client.login(username=self.user.username, password='******')
def __handleQuestion( self, type, row, type_Column, level_number_column, text_question_Column, _questions_rows, _choices_array, qNumber, questionset, log, _checks, _debug, questionnaire, mode=EXACT_MATCH, percentage=0.75, infer_function=None, ): try: slug = None text_en = None if level_number_column.value.startswith("h"): text_en = str(level_number_column.value) + ". " + str(text_question_Column.value) else: level = len(level_number_column.value.split(".")) - 1 text_en = "h%s. %s" % (str(level), str(text_question_Column.value)) dataType_column = None if type == self.CATEGORY: dataType_column = CommentPlaceholder() else: dataType_column = row[3] if row[7].value: slug = row[7].value else: slug = convert_text_to_slug(str(row[1].value)[:50]) slug = self.get_slug(slug, questionnaire) if row[5].value: helpText = row[5].value else: helpText = "" _tooltip = False if row[6].value: if str(row[6].value).lower() == "yes": _tooltip = True # If has dependencies if row[8].value: try: dependencies_list = row[8] list_dep_aux = dependencies_list.value.split("|") question_num_parent = None try: question_num_parent = _questions_rows.get(list_dep_aux[0]).number except AttributeError: """ If this is a merge, the dependant question can already be on the questionset, lets try looking for it """ try: question = Question.objects.get(slug_fk__slug1=list_dep_aux[0], questionset=questionset) _questions_rows[list_dep_aux[0]] = question_num_parent question_num_parent = question.number _choices_array[list_dep_aux[0]] = self.__getChoices(question) except Question.DoesNotExist: raise Exception("The dependant with slug %s does not exist." % (list_dep_aux[0])) index_aux = int(str(list_dep_aux[1])) - 1 choice_parent_list = _choices_array.get(list_dep_aux[0]) choice_parent = choice_parent_list[index_aux] _checks = 'dependent="%s,%s"' % (str(question_num_parent), str(choice_parent)) except: raise try: questionNumber = self.__handleQuestionNumber(level_number_column.value, qNumber, questionset) except: if type == self.QUESTION: log += "\n%s - Error to create question number %s" % (type_Column.row, text_en) elif type == self.CATEGORY: log += "\n%s - Error to create Category number %s" % (type_Column.row, text_en) self.writeLog(log) raise # print slug # Create or load slug slugs = Slugs.objects.filter(slug1=slug, description=text_en) if len(slugs) <= 0: slug_db = Slugs(slug1=slug, description=text_en) slug_db.save() else: slug_db = slugs[0] visible_default = False if row[10].value: if str(row[10].value).lower() == "visible": visible_default = True is_category = None is_stats = None if type == self.QUESTION: is_stats = True is_category = False elif type == self.CATEGORY: is_stats = False is_category = True try: question = Question.objects.get(slug_fk__slug1=slug_db.slug1, questionset=questionset) question.text_en = text_en question.number = str(questionNumber) question.type = dataType_column.value question.help_text = helpText question.stats = is_stats question.category = is_category question.tooltip = _tooltip question.checks = _checks question.visible_default = visible_default except Question.DoesNotExist: question = Question( questionset=questionset, text_en=text_en, number=str(questionNumber), type=dataType_column.value, help_text=helpText, slug=slug, slug_fk=slug_db, stats=is_stats, category=is_category, tooltip=_tooltip, checks=_checks, visible_default=visible_default, disposition=self.__processDisposition(row[11].value.lower()), ) if dataType_column.value in ["open-validated"]: ardict = {} if row[4].value: # some basic types dont need regex known_validations = { "integer": "[+-]?\d+", "decimal": "[+-]?\d*([.]\d*)?", "scientific": "[+-]?\d*([.]\d*)?e[+-]?\d*([.]\d*)?", "range": "[+\-]?\d*([.]\d*);[+\-]?\d*([.]\d*)", "date": "\d{2}/\d{2}/\d{4}", "time": "\d{2}:\d{2}:\d{2}", "datetime": "\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}", "text": ".*", } try: ardict["regex"] = known_validations[row[4].value] ardict["base"] = row[4].value except KeyError: # If this is not known, try to validate it as a regex try: re.compile(row[4].value) ardict["regex"] = row[4].value except re.error: raise Exception("--ERROR: The regex on row %d, column 4 is not valid" % (type_Column.row)) if row[5].value: split = row[5].value.split("|") lensplit = len(split) if lensplit == 1: ardict["unit"] = split[0] question.help_text = "" elif lensplit == 2: ardict["unit"] = split[0] ardict["unit_desc"] = split[1] question.help_text = "" elif lensplit == 3: ardict["unit"] = split[0] ardict["unit_desc"] = split[1] question.help_text = split[2] else: raise Exception( "-- ERROR: Invalid number of segments on help text row %d, column 5. Max syntax is unit|desc|help_text" % (type_Column.row) ) question.metadata = json.dumps(ardict) if not _debug: question.save() if type == self.QUESTION: log += "\n%s - Question created %s " % (type_Column.row, question) elif type == self.CATEGORY: log += "\n%s - Category created %s " % (type_Column.row, question) _questions_rows[slug] = question if type == self.QUESTION: if dataType_column.value in [ "choice", "choice-freeform", "choice-multiple", "choice-multiple-freeform", ]: _choices_array_aux = [] # Parse of values list values_list = row[4] if values_list != None and values_list.value != None: list_aux = values_list.value.split("|") _choices_array[slug] = self.__processChoices( type_Column.row, question, list_aux, log, debug=_debug, mode=mode, match_percentage=percentage, infer_function=infer_function, ) if dataType_column.value in ["choice-yesno", "choice-yesnocomment", "choice-yesnodontknow"]: _choices_array[slug] = ["yes", "no", "dontknow"] except: log += "\n%s - Error to save question %s" % (type_Column.row, text_en) self.writeLog(log) raise