Beispiel #1
0
 def create_question(self):
     title = raw_input("Set title: ")
     if title == None:
         print("No question made")
         return None
     elif title in self.titles:
         print("A question with the same title already exists")
         return None
     question_string = raw_input("Type question: ")
     question = Questionnaire(title, question_string)
     add_answer_bool = True
     while add_answer_bool:
         print("Type an answer or type quit")
         answer = raw_input("Answer: ")
         if answer == "quit" or answer == "q":
             if question.count_answers():
                 self.add_question(question)
                 print("Question " + title + " successfully created")
             else:
                 print("Error: Question " + title +
                       " has no answers and was deleted")
             add_answer_bool = False
         elif answer:
             points = raw_input("Points: ")
             try:
                 p = int(points)
                 question.add_answer(answer, p)
             except:
                 print("Error: Point value must be numeric")
Beispiel #2
0
    def __init__(self,
                 df,
                 disease_name,
                 data_manager,
                 data_path='../data/',
                 pickle_path='../pickle/'):
        """
        Initializes a disease notifiable fields object with a pandas DataFrame.
        
        df requires at least 3 columns and a range index.
        optional columns are "Group", "Group Description", "Resource" (expects all 3)
        
        Rebuilds the groupings from group columns, if available.
        """
        self.data_path = data_path
        self.pickle_path = pickle_path
        self.disease_name = disease_name
        self.df = df
        self.index = df.index
        self.fhir_groups = {}
        self.data_manager = data_manager

        group_col = "Group"
        self.group_columns = [group_col, "Group Description", "Resource"]

        cols = self.df.columns

        # Generate a dictionary of {line#: (label, description)}
        self.lines = {i: tuple(df.loc[i, cols[:2]].values) for i in df.index}

        # Generate default Questionnaire
        self.questionnaire = Questionnaire(self.lines, self.disease_name)

        # if groupings have already been calculated, add them
        # The reverse process is done in save_disease
        if group_col in cols:
            for i in df.index:
                group_name, group_desc, resource = df.loc[i, cols[3:]].values
                if not pd.isnull(group_name) and len(
                        str(group_name).strip()) > 0:
                    if resource.lower() == 'questionnaire':
                        self.add_question_concept(group_name,
                                                  group_desc,
                                                  warn=False)
                        self.map_line_to_questionnaire(i, group_name)
                    else:
                        self.add_fhir_group(group_name,
                                            group_desc,
                                            resource,
                                            warn=False)
                        self.map_line_to_fhir_group(i, group_name)

        #if the columns don't already exist, add empty ones to the dataframe
        for column in self.group_columns:
            self.df[column] = None
 def test_format_answers(self):
     q = Questionnaire()
     q.add('k', prompter=lambda prompt: 'v')
     q.run()
     self.assertEqual(q.format_answers(fmt='obj'), '{"k": "v"}')
     self.assertEqual(q.format_answers(fmt='array'), '[["k", "v"]]')
     self.assertEqual(q.format_answers(fmt='plain'), 'k: v')
 def test_format_answers(self):
     q = Questionnaire()
     q.add('k', prompter=lambda prompt: 'v')
     q.run()
     self.assertEqual(q.format_answers(fmt='obj'), '{"k": "v"}')
     self.assertEqual(q.format_answers(fmt='array'), '[["k", "v"]]')
     self.assertEqual(q.format_answers(fmt='plain'), 'k: v')
Beispiel #5
0
    def _show_questionnaire(self, *args):
        '''
        showing questionnaire
        '''
        # Stop video and eeg record
        self._video_queue.put("stop_record")
        self._eeg_queue.put("stop_record")

        questionnaire = Questionnaire(subject_number, self._image_index)

        # This will call the fixation cross showing after disapearing the questionnaire
        questionnaire.connect("destroy", self._show_fixation_cross)
        questionnaire.show()
        time.sleep(GRAY_IMAGE_SHOW_TIME)
Beispiel #6
0
                      str(answers[key][1]))

    def send_question(self, title):
        question = self.get_question(title)
        if question:
            self.pub(question.serialize(), "question")

    def ask_for_results(self):
        self.pub("results", "results")


publish_key = 'pub-c-c96b6401-1254-4fe2-9d2a-0c193f5818ad'
subscribe_key = 'sub-c-24bd254c-df80-11e6-8652-02ee2ddab7fe'
name = "alex"
admin = Admin(publish_key, subscribe_key, name, "awesome")
q1 = Questionnaire("Q1", "What is 1+1?")
q1.add_answer("2", 1)
q1.add_answer("1", 0)
q1.add_answer("3", 0)
q1.add_answer("4", 0)
admin.add_question(q1)
# admin.pub(q1.serialize(), "question")
print("Type help for commands. Press CTRL+C to exit.")
while True:
    try:
        input = raw_input()
        if input:
            admin.commands(input)
    except KeyboardInterrupt:
        print("Exiting")
        admin.end_question()
Beispiel #7
0
from questionnaire import Questionnaire
import requests

q = Questionnaire(show_answers=False, can_go_back=False)
q.raw('user', prompt='Username:'******'pass', prompt='Password:'******'https://api.github.com/user/repos',
                 auth=(q.answers.get('user'), q.answers.get('pass')))
if not (r.ok):
    import sys
    print('username/password incorrect')
    sys.exit()

repos = [repo.get('url') for repo in r.json()]
q.one('repo', *repos, prompt='Choose a repo')
q.run()
print(q.answers.get('repo'))
Beispiel #8
0
if __name__ == '__main__':

    SERVICES_INITD = ['redis_6379', 'postgresql', 'nginx', 'firewall']
    SERVICES_UPSTART = [
        'gunicorn', 'celery-worker', 'celery-beat', 'celery-flower', 'django'
    ]
    SERVICES_DEV = SERVICES_INITD + [
        s + "-development" for s in SERVICES_UPSTART
    ]
    SERVICES_STG = SERVICES_INITD + [s + "-staging" for s in SERVICES_UPSTART]
    SERVICES_PRD = SERVICES_INITD + [
        s + "-production" for s in SERVICES_UPSTART
    ]

    q = Questionnaire()

    # ENV
    q.add_question('env', options=['development', 'staging', 'production'])

    # KIND
    q.add_question('kind', options=['deploy', 'service'])

    # PLAYBOOKS
    q.add_question('playbooks', prompter="multiple",
        options=['deploy', 'webserver', 'database', 'backend', 'webapp', 'api', 'message', 'staticfiles', 'create_user',]).\
        add_condition(keys=['kind'], vals=['deploy'])

    q.add_question('playbooks', prompter="multiple",
        options=['service', 'webserver', 'database', 'webapp', 'api', 'message',]).\
        add_condition(keys=['kind'], vals=['service'])
Beispiel #9
0
#!/usr/bin/env python

from questionnaire import Questionnaire
from languages import every_language, language_name_list
from google.cloud import *
from generator import generate

q = Questionnaire()
q.one("What is your language", 'Afrikaans', 'Albanian', 'Amharic', 'Arabic', 'Armenian', 'Azerbaijani', 'Basque', 'Belarusian', 'Bengali', 'Bosnian', 'Bulgarian', 'Catalan', 'Cebuano', 'Chichewa', 'Chinese (Simplified)', 'Chinese (Traditional)', 'Corsican', 'Croatian', 'Czech', 'Danish', 'Dutch', 'English', 'Esperanto', 'Estonian', 'Filipino', 'Finnish', 'French', 'Frisian', 'Galician', 'Georgian', 'German', 'Greek', 'Gujarati', 'Haitian Creole', 'Hausa', 'Hawaiian', 'Hebrew', 'Hindi', 'Hmong', 'Hungarian', 'Icelandic', 'Igbo', 'Indonesian', 'Irish', 'Italian', 'Japanese', 'Javanese', 'Kannada', 'Kazakh', 'Khmer', 'Korean', 'Kurdish (Kurmanji)', 'Kyrgyz', 'Lao', 'Latin', 'Latvian', 'Lithuanian', 'Luxembourgish', 'Macedonian', 'Malagasy', 'Malay', 'Malayalam', 'Maltese', 'Maori', 'Marathi', 'Mongolian', 'Myanmar (Burmese)', 'Nepali', 'Norwegian', 'Pashto', 'Persian', 'Polish', 'Portuguese', 'Punjabi', 'Romanian', 'Russian', 'Samoan', 'Scots Gaelic', 'Serbian', 'Sesotho', 'Shona', 'Sindhi', 'Sinhala', 'Slovak', 'Slovenian', 'Somali', 'Spanish', 'Sundanese', 'Swahili', 'Swedish', 'Tajik', 'Tamil', 'Telugu', 'Thai', 'Turkish', 'Ukrainian', 'Urdu', 'Uzbek', 'Vietnamese', 'Welsh', 'Xhosa', 'Yiddish', 'Yoruba', 'Zulu')
q.run()
a = q.format_answers(fmt='plain');
a = a.split(" ")

#language of choice
abbreviated_language = language_name_list[every_language.index(a[-1])][0]

# Instantiates a client
translate_client = translate.Client()


# Translates Quetionire into desired language
# translation = translate_client.translate(text,target_language=abbreviated_language)

q = Questionnaire()
q.raw(translate_client.translate('first_name',target_language=abbreviated_language)['translatedText'], prompt= translate_client.translate('What is your First Name?',target_language=abbreviated_language)['translatedText'])
q.raw(translate_client.translate('last_name',target_language=abbreviated_language)['translatedText'],prompt=translate_client.translate('What is your Last Name?',target_language=abbreviated_language)['translatedText'])
q.raw(translate_client.translate("email",target_language=abbreviated_language)['translatedText'],prompt=translate_client.translate('What is your email? ',target_language=abbreviated_language)['translatedText'])
q.raw(translate_client.translate("phone_number",target_language=abbreviated_language)['translatedText'],prompt=translate_client.translate('What is your phone number?',target_language=abbreviated_language)['translatedText'])
q.raw(translate_client.translate("address_line_1",target_language=abbreviated_language)['translatedText'],prompt=translate_client.translate('What is your street address?',target_language=abbreviated_language)['translatedText'])
q.raw(translate_client.translate("city",target_language=abbreviated_language)['translatedText'],prompt=translate_client.translate('What city?',target_language=abbreviated_language)['translatedText'])
q.raw(translate_client.translate("country",target_language=abbreviated_language)['translatedText'],prompt=translate_client.translate('What country?',target_language=abbreviated_language)['translatedText'])
Beispiel #10
0
from questionnaire import Questionnaire
q = Questionnaire(can_go_back=False)


def email(email):
    import re
    if not re.match(r'[^@]+@[^@]+\.[^@]+', email):
        return 'Enter a valid email'


def one(options):
    if len(options) < 1:
        return 'You must choose at least 1 type of junk mail'


def join(options):
    return ', '.join(options)


q.raw('email').validate(email)
q.many('junk_mail', 'this one weird trick', 'cheap viagra',
       'dermatologists hate her').validate(one).transform(join)

q.run()
print(q.answers)
Beispiel #11
0
from questionnaire import Questionnaire

q = Questionnaire()
q.raw('age', prompt='How old are you?', type=int)

q.one('plans',
      'Valley College',
      'La Escuela de Calor',
      prompt='Where do you want to go to school?').condition(('age', 18, '<='))
q.one('plans',
      'On a farm',
      'In an office',
      'On the couch',
      prompt='Where do you want to work?',
      idx=2).condition(('age', 40, '<='))
q.one('plans',
      'El Caribe',
      'Disneyland',
      'Las Islas Canarias',
      prompt='Where do you want to vacation?').condition(('age', 60, '<='))
q.one('plans',
      'El campo',
      'The beach',
      'San Miguel de Allende',
      prompt='Where do you want to retire?')

