Skip to content
Snippets Groups Projects
Commit 5bc65185 authored by Ossi Laine's avatar Ossi Laine
Browse files

Cleaning codebase, removed unnecessary migrations folder

parent ef9a7efa
No related branches found
No related tags found
No related merge requests found
...@@ -32,6 +32,7 @@ create_blueprint = Blueprint("create", __name__, ...@@ -32,6 +32,7 @@ create_blueprint = Blueprint("create", __name__,
# static_folder='static', # static_folder='static',
url_prefix='/create') url_prefix='/create')
@create_blueprint.route('/experiment', methods=['GET', 'POST']) @create_blueprint.route('/experiment', methods=['GET', 'POST'])
@login_required @login_required
def create_experiment(): def create_experiment():
...@@ -43,24 +44,12 @@ def create_experiment(): ...@@ -43,24 +44,12 @@ def create_experiment():
the_time = datetime.now() the_time = datetime.now()
the_time = the_time.replace(microsecond=0) the_time = the_time.replace(microsecond=0)
new_exp = experiment(name=request.form['name'], instruction=request.form['instruction'], language=request.form['language'], status='Hidden', randomization='Off', single_sentence_instruction=request.form['single_sentence_instruction'], short_instruction=request.form['short_instruction'], creator_name=request.form['creator_name'], is_archived='False', creation_time=the_time, stimulus_size='7', consent_text=request.form['consent_text'], use_forced_id='Off') new_exp = experiment(name=request.form['name'], instruction=request.form['instruction'], language=request.form['language'], status='Hidden', randomization='Off', single_sentence_instruction=request.form['single_sentence_instruction'],
short_instruction=request.form['short_instruction'], creator_name=request.form['creator_name'], is_archived='False', creation_time=the_time, stimulus_size='7', consent_text=request.form['consent_text'], use_forced_id='Off')
db.session.add(new_exp) db.session.add(new_exp)
db.session.commit() db.session.commit()
exp_id = new_exp.idexperiment exp_id = new_exp.idexperiment
#data = request.form.to_dict()
#for key, value in data.items():
#tähän db insertit
#flash(key)
#flash(value)
#flash('{}'.format(form.name.data))
#Input registration page answers to database
# participant_background_question_answers = background_question_answer(answer_set_idanswer_set=session['answer_set'], answer=value, background_question_idbackground_question=key)
# db.session.add(participant_background_question_answers)
# db.session.commit()
return redirect(url_for('create.experiment_bgquestions', exp_id=exp_id)) return redirect(url_for('create.experiment_bgquestions', exp_id=exp_id))
return render_template('create_experiment.html', form=form) return render_template('create_experiment.html', form=form)
...@@ -89,12 +78,14 @@ def experiment_bgquestions(): ...@@ -89,12 +78,14 @@ def experiment_bgquestions():
for x in range(len(list)): for x in range(len(list)):
if x == 0: if x == 0:
add_bgquestion = background_question(background_question=list[x], experiment_idexperiment=exp_id) add_bgquestion = background_question(
background_question=list[x], experiment_idexperiment=exp_id)
db.session.add(add_bgquestion) db.session.add(add_bgquestion)
db.session.commit() db.session.commit()
else: else:
add_bgq_option = background_question_option(background_question_idbackground_question=add_bgquestion.idbackground_question, option=list[x]) add_bgq_option = background_question_option(
background_question_idbackground_question=add_bgquestion.idbackground_question, option=list[x])
db.session.add(add_bgq_option) db.session.add(add_bgq_option)
db.session.commit() db.session.commit()
...@@ -124,7 +115,8 @@ def experiment_questions(): ...@@ -124,7 +115,8 @@ def experiment_questions():
# redirect back to the form # redirect back to the form
if len(list) != 3: if len(list) != 3:
flash("Error Each slider must have 3 parameters separated by ; Some slider has:") flash(
"Error Each slider must have 3 parameters separated by ; Some slider has:")
flash(len(list)) flash(len(list))
return redirect(url_for('create.experiment_questions', exp_id=exp_id)) return redirect(url_for('create.experiment_questions', exp_id=exp_id))
...@@ -135,7 +127,8 @@ def experiment_questions(): ...@@ -135,7 +127,8 @@ def experiment_questions():
list = str_list[a].split(';') list = str_list[a].split(';')
add_question = question(experiment_idexperiment=exp_id, question=list[0], left=list[1], right=list[2]) add_question = question(
experiment_idexperiment=exp_id, question=list[0], left=list[1], right=list[2])
db.session.add(add_question) db.session.add(add_question)
db.session.commit() db.session.commit()
...@@ -158,7 +151,8 @@ def experiment_upload_stimuli(): ...@@ -158,7 +151,8 @@ def experiment_upload_stimuli():
str_list = string.split('/n') str_list = string.split('/n')
for a in range(len(str_list)): for a in range(len(str_list)):
add_text_stimulus = page(experiment_idexperiment=exp_id, type='text', text=str_list[a], media='none') add_text_stimulus = page(
experiment_idexperiment=exp_id, type='text', text=str_list[a], media='none')
db.session.add(add_text_stimulus) db.session.add(add_text_stimulus)
db.session.commit() db.session.commit()
...@@ -184,7 +178,8 @@ def experiment_upload_stimuli(): ...@@ -184,7 +178,8 @@ def experiment_upload_stimuli():
# add pages to the db # add pages to the db
db_path = path + str('/') + str(filename) db_path = path + str('/') + str(filename)
new_page = page(experiment_idexperiment=exp_id, type=form.type.data, media=db_path) new_page = page(experiment_idexperiment=exp_id,
type=form.type.data, media=db_path)
db.session.add(new_page) db.session.add(new_page)
db.session.commit() db.session.commit()
...@@ -196,6 +191,3 @@ def experiment_upload_stimuli(): ...@@ -196,6 +191,3 @@ def experiment_upload_stimuli():
return redirect(url_for('create.experiment_upload_stimuli', exp_id=exp_id)) return redirect(url_for('create.experiment_upload_stimuli', exp_id=exp_id))
return render_template('create_experiment_upload_stimuli.html', form=form) return render_template('create_experiment_upload_stimuli.html', form=form)
# EOF
\ No newline at end of file
...@@ -731,7 +731,6 @@ def remove_embody(): ...@@ -731,7 +731,6 @@ def remove_embody():
# Stimuli: # Stimuli:
@experiment_blueprint.route('/add_stimuli', methods=['GET', 'POST']) @experiment_blueprint.route('/add_stimuli', methods=['GET', 'POST'])
@login_required @login_required
def add_stimuli(): def add_stimuli():
...@@ -1045,13 +1044,11 @@ def remove_rows(rows): ...@@ -1045,13 +1044,11 @@ def remove_rows(rows):
@socketio.on('connect', namespace="/create_embody") @socketio.on('connect', namespace="/create_embody")
def start_create_embody(): def start_create_embody():
print('io connected')
emit('success', {'connection': 'on'}) emit('success', {'connection': 'on'})
@socketio.on('draw', namespace="/create_embody") @socketio.on('draw', namespace="/create_embody")
def create_embody(meta): def create_embody(meta):
print("draw initialized")
page = meta["page"] page = meta["page"]
embody = meta["embody"] embody = meta["embody"]
img_path = embody_plot.get_coordinates(page, embody) img_path = embody_plot.get_coordinates(page, embody)
...@@ -1061,7 +1058,6 @@ def create_embody(meta): ...@@ -1061,7 +1058,6 @@ def create_embody(meta):
@socketio.on('connect', namespace="/download_csv") @socketio.on('connect', namespace="/download_csv")
def start_download_csv(): def start_download_csv():
print('io connected')
emit('success', {'connection': 'Start generating CSV file'}) emit('success', {'connection': 'Start generating CSV file'})
......
...@@ -19,7 +19,6 @@ class LoginForm(FlaskForm): ...@@ -19,7 +19,6 @@ class LoginForm(FlaskForm):
class RegisterForm(Form): class RegisterForm(Form):
questions1 = FieldList(SelectField([validators.InputRequired()])) questions1 = FieldList(SelectField([validators.InputRequired()]))
submit = SubmitField("Send") submit = SubmitField("Send")
...@@ -41,6 +40,7 @@ class ContinueTaskForm(FlaskForm): ...@@ -41,6 +40,7 @@ class ContinueTaskForm(FlaskForm):
participant_id = StringField('participant_id', validators=[DataRequired()]) participant_id = StringField('participant_id', validators=[DataRequired()])
submit = SubmitField(_l('Continue rating')) submit = SubmitField(_l('Continue rating'))
class StartWithIdForm(FlaskForm): class StartWithIdForm(FlaskForm):
participant_id = StringField('participant_id', validators=[DataRequired()]) participant_id = StringField('participant_id', validators=[DataRequired()])
...@@ -54,7 +54,8 @@ class Questions(FlaskForm): ...@@ -54,7 +54,8 @@ class Questions(FlaskForm):
class Answers(FlaskForm): class Answers(FlaskForm):
background_question_idbackground_question = SelectField(coerce=int, validators=[InputRequired]) background_question_idbackground_question = SelectField(
coerce=int, validators=[InputRequired])
class BackgroundQuestionForm(Form): class BackgroundQuestionForm(Form):
...@@ -88,8 +89,10 @@ class CreateExperimentForm(Form): ...@@ -88,8 +89,10 @@ class CreateExperimentForm(Form):
name = StringField('Name', [validators.DataRequired()]) name = StringField('Name', [validators.DataRequired()])
creator_name = StringField('Creator_name', [validators.DataRequired()]) creator_name = StringField('Creator_name', [validators.DataRequired()])
single_sentence_instruction = StringField('Single_sentence_instruction', [validators.DataRequired()]) single_sentence_instruction = StringField(
short_instruction = TextAreaField('Short_instruction', [validators.DataRequired()]) 'Single_sentence_instruction', [validators.DataRequired()])
short_instruction = TextAreaField(
'Short_instruction', [validators.DataRequired()])
instruction = TextAreaField('Instruction', [validators.DataRequired()]) instruction = TextAreaField('Instruction', [validators.DataRequired()])
consent_text = TextAreaField('Instruction', [validators.DataRequired()]) consent_text = TextAreaField('Instruction', [validators.DataRequired()])
language = StringField('Language', [validators.DataRequired()]) language = StringField('Language', [validators.DataRequired()])
...@@ -102,19 +105,31 @@ class EditExperimentForm(Form): ...@@ -102,19 +105,31 @@ class EditExperimentForm(Form):
creator_name = StringField('Creator_name', [validators.DataRequired()]) creator_name = StringField('Creator_name', [validators.DataRequired()])
instruction = TextAreaField('Instruction', [validators.DataRequired()]) instruction = TextAreaField('Instruction', [validators.DataRequired()])
consent_text = TextAreaField('Instruction', [validators.DataRequired()]) consent_text = TextAreaField('Instruction', [validators.DataRequired()])
short_instruction = TextAreaField('Short_instruction', [validators.DataRequired()]) short_instruction = TextAreaField(
single_sentence_instruction = StringField('Single_sentece_instruction', [validators.DataRequired()]) 'Short_instruction', [validators.DataRequired()])
single_sentence_instruction = StringField(
'Single_sentece_instruction', [validators.DataRequired()])
language = SelectField('Language', choices=[ language = SelectField('Language', choices=[
('Afrikanns', 'Afrikanns'), ('Albanian', 'Albanian'), ('Arabic', 'Arabic'), ('Armenian', 'Armenian'), ('Basque', 'Basque'), ('Bengali', 'Bengali'), ('Bulgarian', 'Bulgarian'), ('Afrikanns', 'Afrikanns'), ('Albanian', 'Albanian'), ('Arabic', 'Arabic'), ('Armenian',
('Catalan', 'Catalan'), ('Cambodian', 'Cambodian'), ('Chinese', 'Chinese'), ('Croation', 'Croation'), ('Czech', 'Czech'), ('Danish', 'Danish'), 'Armenian'), ('Basque', 'Basque'), ('Bengali', 'Bengali'), ('Bulgarian', 'Bulgarian'),
('Dutch', 'Dutch'), ('English', 'English'), ('Estonian', 'Estonian'), ('Fiji', 'Fiji'), ('Finnish', 'Finnish'), ('French', 'French'), ('Georgian', 'Georgian'), ('Catalan', 'Catalan'), ('Cambodian', 'Cambodian'), ('Chinese',
('German', 'German'), ('Greek', 'Greek'), ('Gujarati', 'Gujarati'), ('Hebrew', 'Hebrew'), ('Hindi', 'Hindi'), ('Hungarian', 'Hungarian'), ('Icelandic', 'Icelandic'), 'Chinese'), ('Croation', 'Croation'), ('Czech', 'Czech'), ('Danish', 'Danish'),
('Indonesian', 'Indonesian'), ('Irish', 'Irish'), ('Italian', 'Italian'), ('Japanese', 'Japanese'), ('Javanese', 'Javanese'), ('Korean', 'Korean'), ('Latin', 'Latin'), ('Dutch', 'Dutch'), ('English', 'English'), ('Estonian', 'Estonian'), ('Fiji',
('Latvian', 'Latvian'), ('Lithuanian', 'Lithuanian'), ('Macedonian', 'Macedonian'), ('Malay', 'Malay'), ('Malayalam', 'Malayalam'), ('Maltese', 'Maltese'), ('Maori', 'Maori'), 'Fiji'), ('Finnish', 'Finnish'), ('French', 'French'), ('Georgian', 'Georgian'),
('Marathi', 'Marathi'), ('Mongolian', 'Mongolian'), ('Nepali', 'Nepali'), ('Norwegian', 'Norwegian'), ('Persian', 'Persian'), ('Polish', 'Polish'), ('Portuguese', 'Portuguese'), ('German', 'German'), ('Greek', 'Greek'), ('Gujarati', 'Gujarati'), ('Hebrew',
('Punjabi', 'Punjabi'), ('Quechua', 'Quechua'), ('Romanian', 'Romanian'), ('Russian', 'Russian'), ('Samoan', 'Samoan'), ('Serbian', 'Serbian'), ('Slovak', 'Slovak'), 'Hebrew'), ('Hindi', 'Hindi'), ('Hungarian', 'Hungarian'), ('Icelandic', 'Icelandic'),
('Slovenian', 'Slovenian'), ('Spanish', 'Spanish'), ('Swahili', 'Swahili'), ('Swedish ', 'Swedish '), ('Tamil', 'Tamil'), ('Tatar', 'Tatar'), ('Telugu', 'Telugu'), ('Indonesian', 'Indonesian'), ('Irish', 'Irish'), ('Italian', 'Italian'), ('Japanese',
('Thai', 'Thai'), ('Tibetan', 'Tibetan'), ('Tonga', 'Tonga'), ('Turkish', 'Turkish'), ('Ukranian', 'Ukranian'), ('Urdu', 'Urdu'), ('Uzbek', 'Uzbek'), ('Vietnamese', 'Vietnamese'), 'Japanese'), ('Javanese', 'Javanese'), ('Korean', 'Korean'), ('Latin', 'Latin'),
('Latvian', 'Latvian'), ('Lithuanian', 'Lithuanian'), ('Macedonian', 'Macedonian'), ('Malay',
'Malay'), ('Malayalam', 'Malayalam'), ('Maltese', 'Maltese'), ('Maori', 'Maori'),
('Marathi', 'Marathi'), ('Mongolian', 'Mongolian'), ('Nepali', 'Nepali'), ('Norwegian',
'Norwegian'), ('Persian', 'Persian'), ('Polish', 'Polish'), ('Portuguese', 'Portuguese'),
('Punjabi', 'Punjabi'), ('Quechua', 'Quechua'), ('Romanian', 'Romanian'), ('Russian',
'Russian'), ('Samoan', 'Samoan'), ('Serbian', 'Serbian'), ('Slovak', 'Slovak'),
('Slovenian', 'Slovenian'), ('Spanish', 'Spanish'), ('Swahili', 'Swahili'), ('Swedish ',
'Swedish '), ('Tamil', 'Tamil'), ('Tatar', 'Tatar'), ('Telugu', 'Telugu'),
('Thai', 'Thai'), ('Tibetan', 'Tibetan'), ('Tonga', 'Tonga'), ('Turkish', 'Turkish'), ('Ukranian',
'Ukranian'), ('Urdu', 'Urdu'), ('Uzbek', 'Uzbek'), ('Vietnamese', 'Vietnamese'),
('Welsh', 'Welsh'), ('Xhosa', 'Xhosa')]) ('Welsh', 'Welsh'), ('Xhosa', 'Xhosa')])
stimulus_size = SelectField('Stimulus_size', choices=[ stimulus_size = SelectField('Stimulus_size', choices=[
('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10'), ('11', '11'), ('12', '12')]) ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10'), ('11', '11'), ('12', '12')])
...@@ -124,20 +139,23 @@ class EditExperimentForm(Form): ...@@ -124,20 +139,23 @@ class EditExperimentForm(Form):
class CreateBackgroundQuestionForm(Form): class CreateBackgroundQuestionForm(Form):
bg_questions_and_options = TextAreaField('Background questions and options', [validators.DataRequired()]) bg_questions_and_options = TextAreaField(
'Background questions and options', [validators.DataRequired()])
submit = SubmitField('Send') submit = SubmitField('Send')
class EditBackgroundQuestionForm(Form): class EditBackgroundQuestionForm(Form):
bg_questions_and_options = TextAreaField('Background questions and options') bg_questions_and_options = TextAreaField(
'Background questions and options')
new_values = TextAreaField('New values', [validators.DataRequired()]) new_values = TextAreaField('New values', [validators.DataRequired()])
submit = SubmitField('Send') submit = SubmitField('Send')
class CreateQuestionForm(Form): class CreateQuestionForm(Form):
questions_and_options = TextAreaField('Questions and options', [validators.DataRequired()]) questions_and_options = TextAreaField(
'Questions and options', [validators.DataRequired()])
submit = SubmitField('Send') submit = SubmitField('Send')
...@@ -157,7 +175,8 @@ class EditQuestionForm(Form): ...@@ -157,7 +175,8 @@ class EditQuestionForm(Form):
class UploadStimuliForm(Form): class UploadStimuliForm(Form):
type = RadioField('type', choices=[('text', 'text'), ('picture', 'picture'), ('video', 'video'), ('audio', 'audio')]) type = RadioField('type', choices=[
('text', 'text'), ('picture', 'picture'), ('video', 'video'), ('audio', 'audio')])
text = TextAreaField('Text stimulus') text = TextAreaField('Text stimulus')
media = TextAreaField('Media filename') media = TextAreaField('Media filename')
file = FileField('Upload file') file = FileField('Upload file')
...@@ -172,7 +191,8 @@ class UploadResearchBulletinForm(Form): ...@@ -172,7 +191,8 @@ class UploadResearchBulletinForm(Form):
class EditPageForm(Form): class EditPageForm(Form):
type = RadioField('type', choices=[('text', 'text'), ('picture', 'picture'), ('video', 'video'), ('audio', 'audio')]) type = RadioField('type', choices=[
('text', 'text'), ('picture', 'picture'), ('video', 'video'), ('audio', 'audio')])
text = TextAreaField('Text stimulus') text = TextAreaField('Text stimulus')
media = TextAreaField('Media filename') media = TextAreaField('Media filename')
file = FileField('Upload file') file = FileField('Upload file')
...@@ -189,4 +209,3 @@ class GenerateIdForm(Form): ...@@ -189,4 +209,3 @@ class GenerateIdForm(Form):
number = IntegerField('number', [validators.DataRequired()]) number = IntegerField('number', [validators.DataRequired()])
string = StringField('string', [validators.DataRequired()]) string = StringField('string', [validators.DataRequired()])
submit = SubmitField('Submit') submit = SubmitField('Submit')
...@@ -3,16 +3,13 @@ from flask import session ...@@ -3,16 +3,13 @@ from flask import session
from app import db from app import db
from sqlalchemy import Column, Integer, String, Text, Boolean from sqlalchemy import Column, Integer, String, Text, Boolean
from flask_wtf import FlaskForm from flask_wtf import FlaskForm
from wtforms_sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField from wtforms_sqlalchemy.fields import QuerySelectField
from werkzeug.security import generate_password_hash, check_password_hash from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin from flask_login import UserMixin
from app import login from app import login
from datetime import datetime from datetime import datetime
"""DATABASE CLASSES"""
class background_question(db.Model): class background_question(db.Model):
__tablename__ = "background_question" __tablename__ = "background_question"
idbackground_question = db.Column(db.Integer, primary_key=True) idbackground_question = db.Column(db.Integer, primary_key=True)
......
...@@ -198,14 +198,10 @@ def register(): ...@@ -198,14 +198,10 @@ def register():
data = request.form.to_dict() data = request.form.to_dict()
for key, value in data.items(): for key, value in data.items():
# tähän db insertit
# flash(key)
# flash(value)
# Input registration page answers to database # Input registration page answers to database
participant_background_question_answers = background_question_answer( participant_background_question_answers = background_question_answer(
answer_set_idanswer_set=session['answer_set'], answer=value, background_question_idbackground_question=key) answer_set_idanswer_set=session['answer_set'],
answer=value, background_question_idbackground_question=key)
db.session.add(participant_background_question_answers) db.session.add(participant_background_question_answers)
db.session.commit() db.session.commit()
...@@ -253,7 +249,8 @@ def begin_with_id(): ...@@ -253,7 +249,8 @@ def begin_with_id():
else: else:
# save the participant ID in session list for now, this is deleted after the session has been started in participant_session-view # save the participant ID in session list for now, this is deleted after the session has been started in participant_session-view
session['begin_with_id'] = form.participant_id.data session['begin_with_id'] = form.participant_id.data
return render_template('consent.html', exp_id=exp_id, experiment_info=experiment_info, instruction_paragraphs=instruction_paragraphs, consent_paragraphs=consent_paragraphs) return render_template('consent.html', exp_id=exp_id, experiment_info=experiment_info,
instruction_paragraphs=instruction_paragraphs, consent_paragraphs=consent_paragraphs)
return render_template('begin_with_id.html', exp_id=exp_id, form=form) return render_template('begin_with_id.html', exp_id=exp_id, form=form)
...@@ -294,7 +291,9 @@ def instructions(): ...@@ -294,7 +291,9 @@ def instructions():
instruction_paragraphs = str(instructions.instruction) instruction_paragraphs = str(instructions.instruction)
instruction_paragraphs = instruction_paragraphs.split('<br>') instruction_paragraphs = instruction_paragraphs.split('<br>')
return render_template('instructions.html', instruction_paragraphs=instruction_paragraphs, participant_id=participant_id) return render_template('instructions.html',
instruction_paragraphs=instruction_paragraphs,
participant_id=participant_id)
@app.route('/researcher_login', methods=['GET', 'POST']) @app.route('/researcher_login', methods=['GET', 'POST'])
...@@ -312,9 +311,6 @@ def login(): ...@@ -312,9 +311,6 @@ def login():
login_user(user_details, remember=form.remember_me.data) login_user(user_details, remember=form.remember_me.data)
return redirect(url_for('index')) return redirect(url_for('index'))
# flash('Login requested for user {}, remember_me={}'.format(
# form.username.data, form.remember_me.data))
# return redirect('/index')
return render_template('researcher_login.html', title='Sign In', form=form) return render_template('researcher_login.html', title='Sign In', form=form)
...@@ -326,12 +322,12 @@ def logout(): ...@@ -326,12 +322,12 @@ def logout():
@app.route('/view_research_notification') @app.route('/view_research_notification')
def view_research_notification(): def view_research_notification():
exp_id = request.args.get('exp_id', None) exp_id = request.args.get('exp_id', None)
image = experiment.query.filter_by(idexperiment=exp_id).first() image = experiment.query.filter_by(idexperiment=exp_id).first()
research_notification_filename = image.research_notification_filename research_notification_filename = image.research_notification_filename
return render_template('view_research_notification.html', research_notification_filename=research_notification_filename) return render_template('view_research_notification.html',
research_notification_filename=research_notification_filename)
@app.route('/researcher_info') @app.route('/researcher_info')
......
...@@ -36,8 +36,6 @@ $(document).ready(function () { ...@@ -36,8 +36,6 @@ $(document).ready(function () {
drawButtons.click(function (event) { drawButtons.click(function (event) {
event.preventDefault(); event.preventDefault();
console.log("SADATDS");
// Init socket // Init socket
var socket = io.connect(getDrawingURI); var socket = io.connect(getDrawingURI);
initConnection(socket); initConnection(socket);
......
import math import math
import json import json
from datetime import datetime from datetime import datetime
...@@ -45,7 +42,8 @@ def add_slider_answer(key, value, page_id=None): ...@@ -45,7 +42,8 @@ def add_slider_answer(key, value, page_id=None):
the values are inputted for session['current_idpage']. Otherwise the values the values are inputted for session['current_idpage']. Otherwise the values
are set for the corresponding id found in the trial randomization table""" are set for the corresponding id found in the trial randomization table"""
participant_answer = answer(question_idquestion=key, answer_set_idanswer_set=session['answer_set'], answer=value, page_idpage=page_id) participant_answer = answer(
question_idquestion=key, answer_set_idanswer_set=session['answer_set'], answer=value, page_idpage=page_id)
db.session.add(participant_answer) db.session.add(participant_answer)
db.session.commit() db.session.commit()
...@@ -55,8 +53,10 @@ def update_answer_set_page(): ...@@ -55,8 +53,10 @@ def update_answer_set_page():
the_time = datetime.now() the_time = datetime.now()
the_time = the_time.replace(microsecond=0) the_time = the_time.replace(microsecond=0)
update_answer_counter = answer_set.query.filter_by(idanswer_set=session['answer_set']).first() update_answer_counter = answer_set.query.filter_by(
update_answer_counter.answer_counter = int(update_answer_counter.answer_counter) + 1 idanswer_set=session['answer_set']).first()
update_answer_counter.answer_counter = int(
update_answer_counter.answer_counter) + 1
update_answer_counter.last_answer_time = the_time update_answer_counter.last_answer_time = the_time
db.session.commit() db.session.commit()
...@@ -67,7 +67,8 @@ def update_answer_set_type(answer_type): ...@@ -67,7 +67,8 @@ def update_answer_set_type(answer_type):
the_time = datetime.now() the_time = datetime.now()
the_time = the_time.replace(microsecond=0) the_time = the_time.replace(microsecond=0)
updated_answer_set = answer_set.query.filter_by(idanswer_set=session['answer_set']).first() updated_answer_set = answer_set.query.filter_by(
idanswer_set=session['answer_set']).first()
updated_answer_set.answer_type = answer_type updated_answer_set.answer_type = answer_type
updated_answer_set.last_answer_time = the_time updated_answer_set.last_answer_time = the_time
db.session.commit() db.session.commit()
...@@ -77,13 +78,15 @@ def select_form_type(): ...@@ -77,13 +78,15 @@ def select_form_type():
"""Select form type based on the value in answer_set->answer_type""" """Select form type based on the value in answer_set->answer_type"""
form = None form = None
answer_set_type = answer_set.query.filter_by(idanswer_set=session['answer_set']).first().answer_type answer_set_type = answer_set.query.filter_by(
idanswer_set=session['answer_set']).first().answer_type
if answer_set_type == 'slider': if answer_set_type == 'slider':
form = TaskForm() form = TaskForm()
# Get sliders from this experiment # Get sliders from this experiment
categories = question.query.filter_by(experiment_idexperiment=session['exp_id']).all() categories = question.query.filter_by(
experiment_idexperiment=session['exp_id']).all()
categories_and_scales = {} categories_and_scales = {}
for cat in categories: for cat in categories:
scale_list = [(cat.left, cat.right)] scale_list = [(cat.left, cat.right)]
...@@ -100,9 +103,11 @@ def check_if_answer_exists(answer_type, page_id): ...@@ -100,9 +103,11 @@ def check_if_answer_exists(answer_type, page_id):
check_answer = None check_answer = None
if answer_type == 'embody': if answer_type == 'embody':
check_answer = embody_answer.query.filter(and_(embody_answer.answer_set_idanswer_set==session['answer_set'], embody_answer.page_idpage==page_id)).first() check_answer = embody_answer.query.filter(and_(
embody_answer.answer_set_idanswer_set == session['answer_set'], embody_answer.page_idpage == page_id)).first()
elif answer_type == 'slider': elif answer_type == 'slider':
check_answer = answer.query.filter(and_(answer.answer_set_idanswer_set==session['answer_set'], answer.page_idpage==page_id)).first() check_answer = answer.query.filter(and_(
answer.answer_set_idanswer_set == session['answer_set'], answer.page_idpage == page_id)).first()
return check_answer return check_answer
...@@ -124,6 +129,7 @@ def get_experiment_info(): ...@@ -124,6 +129,7 @@ def get_experiment_info():
flash("No valid session found") flash("No valid session found")
return redirect('/') return redirect('/')
def embody_on(): def embody_on():
"""Check from session[exp_id] if embody questions are enabled""" """Check from session[exp_id] if embody questions are enabled"""
experiment_info = get_experiment_info() experiment_info = get_experiment_info()
...@@ -136,7 +142,8 @@ def embody_on(): ...@@ -136,7 +142,8 @@ def embody_on():
def slider_on(): def slider_on():
"""Check from session[exp_id] if there are slider questions in this session""" """Check from session[exp_id] if there are slider questions in this session"""
experiment_info = get_experiment_info() experiment_info = get_experiment_info()
questions = question.query.filter_by(experiment_idexperiment=experiment_info.idexperiment).all() questions = question.query.filter_by(
experiment_idexperiment=experiment_info.idexperiment).all()
if len(questions) == 0: if len(questions) == 0:
return False return False
...@@ -149,7 +156,8 @@ def task_embody(page_num): ...@@ -149,7 +156,8 @@ def task_embody(page_num):
'''Save embody drawing to database.''' '''Save embody drawing to database.'''
form = StringForm(request.form) form = StringForm(request.form)
pages = page.query.filter_by(experiment_idexperiment=session['exp_id']).paginate(per_page=1, page=page_num, error_out=True) pages = page.query.filter_by(experiment_idexperiment=session['exp_id']).paginate(
per_page=1, page=page_num, error_out=True)
page_id = pages.items[0].idpage page_id = pages.items[0].idpage
if form.validate(): if form.validate():
...@@ -195,7 +203,8 @@ def task_answer(page_num): ...@@ -195,7 +203,8 @@ def task_answer(page_num):
'''Save slider answers to database''' '''Save slider answers to database'''
form = TaskForm(request.form) form = TaskForm(request.form)
pages = page.query.filter_by(experiment_idexperiment=session['exp_id']).paginate(per_page=1, page=page_num, error_out=True) pages = page.query.filter_by(experiment_idexperiment=session['exp_id']).paginate(
per_page=1, page=page_num, error_out=True)
page_id = pages.items[0].idpage page_id = pages.items[0].idpage
if form.validate(): if form.validate():
...@@ -232,7 +241,8 @@ def task(page_num): ...@@ -232,7 +241,8 @@ def task(page_num):
stimulus_size = experiment_info.stimulus_size stimulus_size = experiment_info.stimulus_size
stimulus_size_text = 7-math.ceil((int(stimulus_size)/2)) stimulus_size_text = 7-math.ceil((int(stimulus_size)/2))
pages = page.query.filter_by(experiment_idexperiment=session['exp_id']).paginate(per_page=1, page=page_num, error_out=True) pages = page.query.filter_by(experiment_idexperiment=session['exp_id']).paginate(
per_page=1, page=page_num, error_out=True)
page_id = pages.items[0].idpage page_id = pages.items[0].idpage
progress_bar_percentage = round((pages.page/pages.pages)*100) progress_bar_percentage = round((pages.page/pages.pages)*100)
session['current_idpage'] = page_id session['current_idpage'] = page_id
...@@ -241,10 +251,12 @@ def task(page_num): ...@@ -241,10 +251,12 @@ def task(page_num):
# but we will pass the randomized pair of the page_id from trial randomization table to the task.html # but we will pass the randomized pair of the page_id from trial randomization table to the task.html
if session['randomization'] == 'On': if session['randomization'] == 'On':
randomized_page_id = get_randomized_page(page_id).randomized_idpage randomized_page_id = get_randomized_page(page_id).randomized_idpage
randomized_stimulus = page.query.filter_by(idpage=randomized_page_id).first() randomized_stimulus = page.query.filter_by(
idpage=randomized_page_id).first()
# get all embody questions # get all embody questions
embody_questions = embody_question.query.filter_by(experiment_idexperiment=session['exp_id']).all() embody_questions = embody_question.query.filter_by(
experiment_idexperiment=session['exp_id']).all()
return render_template( return render_template(
'task.html', 'task.html',
...@@ -285,7 +297,8 @@ def continue_task(): ...@@ -285,7 +297,8 @@ def continue_task():
if form.validate_on_submit(): if form.validate_on_submit():
# check if participant ID is found from db and that the answer set is linked to the correct experiment # check if participant ID is found from db and that the answer set is linked to the correct experiment
participant = answer_set.query.filter(and_(answer_set.session==form.participant_id.data, answer_set.experiment_idexperiment==exp_id)).first() participant = answer_set.query.filter(and_(
answer_set.session == form.participant_id.data, answer_set.experiment_idexperiment == exp_id)).first()
if participant is None: if participant is None:
flash('Invalid ID') flash('Invalid ID')
return redirect(url_for('task.continue_task', exp_id=exp_id)) return redirect(url_for('task.continue_task', exp_id=exp_id))
...@@ -298,7 +311,8 @@ def continue_task(): ...@@ -298,7 +311,8 @@ def continue_task():
update_answer_set_type(participant.answer_type) update_answer_set_type(participant.answer_type)
mediatype = page.query.filter_by(experiment_idexperiment=session['exp_id']).first() mediatype = page.query.filter_by(
experiment_idexperiment=session['exp_id']).first()
if mediatype: if mediatype:
session['type'] = mediatype.type session['type'] = mediatype.type
else: else:
...@@ -310,7 +324,8 @@ def continue_task(): ...@@ -310,7 +324,8 @@ def continue_task():
return redirect(url_for('task.task', page_num=1)) return redirect(url_for('task.task', page_num=1))
redirect_to_page = participant.answer_counter + 1 redirect_to_page = participant.answer_counter + 1
experiment_page_count = db.session.query(page).filter_by(experiment_idexperiment=session['exp_id']).count() experiment_page_count = db.session.query(page).filter_by(
experiment_idexperiment=session['exp_id']).count()
# If participant has ansvered all pages allready redirect to task completed page # If participant has ansvered all pages allready redirect to task completed page
if experiment_page_count == participant.answer_counter: if experiment_page_count == participant.answer_counter:
......
...@@ -20,7 +20,8 @@ def timeit(method): ...@@ -20,7 +20,8 @@ def timeit(method):
name = kw.get('log_name', method.__name__.upper()) name = kw.get('log_name', method.__name__.upper())
kw['log_time'][name] = int((te - ts) * 1000) kw['log_time'][name] = int((te - ts) * 1000)
else: else:
app.logger.info('{} {:2.2f} ms'.format(method.__name__, (te - ts) * 1000)) app.logger.info('{} {:2.2f} ms'.format(
method.__name__, (te - ts) * 1000))
return result return result
return timed return timed
...@@ -106,42 +107,6 @@ def map_answers_to_questions(answers, questions): ...@@ -106,42 +107,6 @@ def map_answers_to_questions(answers, questions):
return results return results
'''
return list(map(
lambda x: get_values_from_list_of_answers(x, answers),
questions))
'''
'''
select sub.answer_set_idanswer_set, group_concat(concat(
COALESCE(sub.aa, ''),
COALESCE(sub.ab, ''),
COALESCE(sub.ba, ''),
COALESCE(sub.bb, ''),
COALESCE(sub.ca, ''),
COALESCE(sub.cb, '')
))
FROM (
select *,
case when page_idpage = 4 and question_idquestion = 1 then answer end as aa,
case when page_idpage = 4 and question_idquestion = 2 then answer end as ab,
case when page_idpage = 5 and question_idquestion = 1 then answer end as ba,
case when page_idpage = 5 and question_idquestion = 2 then answer end as bb,
case when page_idpage = 6 and question_idquestion = 1 then answer end as ca,
case when page_idpage = 6 and question_idquestion = 2 then answer end as cb
from answer where answer_set_idanswer_set in ( select idanswer_set from answer_set where experiment_idexperiment = 2 and answer_counter != 0 )
) as sub
group by sub.answer_set_idanswer_set;
# all possible page/question comobs
select distinct p.idpage, q.idquestion from question q join page p on p.experiment_idexperiment=q.experiment_idexperiment where p.experiment_idexperiment = 2 order by p.idpage,q.idquestion;
'''
@timeit @timeit
def generate_csv(exp_id): def generate_csv(exp_id):
...@@ -291,7 +256,8 @@ def generate_answer_row(participant, pages, questions, embody_questions): ...@@ -291,7 +256,8 @@ def generate_answer_row(participant, pages, questions, embody_questions):
try: try:
# for every brush stroke, increment the pixel # for every brush stroke, increment the pixel
# value for every brush stroke # value for every brush stroke
coordinates_to_bitmap[int(point[0])][int(point[1])] += 0.1 coordinates_to_bitmap[int(
point[0])][int(point[1])] += 0.1
except IndexError: except IndexError:
continue continue
......
from decouple import config from decouple import config
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object): class Config(object):
# seret key is set in __ini__.py
#SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
LANGUAGES = ['en', 'fi', 'fa', 'el', 'it', 'zh'] LANGUAGES = ['en', 'fi', 'fa', 'el', 'it', 'zh']
"""
#SQLITE3 connection settings:
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
"""
# MariaDB mysql database settings # MariaDB mysql database settings
MYSQL_USER = config('MYSQL_USER') MYSQL_USER = config('MYSQL_USER')
MYSQL_PASSWORD = config('MYSQL_PASSWORD') MYSQL_PASSWORD = config('MYSQL_PASSWORD')
MYSQL_SERVER = config('MYSQL_SERVER') MYSQL_SERVER = config('MYSQL_SERVER')
......
...@@ -29,7 +29,6 @@ CREATE TABLE user ( ...@@ -29,7 +29,6 @@ CREATE TABLE user (
password_hash VARCHAR(128), password_hash VARCHAR(128),
PRIMARY KEY (id) PRIMARY KEY (id)
); );
INSERT INTO user VALUES(1,'timo',NULL,'pbkdf2:sha256:50000$sctKb5R4$688ff9fd63df4a0883b9eb003b6738c6b7baa2010e1cd503c678b43c881c07bf');
CREATE TABLE answer_set ( CREATE TABLE answer_set (
idanswer_set INTEGER NOT NULL, idanswer_set INTEGER NOT NULL,
experiment_idexperiment INTEGER, experiment_idexperiment INTEGER,
......
...@@ -5,27 +5,17 @@ Visualize emBODY data ...@@ -5,27 +5,17 @@ Visualize emBODY data
This python script is based on matlab code found from: This python script is based on matlab code found from:
https://version.aalto.fi/gitlab/eglerean/embody/tree/master/matlab https://version.aalto.fi/gitlab/eglerean/embody/tree/master/matlab
Requirements:
- python 3+
- matplotlib
- numpy
- scipy
Run:
python embody_plot.py
""" """
import sys from config import Config
from app import socketio, app
from flask_socketio import emit
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import time import time
import datetime import datetime
import json import json
import resource
import mysql.connector as mariadb import mysql.connector as mariadb
import io
import urllib, base64
import argparse import argparse
import numpy as np import numpy as np
...@@ -34,15 +24,6 @@ import scipy.ndimage as ndimage ...@@ -34,15 +24,6 @@ import scipy.ndimage as ndimage
import matplotlib import matplotlib
matplotlib.use('agg') matplotlib.use('agg')
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from flask_socketio import emit
from app import socketio, app
from config import Config
# Hard coded image size for default embody image # Hard coded image size for default embody image
WIDTH = 207 WIDTH = 207
...@@ -113,7 +94,7 @@ def timeit(method): ...@@ -113,7 +94,7 @@ def timeit(method):
name = kw.get('log_name', method.__name__.upper()) name = kw.get('log_name', method.__name__.upper())
kw['log_time'][name] = int((te - ts) * 1000) kw['log_time'][name] = int((te - ts) * 1000)
else: else:
print('%r %2.2f ms' % \ print('%r %2.2f ms' %
(method.__name__, (te - ts) * 1000)) (method.__name__, (te - ts) * 1000))
return result return result
...@@ -134,7 +115,8 @@ def get_coordinates(idpage, idembody=None, select_clause=SELECT_BY_PAGE_AND_PICT ...@@ -134,7 +115,8 @@ def get_coordinates(idpage, idembody=None, select_clause=SELECT_BY_PAGE_AND_PICT
if idembody: if idembody:
# Get image path # Get image path
image_query = db.query('SELECT picture from embody_question where idembody=%s', (idembody,)) image_query = db.query(
'SELECT picture from embody_question where idembody=%s', (idembody,))
image_path = db._db_cur.fetchone()[0] image_path = db._db_cur.fetchone()[0]
image_path = './app' + image_path image_path = './app' + image_path
...@@ -170,7 +152,8 @@ def format_coordinates(cursor): ...@@ -170,7 +152,8 @@ def format_coordinates(cursor):
y.extend(coordinates['y']) y.extend(coordinates['y'])
r.extend(coordinates['r']) r.extend(coordinates['r'])
except KeyError: except KeyError:
standard_radiuses = np.full((1, len(coordinates['x'])), standard_radius).tolist()[0] standard_radiuses = np.full(
(1, len(coordinates['x'])), standard_radius).tolist()[0]
r.extend(standard_radiuses) r.extend(standard_radiuses)
continue continue
except ValueError as err: except ValueError as err:
...@@ -197,7 +180,6 @@ def plot_coordinates(coordinates, image_path=DEFAULT_IMAGE_PATH): ...@@ -197,7 +180,6 @@ def plot_coordinates(coordinates, image_path=DEFAULT_IMAGE_PATH):
# Init plots # Init plots
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2) fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2)
# Draw circles from coordinates (imshow don't need interpolation) # Draw circles from coordinates (imshow don't need interpolation)
# TODO: set sigma according to brush size! # TODO: set sigma according to brush size!
ax2.set_title("gaussian disk around points / raw image") ax2.set_title("gaussian disk around points / raw image")
...@@ -250,27 +232,19 @@ def plot_coordinates(coordinates, image_path=DEFAULT_IMAGE_PATH): ...@@ -250,27 +232,19 @@ def plot_coordinates(coordinates, image_path=DEFAULT_IMAGE_PATH):
# return figure for saving/etc... # return figure for saving/etc...
return fig return fig
'''
# Return image as bytes
fig = plt.gcf()
imgdata = io.BytesIO()
fig.savefig(imgdata, format='png')
imgdata.seek(0) # rewind the data
return imgdata.read()
#Show image
mng = plt.get_current_fig_manager()
mng.resize(*mng.window.maxsize())
plt.show()
'''
if __name__ == '__main__': if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(description='Draw bodily maps of emotions') arg_parser = argparse.ArgumentParser(
arg_parser.add_argument('-s','--stimulus', help='Select drawn points from certain stimulus', required=False, action='store_true') description='Draw bodily maps of emotions')
arg_parser.add_argument('-e','--experiment', help='Select drawn points from certain experiment', required=False, action='store_true') arg_parser.add_argument(
arg_parser.add_argument('-a','--answer-set', help='Select drawn points from certain answer_set', required=False, action='store_true') '-s', '--stimulus', help='Select drawn points from certain stimulus', required=False, action='store_true')
arg_parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator') arg_parser.add_argument(
'-e', '--experiment', help='Select drawn points from certain experiment', required=False, action='store_true')
arg_parser.add_argument(
'-a', '--answer-set', help='Select drawn points from certain answer_set', required=False, action='store_true')
arg_parser.add_argument('integers', metavar='N', type=int,
nargs='+', help='an integer for the accumulator')
args = vars(arg_parser.parse_args()) args = vars(arg_parser.parse_args())
value = args['integers'][0] value = args['integers'][0]
...@@ -282,7 +256,3 @@ if __name__=='__main__': ...@@ -282,7 +256,3 @@ if __name__=='__main__':
get_coordinates(value, None, SELECT_BY_EXP_ID) get_coordinates(value, None, SELECT_BY_EXP_ID)
else: else:
print("No arguments given. Exit.") print("No arguments given. Exit.")
sys.exit(0)
Generic single-database configuration.
\ No newline at end of file
# A generic, single database configuration.
[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
import logging
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from flask import current_app
config.set_main_option('sqlalchemy.url',
current_app.config.get('SQLALCHEMY_DATABASE_URI'))
target_metadata = current_app.extensions['migrate'].db.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')
engine = engine_from_config(config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
connection = engine.connect()
context.configure(connection=connection,
target_metadata=target_metadata,
process_revision_directives=process_revision_directives,
**current_app.extensions['migrate'].configure_args)
try:
with context.begin_transaction():
context.run_migrations()
finally:
connection.close()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}
"""empty message
Revision ID: aea4a0f982b4
Revises:
Create Date: 2018-11-28 17:07:11.577139
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'aea4a0f982b4'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('background_question',
sa.Column('idbackground_question', sa.Integer(), nullable=False),
sa.Column('background_question', sa.String(length=120), nullable=True),
sa.Column('experiment_idexperiment', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('idbackground_question')
)
op.create_table('experiment',
sa.Column('idexperiment', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=120), nullable=True),
sa.Column('instruction', sa.Text(), nullable=True),
sa.Column('directoryname', sa.String(length=120), nullable=True),
sa.Column('language', sa.String(length=120), nullable=True),
sa.Column('status', sa.String(length=120), nullable=True),
sa.Column('randomization', sa.String(length=120), nullable=True),
sa.Column('short_instruction', sa.Text(), nullable=True),
sa.Column('single_sentence_instruction', sa.Text(), nullable=True),
sa.Column('is_archived', sa.String(length=120), nullable=True),
sa.Column('creator_name', sa.String(length=120), nullable=True),
sa.Column('research_notification_filename', sa.String(length=120), nullable=True),
sa.Column('creation_time', sa.DateTime(), nullable=True),
sa.Column('stimulus_size', sa.String(length=120), nullable=True),
sa.Column('consent_text', sa.Text(), nullable=True),
sa.Column('use_forced_id', sa.String(length=120), nullable=True),
sa.PrimaryKeyConstraint('idexperiment')
)
op.create_index(op.f('ix_experiment_consent_text'), 'experiment', ['consent_text'], unique=False)
op.create_index(op.f('ix_experiment_creation_time'), 'experiment', ['creation_time'], unique=False)
op.create_index(op.f('ix_experiment_directoryname'), 'experiment', ['directoryname'], unique=True)
op.create_index(op.f('ix_experiment_instruction'), 'experiment', ['instruction'], unique=False)
op.create_index(op.f('ix_experiment_name'), 'experiment', ['name'], unique=False)
op.create_index(op.f('ix_experiment_short_instruction'), 'experiment', ['short_instruction'], unique=False)
op.create_index(op.f('ix_experiment_single_sentence_instruction'), 'experiment', ['single_sentence_instruction'], unique=False)
op.create_table('trial_randomization',
sa.Column('idtrial_randomization', sa.Integer(), nullable=False),
sa.Column('page_idpage', sa.Integer(), nullable=True),
sa.Column('randomized_idpage', sa.Integer(), nullable=True),
sa.Column('answer_set_idanswer_set', sa.Integer(), nullable=True),
sa.Column('experiment_idexperiment', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('idtrial_randomization')
)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=64), nullable=True),
sa.Column('email', sa.String(length=120), nullable=True),
sa.Column('password_hash', sa.String(length=128), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)
op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=True)
op.create_table('answer_set',
sa.Column('idanswer_set', sa.Integer(), nullable=False),
sa.Column('experiment_idexperiment', sa.Integer(), nullable=True),
sa.Column('session', sa.String(length=120), nullable=True),
sa.Column('agreement', sa.String(length=120), nullable=True),
sa.Column('answer_counter', sa.Integer(), nullable=True),
sa.Column('registration_time', sa.DateTime(), nullable=True),
sa.Column('last_answer_time', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['experiment_idexperiment'], ['experiment.idexperiment'], ),
sa.PrimaryKeyConstraint('idanswer_set')
)
op.create_index(op.f('ix_answer_set_last_answer_time'), 'answer_set', ['last_answer_time'], unique=False)
op.create_index(op.f('ix_answer_set_registration_time'), 'answer_set', ['registration_time'], unique=False)
op.create_table('background_question_option',
sa.Column('idbackground_question_option', sa.Integer(), nullable=False),
sa.Column('background_question_idbackground_question', sa.Integer(), nullable=True),
sa.Column('option', sa.String(length=120), nullable=True),
sa.ForeignKeyConstraint(['background_question_idbackground_question'], ['background_question.idbackground_question'], ),
sa.PrimaryKeyConstraint('idbackground_question_option')
)
op.create_table('forced_id',
sa.Column('idforced_id', sa.Integer(), nullable=False),
sa.Column('experiment_idexperiment', sa.Integer(), nullable=True),
sa.Column('pregenerated_id', sa.String(length=120), nullable=True),
sa.ForeignKeyConstraint(['experiment_idexperiment'], ['experiment.idexperiment'], ),
sa.PrimaryKeyConstraint('idforced_id')
)
op.create_table('page',
sa.Column('idpage', sa.Integer(), nullable=False),
sa.Column('experiment_idexperiment', sa.Integer(), nullable=True),
sa.Column('type', sa.String(length=120), nullable=True),
sa.Column('text', sa.String(length=120), nullable=True),
sa.Column('media', sa.String(length=120), nullable=True),
sa.ForeignKeyConstraint(['experiment_idexperiment'], ['experiment.idexperiment'], ),
sa.PrimaryKeyConstraint('idpage')
)
op.create_index(op.f('ix_page_media'), 'page', ['media'], unique=False)
op.create_index(op.f('ix_page_text'), 'page', ['text'], unique=False)
op.create_index(op.f('ix_page_type'), 'page', ['type'], unique=False)
op.create_table('question',
sa.Column('idquestion', sa.Integer(), nullable=False),
sa.Column('experiment_idexperiment', sa.Integer(), nullable=True),
sa.Column('question', sa.String(length=120), nullable=True),
sa.Column('left', sa.String(length=120), nullable=True),
sa.Column('right', sa.String(length=120), nullable=True),
sa.ForeignKeyConstraint(['experiment_idexperiment'], ['experiment.idexperiment'], ),
sa.PrimaryKeyConstraint('idquestion')
)
op.create_table('answer',
sa.Column('idanswer', sa.Integer(), nullable=False),
sa.Column('question_idquestion', sa.Integer(), nullable=True),
sa.Column('answer_set_idanswer_set', sa.Integer(), nullable=True),
sa.Column('answer', sa.String(length=120), nullable=True),
sa.Column('page_idpage', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['answer_set_idanswer_set'], ['answer_set.idanswer_set'], ),
sa.ForeignKeyConstraint(['page_idpage'], ['page.idpage'], ),
sa.ForeignKeyConstraint(['question_idquestion'], ['question.idquestion'], ),
sa.PrimaryKeyConstraint('idanswer')
)
op.create_table('background_question_answer',
sa.Column('idbackground_question_answer', sa.Integer(), nullable=False),
sa.Column('answer_set_idanswer_set', sa.Integer(), nullable=True),
sa.Column('answer', sa.String(length=120), nullable=True),
sa.Column('background_question_idbackground_question', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['answer_set_idanswer_set'], ['answer_set.idanswer_set'], ),
sa.ForeignKeyConstraint(['background_question_idbackground_question'], ['background_question.idbackground_question'], ),
sa.PrimaryKeyConstraint('idbackground_question_answer')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('background_question_answer')
op.drop_table('answer')
op.drop_table('question')
op.drop_index(op.f('ix_page_type'), table_name='page')
op.drop_index(op.f('ix_page_text'), table_name='page')
op.drop_index(op.f('ix_page_media'), table_name='page')
op.drop_table('page')
op.drop_table('forced_id')
op.drop_table('background_question_option')
op.drop_index(op.f('ix_answer_set_registration_time'), table_name='answer_set')
op.drop_index(op.f('ix_answer_set_last_answer_time'), table_name='answer_set')
op.drop_table('answer_set')
op.drop_index(op.f('ix_user_username'), table_name='user')
op.drop_index(op.f('ix_user_email'), table_name='user')
op.drop_table('user')
op.drop_table('trial_randomization')
op.drop_index(op.f('ix_experiment_single_sentence_instruction'), table_name='experiment')
op.drop_index(op.f('ix_experiment_short_instruction'), table_name='experiment')
op.drop_index(op.f('ix_experiment_name'), table_name='experiment')
op.drop_index(op.f('ix_experiment_instruction'), table_name='experiment')
op.drop_index(op.f('ix_experiment_directoryname'), table_name='experiment')
op.drop_index(op.f('ix_experiment_creation_time'), table_name='experiment')
op.drop_index(op.f('ix_experiment_consent_text'), table_name='experiment')
op.drop_table('experiment')
op.drop_table('background_question')
# ### end Alembic commands ###
...@@ -22,12 +22,10 @@ in onni.utu.fu) to the same path as the script. ...@@ -22,12 +22,10 @@ in onni.utu.fu) to the same path as the script.
''' '''
import copy import copy
import numpy as np import numpy as np
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import csv import csv
import sys import sys
import json
csv.field_size_limit(sys.maxsize) csv.field_size_limit(sys.maxsize)
...@@ -58,7 +56,6 @@ def show_images(images, cols=1, titles=None): ...@@ -58,7 +56,6 @@ def show_images(images, cols=1, titles=None):
# set how the colormap handles 'bad' values # set how the colormap handles 'bad' values
my_cmap.set_bad(alpha=0) my_cmap.set_bad(alpha=0)
assert((titles is None) or (len(images) == len(titles))) assert((titles is None) or (len(images) == len(titles)))
n_images = len(images) n_images = len(images)
if titles is None: if titles is None:
......
import os
from app import app from app import app
# Setup logging
import logging import logging
from logging.handlers import RotatingFileHandler from logging.handlers import RotatingFileHandler
from logging import Formatter from logging import Formatter
...@@ -31,7 +29,6 @@ handler.setFormatter( ...@@ -31,7 +29,6 @@ handler.setFormatter(
app.logger.addHandler(handler) app.logger.addHandler(handler)
# Logging for production (nginx + gunicorn) # Logging for production (nginx + gunicorn)
import os
is_gunicorn = "gunicorn" in os.environ.get("SERVER_SOFTWARE", "") is_gunicorn = "gunicorn" in os.environ.get("SERVER_SOFTWARE", "")
if is_gunicorn: if is_gunicorn:
app.logger.info("Application run through gunicorn") app.logger.info("Application run through gunicorn")
...@@ -44,6 +41,3 @@ else: ...@@ -44,6 +41,3 @@ else:
log = logging.getLogger('werkzeug') log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR) log.setLevel(logging.ERROR)
''' '''
# EOF
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment