def setup_questions(round_file, q_file=config['QUESTIONS_FILENAME']): app.logger.info("Setup questions from file: {}".format(q_file)) game = Game.query.one() if game.state == GameState.uninitialized: gamefile, final = parse_gamefile(config['BASE_DIR'] + 'data/' + round_file) questions = parse_questions(config['BASE_DIR'] + q_file) # TODO do some validation based on config constants for _col, _cat in enumerate(gamefile, start=1): for _row, _q in enumerate(questions[_cat], start=1): score = _row * config['SCORE_TICK'] question = Question(_q, score, _cat, _row, _col) db.session.add(question) # Add final question if final is not None: final = FinalQuestion(**final) question = Question(final.question, 0, final.category, 0, 0, final=True) db.session.add(question) # Once everything loaded successfully, identify round file and commit game.round_filename = round_file db.session.add(game) db.session.commit() else: raise GameProblem("Trying to setup a game that is already started") return True
def question(): if request.method == 'GET': return render_template('question.html') else: title = request.form.get('title') content = request.form.get('content') question = Question(title=title, content=content) question.author = g.user db.session.add(question) db.session.commit() return redirect(url_for('index'))
def registration_form_submit(event_id): """User builds structure of the registration form""" # Get form variables labels = request.form.getlist('label') print "**************************" print labels selectors = request.form.getlist('selector') print "**************************" print selectors data = request.form.getlist('data') print "**************************" print data # For each label creates a new question for i in range(len(labels)): new_question = Question() new_question.label = labels[i] new_question.selector = selectors[i] new_question.ordinal = i new_question.event_id = event_id field_options = data[i] # Json for the options for the selectors if field_options: new_question.data = json.loads(data[i]) else: new_question.data = None # Adds each question to the database db.session.add(new_question) db.session.commit() flash("Successfully created event", "success") return redirect("/event_profile/%s" % event_id)
def _choose_question() -> (int, str, str): while True: cli_input = input("Choose Euler Project problem by id: ") try: q_id = int(cli_input) q = Question(q_id) if not q.record_exists: q_title, q_text = collector.call_by_id(q_id) q.add_vals(title=q_title, question_text=q_text) return q except IndexError: print(f"No Euler Project problem found with id {cli_input}") except ValueError: print(f"Problem id must be an integer. Cannot cast {cli_input}")
def questions(): if request.method == 'GET': return render_template('questions.html') elif request.method == 'POST': title = request.form.get('title') print(title) content = request.form.get('content') print(content) question = Question(title=title, content=content.encode('utf-8')) user_id = session.get('user_id') user = User.query.filter(User.id == user_id).first() question.author = user db.session.add(question) db.session.commit() return redirect(url_for('index'))
def parse_question_page(self): question = Question() self.find_question_text(question) self.find_question_code(question) self.find_question_answer(question) print(question.text)
def load_questions(): for i, row in enumerate(open("seed_data/u.question.tsv")): row = row.rstrip() question_id, difficulty = row.split("\t") question = Question(question_id=question_id, difficulty=difficulty) db.session.add(question) db.session.commit()
def question(): if request.method == 'GET': return render_template('question.html') else: body = Question(title=request.form.get('title'), content=request.form.get('content'), author_id=session.get('user_id')) db.session.add(body) return redirect(url_for('index'))
def new_question(): form = QuestionForm() if form.validate_on_submit(): title = form.title.data body = form.body.data tags = form.tags.data if tags != "": tags = set(map(lambda x: x.strip(), tags.split(","))) tag_obj = Tag.objects.first() for tag in tags: tag_obj.update(add_to_set__tags=tag) tag_obj.save() else: tags = [] question = Question(username=current_user.username, title=title, body=body, tags=tags) question.save() return redirect(url_for("index")) return render_template("add_question.html", form=form)
def post_question_form(lookup_id, body=None, **__): content = body['content'][0] name = body.get('name') if name: content += "\n\n - " + name[0] question = Question.create(lookup_id, content) return render_template("question_posted.html", lookup_id=lookup_id, question=question)
def parse_question_page(self): question = Question() self.fill_question_text(question) self.fill_question_code(question) self.fill_answer(question) self.choose_answer() self.right_answer(question) self.next_question() p = question return p
def find_best_split(rows): best_gain = 0 best_question = None current_uncertainty = gini(rows) n_features = len(rows[0]) - 1 for col in range(n_features): values = set([row[col] for row in rows]) for val in values: question = Question(col, val) true_rows, false_rows = question.partition(rows) if len(true_rows) == 0 or len(false_rows) == 0: continue gain = info_gain(true_rows, false_rows, current_uncertainty) if gain >= best_gain: best_gain = gain best_question = question return best_gain, best_question
def submit_question_api(user, user_input): """Commits question to the database. Calls make_question function and submits request to MTurk.""" keyword_key = user_input['keyword'] keywords = keyword_dict[keyword_key] description = description_dict[keyword_key] num_ppl_to_ask = 4 time_posted = datetime.datetime.now() title = user_input['title'] question = user_input['question'] price = user_input['price'] price_cents_each = float(int((float(price[1:]) / 4) * 100)) / 100 price_cents_four = int(price_cents_each*100) * 4 balance = user.balance - price_cents_four new_question = QuestionModel( title=title, question=question, description=description, keywords=keywords, price=price, num_ppl_to_ask=num_ppl_to_ask, time_posted=time_posted, user_id=user.user_id ) make_q = makequestion.make_question(title, question, description, keywords, price_cents_each, num_ppl_to_ask) new_question.amzn_hit_id = make_q[0].HITId user.balance = balance db.session.add(new_question) db.session.commit() return new_question
def get_question(api_id): """Returns a question in the selected category.""" cat_questions = questions.get_category_questions(api_id) # gets all questions in that category questions_list = [] for question in cat_questions: x = Question.as_dict(question) questions_list.append(x) # gets a random question ran_num = randint(0, 50) random_question = questions_list[ran_num] return jsonify(random_question)
def load_questions(): """Load questions from questions.csv""" print "Questions table" with open('questions.csv') as questions_file: for row in questions_file.readlines()[1:]: row = row.rstrip() strand_id, strand_name, standard_id, standard_name, question_id, difficulty = row.split(',') question = Question(strand_id=strand_id, strand_name=strand_name, standard_id=standard_id, standard_name=standard_name, question_id=question_id, difficulty=difficulty) db.session.add(question) db.session.commit()
def sub2(subject_id): username = request.get_cookie("username") subject = Subject.get(Subject.id == subject_id) user = User.get(User.id == int(username)) print(user) result = Result.select().where(Result.username == int(username)) if (len(result) != 0) and (result[0].is_taken == True): return redirect("/result") for question in Question.filter(Question.subject_code == subject): res = request.forms.get(f"question-{question.id}") response = Response(qid=question.id, subject_code=subject_id, user=user, response=res) response.save() try: result = Result.get(Result.username == user, Result.subject_code == subject) except: result = Result(username=user, subject_code=subject, is_taken=True) if int(res) == question.right_option: result.marks_obtained += 1 if result.marks_obtained == 20: result.grade = "A" result.state = "Outstanding!" elif result.marks_obtained > 13: result.grade = "B" result.state = "Good!" elif result.marks_obtained > 7: result.grade = "C" result.state = "Average!" else: result.grade = "D" result.state = "Poor!" else: result.marks_obtained += 0 result.save() subject = subject.select()[0] return redirect("/choosesub")
def parse_json(self): try: questions_json = json.loads(self.json_file.read()) # Iterating through an array of JSON objects and filling out Question objects for json_object in questions_json: self.all_questions.append( Question( question=json_object['question'], incorrect=json_object['incorrect'], correct=json_object['correct'], )) except Exception as e: print(e)
def load_questions(): """Load questions from seed data into database""" print "Questions" with open("seed_data/questions.txt") as questions: for q in questions: q = q.rstrip() question_id, question = q.split("|") question = Question(question_id=question_id, question=question) db.session.add(question) db.session.commit()
def load_questions(): """Load questions from questions.txt into database.""" print("Loading questions") # Delete all rows in table, so if we need to run this a second time, # we won't be trying to add duplicate questions Question.query.delete() # Read the file and insert data one by one for row in open("data/questions.txt"): row = row.rstrip() question = Question(question=row) db.session.add(question) db.session.commit()
def create_question(question_title, question_answer, incorrect_1, incorrect_2, incorrect_3, question_difficulty, category_id): """Create and return a new question.""" question = Question(question_title=question_title, question_answer=question_answer, incorrect_1=incorrect_1, incorrect_2=incorrect_2, incorrect_3=incorrect_3, question_difficulty=question_difficulty, category_id=category_id) db.session.add(question) db.session.commit() return question
def create_question(): user_id = request.json['user_id'] content = request.json['content'] user = User.query.filter_by(user_id=user_id).first() if not user: return 'This account have been not registed!' question = Question(content, user_id) try: db.session.add(question) db.session.commit() except: return 'Error! Fail to create question!' return question_schema.jsonify(question)
def questionnaireGET(questionnaire_id): key = ndb.Key(Questionnaire, int(questionnaire_id)) questionnaire = key.get() if questionnaire is None: return fail_response('Questionnaire not found.') sections = QuestionSection.query(QuestionSection.questionnaire_id == questionnaire.key.integer_id()).fetch() questionnaire = entity_to_dict(questionnaire, enum_map={ 'age_range': PatientAgeRange }) sections = map(entity_to_dict, sections) for section in sections: questions = Question.query(Question.section_id == section['id']).fetch() section['questions'] = map( lambda e: entity_to_dict(e, enum_map={ 'question_type': QuestionType }), questions ) questionnaire['sections'] = sections return succesful_response(questionnaire)
def initialize_quiz(chosen_level): """Function to return list of questions of a specific level Args: chosen_level: String containing selected level (easy, intermediate, hard) Returns: list of objects """ # parsing questions from a .json file with open('numerical_reasoning.json') as f_json: question_json = json.load(f_json) # appending questions in a list questions_list = [] for question in question_json[chosen_level]: question_input = Question(id=question['id'], type=question['type'], question=question['question'], answer=question['answer'], explanation=question['explanation']) questions_list.append(question_input) print("Questions have been loaded for {0} level".format(chosen_level)) return questions_list
def main(): # global variables set before parsing questions args = handle_args(sys.argv) # load the question set with open(args['file_name_json'], "r") as f: data = json.load(f) # convert them to question objects questions = [Question(d, shuffle=shuffle_answers) for d in data] # randomize order of questions if shuffle_questions: random.shuffle(questions) # render each question and wait for input from user for i, q in enumerate(questions): clear_screen() ask_question(q, i+1) answer = handle_input(q) if not answer: break q.answered = True if check_correct_answer(q, answer): q.correct = True if show_answer: if q.correct: print(f"{x_indent}Correct") else: print(f"{x_indent}Incorrect: {', '.join(chr(97+a) for a in q.answer)}") try: input(f"{x_indent}Press <enter> to continue...") except KeyboardInterrupt: break output_results(questions)
def registration_form_submit(event_id): labels = request.form.getlist('label') selectors = request.form.getlist('selector') data = request.form.getlist('options') for i in range (len(labels)): new_question = Question() new_question.label=labels[i] new_question.selector=selectors[i] new_question.ordinal = i new_question.event_id = event_id field_options = data[i] if field_options: new_question.data = json.loads(data[i]) else: new_question.data = None db.session.add(new_question) db.session.commit() flash("Successfully created event") return redirect("/event_profile/%s" % event_id)
for row in rows: topic = Topic(did_unit=row['did_unit'], title=row['title']) topic.subject = current_subject session.add(topic) session.commit() print "Importing question in each topic..." # current_topic = select_topic(session, current_subject) # if not current_topic: # sys.exit(1) cur.execute("Select question, qtype, answers, topic_id from questions") rows = cur.fetchall() for row in rows: qa = Question(row['qtype'], row['question']) qa.topic_id = int(row['topic_id']) for answer in row['answers'].split('\n'): if answer: answ = Answer(answer[6:]) answ.question = qa session.add(answ) session.add(qa) session.commit() print "Importing classes..." cur.execute("Select name from classes") rows = cur.fetchall() for row in rows:
def question_by_kind(kind): for q in QUESTIONS: if kind == q.kind: return q return Question('?', '?', '?')
import pprint import xml.dom.minidom from xml.dom.minidom import Node from os.path import normpath, join from turbogears import config from pethelper import model from model import Question static_dir = config.get('static_filter.dir', path="/static") XML_FILENAME = join(normpath(static_dir), "pethelper_questions.xml") doc = xml.dom.minidom.parse(XML_FILENAME) ALL_QUESTIONS = {} for question in doc.getElementsByTagName("q"): q_key = question.getAttribute("q_key") q_value = question.getAttribute("q_value") q = Question() q.q = { q_key : q_value } q.a = [] answers = question.getElementsByTagName("a") for answer in answers: a_key = answer.getAttribute("a_key") a_value = answer.getAttribute("a_value") q.a.append( { a_key : a_value } ) ALL_QUESTIONS[q_key] = q print '999999999999999999:::', len(ALL_QUESTIONS)
def mutate(root, info, oid): return Que.objects(oid=str(oid)).delete()
def resolve_question_analyse_items(self, info): tmp = [] for each in Sur.objects.all(): for item in Que.objects(survey_oid=str(each.oid)): tmp.append(QuestionAnalyseItem(oid=str(item.oid))) return tmp
def mutate(root, info, question_input): tmp = Que() tmp = obj_copy(question_input, tmp) tmp.save() tmp.oid = tmp.auto_id_0 return CreateQuestion(question=tmp)
def tag(tag): questions = Question.objects(tags=tag).order_by("-timestamp") return render_template('tag.html', questions=questions, tag=tag)
def post_question_vote(user=None, body=None): question = Question.vote(question_id=body['question_id'], user_email=user['email'], score=body['vote']) return question
break data = dict() loop = True while loop: data['qtype'] = safe_prompt(session, "Type ('BC', 'SC', 'MC', 'OC'): ") if not data['qtype']: loop = False if safe_prompt(session, "Continue? ") in ("N",'n','No','no') else True continue data['question'] = safe_prompt(session, "Question: ") if not data['question']: loop = False if safe_prompt(session, "Continue? ") in ("N",'n','No','no') else True continue qa = Question(**data) qa.topic = current_topic session.add(qa) session.commit() if data['qtype'] in ('BC','bc','b'): true = Answer('Vero') true.question = qa false = Answer('Falso') false.question = qa session.add(true) session.add(false) else: subloop = True answer_id = 1 while subloop:
def add_question_for_user(self, question): user = self.repo.get_user_for_name(question['user']) new_question = Question(question=question['question'], user=user) self.repo.add_question(new_question)
with self.get_cursor() as cursor: cursor.execute('SELECT userid FROM users') return [row[0] for row in cursor.fetchall()] def get_stats(self, start_date, end_date, user_id): s, e = str(min(start_date, end_date)), str(max(start_date, end_date)) start_date, end_date = s, e rates = self.get_rates(user_id, start_date, end_date) values_by_kind = defaultdict(list) for rate in rates: values_by_kind[rate.kind].append(rate) return values_by_kind QUESTIONS = [ Question("качество еды", "избыточная", "здоровая"), Question("сон", "недостаточный", "нормальный"), Question("употребление алкоголя", "выпил много", "не пил"), Question("физические нагрузки", "сидел весь день", "хорошо потренировался"), ] def question_by_kind(kind): for q in QUESTIONS: if kind == q.kind: return q return Question('?', '?', '?') def test_pls():
def seed_data(): """Seeding questions from Question class into database""" print "Seed Complete." #creating forms safety_plan_form = Form(form_name="Safety Plan") #creating login for a victim and for an advocate login_1 = Login(user_name='advocate_1', password='******', email='*****@*****.**', name='Denise') login_2 = Login(user_name='victim_1', password='******', email='*****@*****.**', name='Lauren') #creating agency type agency_type_1 = Agency_Type(agency_type="Domestic Violence Center") # #creating agency agency_1 = Agency(agency_name="The Haven", agency_address='1412 North Fort Harrison Clearwater Fl', agency_phone=7274424128, agency_type=agency_type_1) #creating shelter s1 = 'Monday, February 01, 2018' shelter_information_1 = Shelter_Information( agency=agency_1, number_beds=42, next_available_date=datetime.strptime(s1, "%A, %B %d, %Y")) #creating advocate advocate_1 = Advocate(login=login_1, shelter_information=shelter_information_1, position_name="Legal Advocate") #creating victim victim_1 = Victim(login=login_2, advocate=advocate_1) # # s2 = 'Monday, January 01, 2018' # safety_plan_filled_form = Filled_Form(form=safety_plan_form, victim=victim_1, # # time_filled=datetime.strptime(s2, "%A, %B %d, %Y")) # ****************************Safety Plan Form********************************** # A "Yes" response to any of Questions #1-3 automatically triggers the protocol referral. question_1 = Question( question_text="""Has he/she ever used a weapon against you/threatened you with a weapon?""", question_number=1, section_number=1, answer_required=True, form=safety_plan_form) question_2 = Question(question_text="""Has he/she threatened to kill you or your children?""", question_number=2, section_number=1, answer_required=True, form=safety_plan_form) question_3 = Question( question_text="""Do you think he/she might try to kill you?""", question_number=3, section_number=1, answer_required=True, form=safety_plan_form) # Negative responses to Questions #1-3, but positive responses to at least four of Questions #4-11, #trigger the protocol referral. question_4 = Question(question_text="""Does he/she have a gun or can he/she get one easily?""", question_number=4, section_number=2, answer_required=True, form=safety_plan_form) question_5 = Question(question_text="Has he/she ever tried to choke you?", question_number=5, section_number=2, answer_required=True, form=safety_plan_form) question_6 = Question(question_text="""Is he/she violently or constantly jealous or does he/she control most of your daily activities?""", question_number=6, section_number=2, answer_required=True, form=safety_plan_form) question_7 = Question(question_text="""Have you left him/her or separated after living together or being married?""", question_number=7, section_number=2, answer_required=True, form=safety_plan_form) question_8 = Question(question_text="Is he/she unemployed?", question_number=8, section_number=2, answer_required=True, form=safety_plan_form) question_9 = Question( question_text="Has he/she ever tried to kill himself/herself?", question_number=9, section_number=2, answer_required=True, form=safety_plan_form) question_10 = Question( question_text="Do you have a child that he/she knows is not his/hers?", question_number=10, section_number=2, answer_required=True, form=safety_plan_form) question_11 = Question(question_text="""Does he/she follow or spy on you or leave threatening message?""", question_number=11, section_number=2, answer_required=True, form=safety_plan_form) question_12 = Question(question_text="""Is there anything else that worries you about your safety? (If 'yes') What worries you?""", question_number=12, section_number=3, answer_required=True, form=safety_plan_form) #creating answers for safety plan filled form # answer_1 = Answer(question=question_1, answer_text=answer_text, # filled_form=safety_plan_filled_form) # answer_2 = Answer(question=question_2, answer_text=answer_text, # filled_form=safety_plan_filled_form) # answer_3 = Answer(question=question_3, answer_text=answer_text, # filled_form=safety_plan_filled_form) # answer_4 = Answer(question=question_4, answer_text=answer_text, # filled_form=safety_plan_filled_form) # answer_5 = Answer(question=question_5, answer_text=answer_text, # filled_form=safety_plan_filled_form) # answer_6 = Answer(question=question_6, answer_text=answer_text, # filled_form=safety_plan_filled_form) # answer_7 = Answer(question=question_7, answer_text=answer_text, # filled_form=safety_plan_filled_form) # answer_8 = Answer(question=question_8, answer_text=answer_text, # filled_form=safety_plan_filled_form) # answer_9 = Answer(question=question_9, answer_text=answer_text, # filled_form=safety_plan_filled_form) # answer_10 = Answer(question=question_10, answer_text=answer_text, # filled_form=safety_plan_filled_form) # answer_11 = Answer(question=question_11, answer_text=answer_text, # filled_form=safety_plan_filled_form) # answer_12 = Answer(question=question_12, answer_text=answer_text, # filled_form=safety_plan_filled_form) db.session.add_all([ safety_plan_form, #Questions to Safety Plan Form question_1, question_2, question_3, question_4, question_5, question_6, question_7, question_8, question_9, question_10, question_11, question_12, #Answers to Safety Plan Form # answer_1, answer_2, answer_3, answer_4, answer_5, # answer_6, answer_7, answer_8, answer_9, answer_10, # answer_11, answer_12, # safety_plan_filled_form, login_1, login_2, agency_type_1, agency_1, shelter_information_1, advocate_1, victim_1 ]) # *******************Victim Compensation Form********************************** victim_comp_form = Form(form_name="Victim Compensation Application") question_1 = Question(question_text="Name: (last, first, middle)", question_number=1, section_number=1, answer_required=True, form=victim_comp_form) question_2 = Question(question_text="Date of Birth: (MM-DD-YYYY)", question_number=2, section_number=1, answer_required=True, form=victim_comp_form) question_3 = Question(question_text="E-mail address", question_number=3, section_number=1, answer_required=True, form=victim_comp_form) question_4 = Question(question_text="Address:", question_number=4, section_number=1, answer_required=True, form=victim_comp_form) question_5 = Question(question_text="City:", question_number=5, section_number=1, answer_required=True, form=victim_comp_form) question_6 = Question(question_text="State:", question_number=6, section_number=1, answer_required=True, form=victim_comp_form) question_7 = Question(question_text="Zipcode:", question_number=7, section_number=1, answer_required=True, form=victim_comp_form) question_8 = Question(question_text="Telephone Number:", question_number=8, section_number=1, answer_required=True, form=victim_comp_form) question_9 = Question(question_text="Occupation: (optional)", question_number=9, section_number=1, answer_required=True, form=victim_comp_form) question_10 = Question(question_text="Race/Ethnicity:", question_number=10, section_number=1, answer_required=True, form=victim_comp_form) question_11 = Question(question_text="Gender:", question_number=11, section_number=1, answer_required=True, form=victim_comp_form) question_12 = Question(question_text="National Origin:", question_number=12, section_number=1, answer_required=True, form=victim_comp_form) question_13 = Question( question_text="Were you disabled before the crime?:", question_number=13, section_number=1, answer_required=True, form=victim_comp_form) question_14 = Question( question_text= "Name of person assisting with application (last, first, middle):", question_number=14, section_number=2, answer_required=True, form=victim_comp_form) question_15 = Question(question_text="Email address:", question_number=15, section_number=2, answer_required=True, form=victim_comp_form) question_16 = Question(question_text="Name of Agency/Organization:", question_number=16, section_number=2, answer_required=True, form=victim_comp_form) question_17 = Question( question_text= "Agency/Organization's Address: (address, city, state, zip code)", question_number=17, section_number=2, answer_required=True, form=victim_comp_form) question_18 = Question(question_text="Telephone Number:", question_number=18, section_number=2, answer_required=True, form=victim_comp_form) question_19 = Question( question_text= "Is Insurance or Medicaid Available to assist with these expenses?:", question_number=19, section_number=3, answer_required=False, form=victim_comp_form) question_20 = Question(question_text="Medicaid Number:", question_number=20, section_number=3, answer_required=False, form=victim_comp_form) question_21 = Question(question_text="Company Name:", question_number=21, section_number=3, answer_required=False, form=victim_comp_form) question_22 = Question(question_text="Policy Number:", question_number=22, section_number=3, answer_required=False, form=victim_comp_form) question_23 = Question(question_text="Telephone Number:", question_number=23, section_number=3, answer_required=False, form=victim_comp_form) question_24 = Question(question_text="Address:", question_number=24, section_number=3, answer_required=False, form=victim_comp_form) question_25 = Question(question_text="City:", question_number=25, section_number=3, answer_required=False, form=victim_comp_form) question_26 = Question(question_text="State:", question_number=26, section_number=3, answer_required=False, form=victim_comp_form) question_27 = Question(question_text="Zipcode:", question_number=27, section_number=3, answer_required=False, form=victim_comp_form) question_28 = Question(question_text="Name of Law Enforcement Agency:", question_number=28, section_number=4, answer_required=True, form=victim_comp_form) question_29 = Question(question_text="Date of Crime:", question_number=29, section_number=4, answer_required=False, form=victim_comp_form) question_30 = Question( question_text="Date Reported To Law Enforcement Agency:", question_number=30, section_number=4, answer_required=False, form=victim_comp_form) question_31 = Question( question_text= "Was the crime reported to law enforcement within 72 hours?", question_number=31, section_number=4, answer_required=False, form=victim_comp_form) question_32 = Question( question_text="""If no, please explain. (If no, failure to provide an acceptable explanation in this section will result in a denial of benefits.""", question_number=32, section_number=4, answer_required=False, form=victim_comp_form) question_33 = Question(question_text="""Is the application and and law enforcement report being submitted within one year from the date of crime?""", question_number=33, section_number=4, answer_required=False, form=victim_comp_form) question_34 = Question(question_text="""If no, please explain. (Please be advised that most benefi ts apply to treatment losses suffered within one year from the date of crime, with some exceptions for minor victims. If no, failure to provide an acceptable explanation in this section will result in a denial of benefits.)?""", question_number=34, section_number=4, answer_required=False, form=victim_comp_form) question_35 = Question(question_text="""Type of crime as specified on the law enforcement report?""", question_number=35, section_number=4, answer_required=True, form=victim_comp_form) question_36 = Question(question_text="""Law Enforcement report number""", question_number=36, section_number=4, answer_required=True, form=victim_comp_form) question_37 = Question(question_text="""Name of Law Enforcement Officer""", question_number=37, section_number=4, answer_required=True, form=victim_comp_form) question_38 = Question(question_text="""Name of offender (if known)""", question_number=38, section_number=4, answer_required=False, form=victim_comp_form) question_39 = Question(question_text="""Name of Assistant State Attorney Handling the case (if applicable)""", question_number=39, section_number=4, answer_required=False, form=victim_comp_form) question_40 = Question(question_text="""State Attorney/Clerk of Court case Number""", question_number=40, section_number=4, answer_required=True, form=victim_comp_form) #Victim Signature question_41 = Question(question_text="""Printed Name""", question_number=41, section_number=5, answer_required=True, form=victim_comp_form) question_42 = Question(question_text="""Signature""", question_number=42, section_number=5, answer_required=True, form=victim_comp_form) question_43 = Question(question_text="""Date""", question_number=43, section_number=5, answer_required=True, form=victim_comp_form) # #TO DO: SEE if can use timestamp in order to see the time the form was sent # #creating filled victim compensation form # s2 = 'Monday, January 01, 2018' # victim_comp_filled_form = Filled_Form(form=victim_comp_form, victim=victim_1, # time_filled=datetime.strptime(s2, "%A, %B %d, %Y")) # #creating answers for safety plan filled form # answer_1 = Answer(question=question_1, answer_text="Answer text 1", # filled_form=victim_comp_filled_form) # answer_2 = Answer(question=question_2, answer_text="Answer text 2", # filled_form=victim_comp_filled_form) # answer_3 = Answer(question=question_3, answer_text="Answer text 3", # filled_form=victim_comp_filled_form) # answer_4 = Answer(question=question_4, answer_text="Answer text 4", # filled_form=victim_comp_filled_form) # answer_5 = Answer(question=question_5, answer_text="Answer text 5", # filled_form=victim_comp_filled_form) # answer_6 = Answer(question=question_6, answer_text="Answer text 6", # filled_form=victim_comp_filled_form) # answer_7 = Answer(question=question_7, answer_text="Answer text 7", # filled_form=victim_comp_filled_form) # answer_8 = Answer(question=question_8, answer_text="Answer text 8", # filled_form=victim_comp_filled_form) # answer_9 = Answer(question=question_9, answer_text="Answer text 9", # filled_form=victim_comp_filled_form) # answer_10 = Answer(question=question_10, answer_text="Answer text 10", # filled_form=victim_comp_filled_form) # answer_11 = Answer(question=question_11, answer_text="Answer text 11", # filled_form=victim_comp_filled_form) # answer_12 = Answer(question=question_12, answer_text="Answer text 12", # filled_form=victim_comp_filled_form) # answer_13 = Answer(question=question_13, answer_text="Answer text 13", # filled_form=victim_comp_filled_form) # answer_14 = Answer(question=question_14, answer_text="Answer text 14", # filled_form=victim_comp_filled_form) # answer_15 = Answer(question=question_15, answer_text="Answer text 15", # filled_form=victim_comp_filled_form) # answer_16 = Answer(question=question_16, answer_text="Answer text 16", # filled_form=victim_comp_filled_form) # answer_17 = Answer(question=question_17, answer_text="Answer text 17", # filled_form=victim_comp_filled_form) # answer_18 = Answer(question=question_18, answer_text="Answer text 18", # filled_form=victim_comp_filled_form) # answer_19 = Answer(question=question_19, answer_text="Answer text 19", # filled_form=victim_comp_filled_form) # answer_20 = Answer(question=question_20, answer_text="Answer text 20", # filled_form=victim_comp_filled_form) # answer_21 = Answer(question=question_21, answer_text="Answer text 21", # filled_form=victim_comp_filled_form) # answer_22 = Answer(question=question_22, answer_text="Answer text 22", # filled_form=victim_comp_filled_form) # answer_23 = Answer(question=question_23, answer_text="Answer text 23", # filled_form=victim_comp_filled_form) # answer_24 = Answer(question=question_24, answer_text="Answer text 24", # filled_form=victim_comp_filled_form) # answer_25 = Answer(question=question_25, answer_text="Answer text 25", # filled_form=victim_comp_filled_form) # answer_26 = Answer(question=question_26, answer_text="Answer text 26", # filled_form=victim_comp_filled_form) # answer_27 = Answer(question=question_27, answer_text="Answer text 27", # filled_form=victim_comp_filled_form) # answer_28 = Answer(question=question_28, answer_text="Answer text 28", # filled_form=victim_comp_filled_form) # answer_29 = Answer(question=question_29, answer_text="Answer text 21", # filled_form=victim_comp_filled_form) # answer_30 = Answer(question=question_30, answer_text="Answer text 21", # filled_form=victim_comp_filled_form) # answer_31 = Answer(question=question_31, answer_text="Answer text 21", # filled_form=victim_comp_filled_form) # answer_32 = Answer(question=question_32, answer_text="Answer text 21", # filled_form=victim_comp_filled_form) # answer_33 = Answer(question=question_33, answer_text="Answer text 21", # filled_form=victim_comp_filled_form) # answer_34 = Answer(question=question_34, answer_text="Answer text 21", # filled_form=victim_comp_filled_form) # answer_35 = Answer(question=question_35, answer_text="Answer text 21", # filled_form=victim_comp_filled_form) # answer_36 = Answer(question=question_36, answer_text="Answer text 21", # filled_form=victim_comp_filled_form) # answer_37 = Answer(question=question_37, answer_text="Answer text 21", # filled_form=victim_comp_filled_form) # answer_38 = Answer(question=question_38, answer_text="Answer text 21", # filled_form=victim_comp_filled_form) # answer_39 = Answer(question=question_39, answer_text="Answer text 21", # filled_form=victim_comp_filled_form) # answer_40 = Answer(question=question_40, answer_text="Answer text 21", # filled_form=victim_comp_filled_form) # answer_41 = Answer(question=question_41, answer_text="Answer text 21", # filled_form=victim_comp_filled_form) # answer_42 = Answer(question=question_42, answer_text="Answer text 21", # filled_form=victim_comp_filled_form) # #adding to objects to session db.session.add_all([ #Questions to Victim Compensation Form question_1, question_2, question_3, question_4, question_5, question_6, question_7, question_8, question_9, question_10, question_11, question_12, question_13, question_14, question_15, question_16, question_17, question_18, question_19, question_20, question_21, question_22, question_23, question_24, question_25, question_26, question_27, question_28, question_29, question_30, question_31, question_32, question_33, question_34, question_35, question_36, question_37, question_38, question_39, question_40, question_41, question_42, question_43, #Answers to Victim Compensation Form # answer_1, answer_2, answer_3, answer_4, answer_5, # answer_6, answer_7, answer_8, answer_9, answer_10, # answer_11, answer_12, answer_13, answer_14, answer_15, answer_16, answer_17, # answer_18, answer_19, answer_20, answer_21, answer_22, # answer_23, answer_24, answer_25, answer_26, answer_27, answer_28, answer_29, # answer_30, answer_31, answer_32, answer_33, answer_34, # answer_35, answer_36, answer_37, answer_38, answer_39, answer_40, answer_41, # answer_6, answer_7, answer_8, answer_9, answer_10, # answer_42, victim_comp_form #, victim_comp_filled_form ]) #commiting objects db.session.commit()
def new(): # Extract data from response data = request.data.decode("utf-8") print("----") print(data) data = loads(data) # Authenticate if "user_id" not in login_session or login_session["user_id"] is not data[ "user_id"]: # print(type(login_session["user_id"])) # print(type(data["user_id"])) # print(type(login_session)) # print(login_session.keys()) return "Forbidden", 403 # Extract quiz from data quiz = data["quiz"] questions = data["questions"] ########################### # Data must be cleaned # Validate data ## Check questions length 3 or more if len(questions) < 3: return "Bad Request", 400 ## Check there is a valid title if not isinstance(quiz["title"], str) or len(quiz["title"]) == 0: print("1") return "Bad Request", 400 ## Check there is a valid description if not isinstance(quiz["description"], str) or len( quiz["description"]) == 0: print("2") return "Bad Request", 400 ## Check there is a number for timer if not isinstance(quiz["timer"], int) or quiz["timer"] < 0 or quiz["timer"] > 30: print("3") return "Bad Request", 400 ## For each question for question in questions: ### Check valid question if not isinstance(question["question"], str) or len( question["question"]) == 0: print("4") return "Bad Request", 400 ### Check codes are valid format if len(question["codes"]) > 3: print("5") return "Bad Request", 400 # Need to confirm these valid_codes = ["html", "css", "javascript", "python"] for code in question["codes"]: if not code["language"] in valid_codes: print("6") return "Bad Request", 400 if not isinstance(code["contents"], str) or len( code["contents"]) == 0: print("7") return "Bad Request", 400 ### Check valid answer if not isinstance(question["answer"], str) or len( question["answer"]) == 0: print("8") return "Bad Request", 400 ### Check there is between 1 and 5 duds if len(question["duds"]) < 1 or len(question["duds"]) > 5: print("9") return "Bad Request", 400 ### Check that the duds are all valid strings for dud in question["duds"]: if not isinstance(dud, str) or len(dud) == 0: print("10") return "Bad Request", 400 ### Check that there is a valid explanation if not isinstance(question["explanation"], str) or len( question["explanation"]) == 0: print("11") return "Bad Request", 400 # Add quiz to database print('Validated') new_quiz = Quiz(name=bleach.clean(quiz["title"]), description=bleach.clean(quiz["description"]), time_limit=quiz["timer"], visible=True, creator=data["user_id"]) db_session.add(new_quiz) db_session.flush() print("Added quiz") for question in questions: new_question = Question(text=bleach.clean(question["question"]), answer=bleach.clean(question["answer"]), explanation=bleach.clean( question["explanation"]), correct_replies=0, incorrect_replies=0) db_session.add(new_question) db_session.flush() print("Added question") new_quiz_join = QuizJoin(question_id=new_question.id, quiz_id=new_quiz.id) db_session.add(new_quiz_join) print("Added quizjoin") for dud in question["duds"]: new_dud = Dud(question_id=new_question.id, text=bleach.clean(dud)) db_session.add(new_dud) print("Added dud", dud) for code in question["codes"]: new_code = Code(question_id=new_question.id, type=bleach.clean(code["language"]), sample=bleach.clean(code["contents"])) db_session.add(new_code) print("Added code", code) db_session.commit() print("Added to database") return "OK", 200
except lite.Error, e: print "Error %s" % e.args[0] except Exception, e: print "Error %s" % e subject = select_subject(session) selected_topic = select_topic(session, subject) print "Importing question in to this topic...", selected_topic con.row_factory = lite.Row cur = con.cursor() cur.execute("Select id, question, qtype from questions") rows = cur.fetchall() for row in rows: qa = Question(row['qtype'], row['question']) qa.topic = selected_topic session.add(qa) session.commit() con.row_factory = lite.Row cur2 = con.cursor() cur2.execute("Select answer_text, correct from answers where question_id=%d" % row['id']) for answer in cur2.fetchall(): answ = Answer(answer['answer_text'], answer['correct']) answ.question = qa session.add(answ) session.add(qa) session.commit()