q.run()
print(q.answers)
    def test_questionnaire(self):
        q = Questionnaire()
        q.add('k', prompter=lambda prompt: 'v')
        q.run()
        self.assertEqual(q.answers['k'], 'v')

        q.add('k2', prompter=lambda prompt: 'v2_first').condition(('k', 'v_'))
        q.add('k2', prompter=lambda prompt: 'v2_second').condition(('k', 'v'))
        q.ask()
        self.assertEqual(q.answers['k2'], 'v2_second')
        self.assertEqual(len(q.answers), 2)

        q.add('k3', prompter=lambda prompt: randrange(10)).validate(
            lambda a: None if a == 0 else 'error'
        ).transform(lambda a: a-1)
        q.ask()
        self.assertEqual(q.answers['k3'], -1)

        q.reset()
        self.assertEqual(dict(q.answers), {})
Beispiel #13
0
from questionnaire import Questionnaire


def not_blank(value):
    return 'enter a color' if not value else None


q = Questionnaire(show_answers=False, can_go_back=False)
q.raw('color', prompt='Favorite color (type ENTER to insert the default value):', default='blue').validate(not_blank)

q.run()
print(q.answers.get('color'))
Beispiel #14
0
from questionnaire import Questionnaire

q = Questionnaire()
q.raw('age', prompt='How old are you?', type=int)

q.one('plans', 'Valley College', 'La Escuela de Calor', prompt='Where do you want to go to school?').condition(
    ('age', 18, '<='))
q.one('plans', 'On a farm', 'In an office', 'On the couch', prompt='Where do you want to work?', idx=2).condition(
    ('age', 40, '<='))
q.one('plans', 'El Caribe', 'Disneyland', 'Las Islas Canarias', prompt='Where do you want to vacation?').condition(
    ('age', 60, '<='))
q.one('plans', 'El campo', 'The beach', 'San Miguel de Allende', prompt='Where do you want to retire?')

q.run()
print(q.answers)
def Questions():
    '''
  AIM -> Create a good looking questionnaire to generate required arguments to be used with tweet_collection
  OUTPUT -> String with desired arguments
  '''

    # Initialize Questionnaire
    q = Questionnaire()

    # Create Raw Questions
    q.raw('Search Keyword')
    q.raw('Number of Tweets', type=int)
    q.raw('CSV Name')

    # Run the module
    q.run()

    return q.format_answers()
    def test_go_back_remove(self):
        def go_back(prompt):
            raise QuestionnaireGoBack(2)

        q = Questionnaire()
        q.add('k', prompter=lambda prompt: 'v')
        q.ask()
        self.assertEqual(q.answers['k'], 'v')

        q.add('k2', prompter=lambda prompt: 'v2')
        q.ask()
        self.assertEqual(q.answers['k2'], 'v2')

        q.go_back(1)
        self.assertEqual(q.answers['k'], 'v')
        self.assertEqual(q.answers.get('k2'), None)
        q.ask()
        self.assertEqual(q.answers['k2'], 'v2')

        q.add('k3', prompter=go_back)
        q.ask()
        self.assertEqual(len(q.answers), 0)

        q.remove('k2')
        q.remove('k3')
        q.run()
        self.assertEqual(dict(q.answers), {'k': 'v'})
    def test_questionnaire(self):
        q = Questionnaire()
        q.add('k', prompter=lambda prompt: 'v')
        q.run()
        self.assertEqual(q.answers['k'], 'v')

        q.add('k2', prompter=lambda prompt: 'v2_first').condition(('k', 'v_'))
        q.add('k2', prompter=lambda prompt: 'v2_second').condition(('k', 'v'))
        q.ask()
        self.assertEqual(q.answers['k2'], 'v2_second')
        self.assertEqual(len(q.answers), 2)

        q.add('k3', prompter=lambda prompt: randrange(10)).validate(
            lambda a: None if a == 0 else 'error').transform(lambda a: a - 1)
        q.ask()
        self.assertEqual(q.answers['k3'], -1)

        q.reset()
        self.assertEqual(dict(q.answers), {})
Beispiel #18
0
from questionnaire import Questionnaire


def not_blank(value):
    return 'enter a color' if not value else None


q = Questionnaire(show_answers=False, can_go_back=False)
q.raw('color',
      prompt='Favorite color (type ENTER to insert the default value):',
      default='blue').validate(not_blank)

q.run()
print(q.answers.get('color'))
    def test_go_back_remove(self):
        def go_back(prompt):
            raise QuestionnaireGoBack(2)

        q = Questionnaire()
        q.add('k', prompter=lambda prompt: 'v')
        q.ask()
        self.assertEqual(q.answers['k'], 'v')

        q.add('k2', prompter=lambda prompt: 'v2')
        q.ask()
        self.assertEqual(q.answers['k2'], 'v2')

        q.go_back(1)
        self.assertEqual(q.answers['k'], 'v')
        self.assertEqual(q.answers.get('k2'), None)
        q.ask()
        self.assertEqual(q.answers['k2'], 'v2')

        q.add('k3', prompter=go_back)
        q.ask()
        self.assertEqual(len(q.answers), 0)

        q.remove('k2')
        q.remove('k3')
        q.run()
        self.assertEqual(dict(q.answers), {'k': 'v'})
        if services and "all" not in services:
            extra_vars['services'] = services
    if extra_vars:
        command += " --extra-vars=\"{}\"".format(extra_vars)
    return command


if __name__ == '__main__':

    SERVICES_INITD = ['redis_6379', 'postgresql', 'nginx', 'firewall']
    SERVICES_UPSTART = ['gunicorn', 'celery-worker', 'celery-beat', 'celery-flower', 'django']
    SERVICES_DEV = SERVICES_INITD + [s + "-development" for s in SERVICES_UPSTART]
    SERVICES_STG = SERVICES_INITD + [s + "-staging" for s in SERVICES_UPSTART]
    SERVICES_PRD = SERVICES_INITD + [s + "-production" for s in SERVICES_UPSTART]

    q = Questionnaire()

    # ENV
    q.add_question('env', options=['development', 'staging', 'production'])

    # KIND
    q.add_question('kind', options=['deploy', 'service'])

    # PLAYBOOKS
    q.add_question('playbooks', prompter="multiple",
        options=['deploy', 'webserver', 'database', 'backend', 'webapp', 'api', 'message', 'staticfiles', 'create_user',]).\
        add_condition(keys=['kind'], vals=['deploy'])

    q.add_question('playbooks', prompter="multiple",
        options=['service', 'webserver', 'database', 'webapp', 'api', 'message',]).\
        add_condition(keys=['kind'], vals=['service'])
Beispiel #21
0
# import the Flask class from the flask module
from flask import render_template, request, redirect, url_for

from questionnaire import Questionnaire
from forms import LoginForm
from app import app

questionnaire = Questionnaire("core")


@app.route('/')
def home():
    return render_template('index.html')


@app.route('/welcome', methods=['POST', 'GET'])
def welcome():
    if request.method == 'POST':
        return redirect(url_for('menu'))
    # print questionnaire.get_assessment_results()
    else:
        return render_template('welcome.html')


@app.route('/assessment')
def assessment():
    questionnaire.create_new_questionnaire()
    return render_template('assessment.html',
                           assessment_id=questionnaire.assessment.id)

Beispiel #22
0
from questionnaire import Questionnaire
q = Questionnaire()

q.one('day', 'monday', 'friday', 'saturday')
q.one('time', 'morning', 'night')

q.many('activities', 'tacos de pastor', 'go to cantina', 'write code').condition(('time', 'night'))
q.many('activities', 'barbacoa', 'watch footy', 'walk dog').condition(('day', 'saturday'), ('time', 'morning'))
q.many('activities', 'eat granola', 'get dressed', 'go to work').condition(('time', 'morning'))

q.run()
print(q.format_answers(fmt='array'))
Beispiel #23
0
from questionnaire import Questionnaire
q = Questionnaire()


def two(options):
    if len(options) < 2:
        return 'You must choose at least 2 options'


def join(options):
    return ', '.join(options)


q.many('options', 'Option 1', 'Option 2', 'Option 3', prompt='Choose some options').validate(two).transform(join)
q.many('more', 'Option 4', 'Option 5', 'Option 6', prompt='Choose some more').validate(two).transform(join)

q.run()
print(q.answers)


q.many('yet_more', 'Option 7', 'Option 8', prompt='And more...', default=[0, 1])
q.many('done', 'Option 9', 'Option 10', prompt='Last ones', default=1)

q.run()
print(q.answers)
Beispiel #24
0
from questionnaire import Questionnaire
q = Questionnaire()

q.one('day', 'monday', 'friday', 'saturday')
q.one('time', 'morning', 'night')

q.many('activities', 'tacos de pastor', 'go to cantina',
       'write code').condition(('time', 'night'))
q.many('activities', 'barbacoa', 'watch footy', 'walk dog').condition(
    ('day', 'saturday'), ('time', 'morning'))
q.many('activities', 'eat granola', 'get dressed', 'go to work').condition(
    ('time', 'morning'))

q.run()
print(q.format_answers(fmt='array'))
Beispiel #25
0
from questionnaire import Questionnaire
q = Questionnaire(can_go_back=False)


def email(email):
    import re
    if not re.match(r'[^@]+@[^@]+\.[^@]+', email):
        return 'Enter a valid email'


def one(options):
    if len(options) < 1:
        return 'You must choose at least 1 type of junk mail'


def join(options):
    return ', '.join(options)


q.raw('email').validate(email)
q.many('junk_mail', 'this one weird trick', 'cheap viagra', 'dermatologists hate her').validate(one).transform(join)

q.run()
print(q.answers)
Beispiel #26
0
from questionnaire import Questionnaire

q = Questionnaire()
q.add_question('age', prompter="raw", prompt='How old are you?', type=int)

# youngsters (age less than or equal to 18)
q.add_question('plans', prompt="Where do you want to go to school?", options=['Valley College', 'La Escuela de Calor']).\
    add_condition(keys=['age'], vals=[18], operators=['<='])
q.add_question('plans', prompt="Where do you want to work?", options=['On a farm', 'In an office', 'On the couch']).\
    add_condition(keys=['age'], vals=[40], operators=['<='])
q.add_question('plans', prompt="Where do you want to vacation?", options=['El Caribe', 'On a cruise ship', 'Las Islas Canarias']).\
    add_condition(keys=['age'], vals=[60], operators=['<='])
# old folks (more than 60 years old)
q.add_question('plans', prompt="Where do you want to retire?", options=['El campo', 'The beach', 'San Miguel de Allende'])

answers = q.run()
print(answers)
Beispiel #27
0
from questionnaire import Questionnaire
import requests

q = Questionnaire(show_answers=False, can_go_back=False)
q.raw('user', prompt='Username:'******'pass', prompt='Password:'******'https://api.github.com/user/repos', auth=(q.answers.get('user'), q.answers.get('pass')))
if not(r.ok):
    import sys
    print('username/password incorrect')
    sys.exit()

repos = [repo.get('url') for repo in r.json()]
q.one('repo', *repos, prompt='Choose a repo')
q.run()
print(q.answers.get('repo'))
Beispiel #28
0
class Disease(object):
    def __init__(self,
                 df,
                 disease_name,
                 data_manager,
                 data_path='../data/',
                 pickle_path='../pickle/'):
        """
        Initializes a disease notifiable fields object with a pandas DataFrame.
        
        df requires at least 3 columns and a range index.
        optional columns are "Group", "Group Description", "Resource" (expects all 3)
        
        Rebuilds the groupings from group columns, if available.
        """
        self.data_path = data_path
        self.pickle_path = pickle_path
        self.disease_name = disease_name
        self.df = df
        self.index = df.index
        self.fhir_groups = {}
        self.data_manager = data_manager

        group_col = "Group"
        self.group_columns = [group_col, "Group Description", "Resource"]

        cols = self.df.columns

        # Generate a dictionary of {line#: (label, description)}
        self.lines = {i: tuple(df.loc[i, cols[:2]].values) for i in df.index}

        # Generate default Questionnaire
        self.questionnaire = Questionnaire(self.lines, self.disease_name)

        # if groupings have already been calculated, add them
        # The reverse process is done in save_disease
        if group_col in cols:
            for i in df.index:
                group_name, group_desc, resource = df.loc[i, cols[3:]].values
                if not pd.isnull(group_name) and len(
                        str(group_name).strip()) > 0:
                    if resource.lower() == 'questionnaire':
                        self.add_question_concept(group_name,
                                                  group_desc,
                                                  warn=False)
                        self.map_line_to_questionnaire(i, group_name)
                    else:
                        self.add_fhir_group(group_name,
                                            group_desc,
                                            resource,
                                            warn=False)
                        self.map_line_to_fhir_group(i, group_name)

        #if the columns don't already exist, add empty ones to the dataframe
        for column in self.group_columns:
            self.df[column] = None

    def __getitem__(self, i):
        """ Get's the i-th item in the dataframe (includes group info). """
        if i in self.lines:
            return self.lines[i]
        return None

    def __contains__(self, i):
        return i in self.lines

    def add_fhir_group(self,
                       group_name,
                       group_description,
                       fhir_resource,
                       warn=True):
        if group_name not in self.fhir_groups:
            group = QueryGroup(self.disease_name, fhir_resource, group_name,
                               group_description, self.pickle_path)
            self.fhir_groups[group_name] = group
        elif warn:
            print("Group '{}' already exists".format(group_name))

    def map_line_to_fhir_group(self, line_number, group_name):
        """
        Map a line to a fhir resource by giving the line # and group name.
        To see what groups are available, check out the fhir_gorups variable.
        To create a new group, use add_fhir_group.
        
        Adds the mapping to 
        """
        if group_name not in self.fhir_groups:
            print(
                "Group {} not found in fhir_groups. Try adding the group first."
                .format(group_name))
            return

        self.unmap_line(line_number)
        grp = self.fhir_groups[group_name]
        label, description = self.lines[line_number]
        grp.map_line(line_number, label, description)

    def add_criteria_to_fhir_group(self, group_name, criteria_dict):
        """
        Given a group name, updates the search query criteria.
        The criteria dict are pairs of field:value that specify a single query.
        """
        if group_name not in self.fhir_groups:
            print("Could not add criteria to group: {}. Does not exist".format(
                group_name))
        group = self.fhir_groups[group_name]
        group.add_criteria(criteria_dict)

    def add_question_concept(self, concept, description, warn=True):
        if concept not in self.questionnaire:
            self.questionnaire.add_group(concept, description)
        elif warn:
            print("Questionnaire concept group '{}' already exists".format(
                concept))

    def map_line_to_questionnaire(self, line_number, concept):
        """
        Map a line to a questionnaire group by giving the line # and group name.
        To see what groups are available, check out the questionnaire variable.
        To create a new group, use add_question_concept.
        """
        if concept not in self.questionnaire:
            print(
                "Group {} not found in questionnaire. Try adding the question concept first."
                .format(concept))
            return
        self.unmap_line(line_number)
        self.questionnaire.map_line(concept, line_number)

    def unmap_line(self, line_number):
        """
        Removes a line from any existing mapping.
        """
        for concept, group in self.fhir_groups.items():
            group.unmap_line(line_number)
        self.questionnaire.unmap_line(line_number)

    def unmapped_lines(self):
        """
        Returns a dict of:
        line#: (Label, Description)
        For all the lines in the disease that are still in the default
        Questionnaire group.
        """
        line_numbers = self.questionnaire.unmapped_lines()
        for grp_name, grp in self.fhir_groups.items():
            line_numbers.extend(grp.lines.keys())

        lines = {i: v for i, v in self.lines.items() if i not in line_numbers}
        return lines

    def mapped_lines(self):
        """
        Returns a dictionary of {line#: (group, description, resource)}
        for lines that have been mapped to fhir groups or question concepts.
        """
        lines = self.questionnaire.mapped_lines()
        for grp_name, grp in self.fhir_groups.items():
            for line in grp.lines:
                lines[line] = (grp.name, grp.description, grp.resource_name)
        # Add the line's label and description to each tuple
        for num, line in lines.items():
            lines[num] = self.lines[num] + line

        #print("Output columns are (Label, Description, {}, {}, {})".format(*self.group_columns))
        return lines

    def search_mapped_lines(self, line_number):
        label, description = self.lines[line_number][:2]
        #print("Searching for line # {}: {}; {}.\n".format(line_number, label, description))
        return self.data_manager.search_mapped_lines(
            str(label) + " " + str(description))

    def search_unmapped_lines(self, line_number, n=10):
        """ Finds unmapped lines in this disease to facilitate grouping. """
        label, description = self.lines[line_number][:2]
        print("Searching for line # {}: {}; {}.\n".format(
            line_number, label, description))
        lines = [(i, ) + v for i, v in self.unmapped_lines().items()]
        sort_tuples(lines, description, 2)
        return lines[1:n + 1]  # The top match will always be the input line

    def refresh_df(self):
        """
        Uses the information in the questionnaire groups to update the DataFrame.
        """
        # Don't refresh if no mappings have been created
        if not all(col in self.df.columns for col in self.group_columns):
            return
        # delete info in the csv
        self.df.loc[:, self.group_columns] = pd.np.nan
        # Add the latest groupings back in
        questionnaire_lines = self.questionnaire.mapped_lines()

        fhir_query_lines = {}
        for grp_name, grp in self.fhir_groups.items():
            line_nums = grp.lines.keys()
            fhir_query_lines.update({
                i: (grp.name, grp.description, grp.resource_name)
                for i in line_nums
            })

        for i in questionnaire_lines:
            line = questionnaire_lines[i]
            self.df.loc[i, self.group_columns] = line
        for i in fhir_query_lines:
            self.df.loc[i, self.group_columns] = fhir_query_lines[i]

    def to_csv(self, path=None):
        """
        Saves the most updated DataFrame (including group mappings) to csv.
        Overwrites the old csv in the data path if no path is specified.
        Also pickles the criteria in the FHIR query groups.
        """
        if path is None:
            path = self.data_path

        self.refresh_df()
        if self.group_columns[0] in self.df.columns:
            self.df.to_csv(path + self.disease_name + '.csv', index=False)

        for group_name, group in self.fhir_groups.items():
            group.pickle()

    def as_json(self):
        print("JSON representations of the FHIR query groups:\n")

        for group_name, group in self.fhir_groups.items():
            print("{}:".format(group_name))
            print(group.as_json())
            print("\n")

        print("Questionnaire JSON:\n")
        print(self.questionnaire.as_json())
Beispiel #29
0
from questionnaire import Questionnaire
q = Questionnaire()


def two(options):
    if len(options) < 2:
        return 'You must choose at least 2 options'


def join(options):
    return ', '.join(options)


q.many('options',
       'Option 1',
       'Option 2',
       'Option 3',
       prompt='Choose some options').validate(two).transform(join)
q.many('more', 'Option 4', 'Option 5', 'Option 6',
       prompt='Choose some more').validate(two).transform(join)

q.run()
print(q.answers)

q.many('yet_more',
       'Option 7',
       'Option 8',
       prompt='And more...',
       default=[0, 1])
q.many('done', 'Option 9', 'Option 10', prompt='Last ones', default=1)
from questionnaire import Questionnaire

q = Questionnaire()
q.add_question('day', options=['monday', 'friday', 'saturday'])
q.add_question('time', options=['morning', 'night'])

# nights
q.add_question('activities', prompter='multiple', options=['eat tacos de pastor', 'go to the cantina', 'do some programming']).\
    add_condition(keys=['time'], vals=['night'])
# saturday morning
q.add_question('activities', prompter='multiple', options=['eat barbacoa', 'watch footy match', 'walk the dog']).\
    add_condition(keys=['day', 'time'], vals=['saturday', 'morning'])
# other mornings
q.add_question('activities', prompter='multiple', options=['eat granola', 'get dressed', 'go to work']).\
    add_condition(keys=['time'], vals=['morning'])

answers = q.run()
print(answers)