Exemple #1
0
def handle_search_benefit():
    """
    OPTION - Search Plans based on benefits

    This option would provide user all the available benefits.
    Then user is able to search all plans that cover this selected benefit.
    """

    # Search benefits list from database
    benefit_list = Query.get_benefit_list()

    # Select a benefit
    print("\n==============Plan Benefit==============")
    instruction = "Which benefit of do you want to query?:"
    ind = display_in_pages(benefit_list, ["Benefit"],
                           instruction,
                           showindex=True)
    if ind == -1:
        return
    benefit_type = benefit_list[int(ind)][0]

    # Query for the result
    results = Query.get_benefit(benefit_type=benefit_type)
    headers = ["Plan ID", "Benefit", "Quantity Limit", "Unit Limit"]
    if results:
        instruction = "You can select a plan for detail information: "
        ind = display_in_pages(results, headers, instruction, showindex=True)
        if ind >= 0:
            plan_id = results[ind][0]
            search_plan_detail_information(plan_id)
    else:
        print("\nNo plans found.")
        input("\nPress any key to continue.")
Exemple #2
0
async def process_choose_old_deadline(message: Message, state: FSMContext):
    user_data = await state.get_data()

    if message.text not in Database.show(subject=user_data['subject'],
                                         task=user_data['task']):
        await message.reply('Выберите дедлайн, используя клавиатуру ниже')
        return

    deadline = message.text[-10:]
    await state.update_data(deadline=deadline)
    user_data = await state.get_data()
    query = Query(subject=user_data['subject'],
                  task=user_data['task'],
                  deadline='.'.join(reversed(user_data['deadline'].split('.'))))
    if user_data['type'] == QueryTypes.DEL:
        Database.delete(query)
        await message.answer(f'Дедлайн {user_data["task"]} '
                             f'по предмету {user_data["subject"]} '
                             f'от {user_data["deadline"]} был удален',
                             reply_markup=ReplyKeyboardRemove())
        await state.finish()
    else:  # QueryTypes.UPD
        await message.answer('Введите дату дедлайна в формате ДД.ММ.ГГГГ',
                             reply_markup=ReplyKeyboardRemove())
        await StateMachine.waiting_for_new_date.set()
Exemple #3
0
def search_plan_sub_menu(constrains, insurance_type):
    """
    Sub Menu - Search Plan Using Dynamic Filter(s).

    :param constrains: filter constrains
    :param insurance_type: medical/dental plan
    """
    plans = list()
    options = list()
    options.append((1, "Select Plans"))
    options.append((2, "Add Filter"))
    options.append((3, "Remove Filter"))
    options.append((4, "Back to Menu"))
    attributes = [const.PLAN_ID, const.PLAN_VAR_NAME]
    detailed_constrains = collections.OrderedDict()

    while True:
        # Query the plans from database
        plans = Query.get_plans(attributes=attributes,
                                constrains=constrains,
                                detail_constrains=detailed_constrains,
                                insurance_type=insurance_type)
        # Update the record number
        options[0] = (1, "Show plans ({})".format(len(plans)))

        print("\n==========Insurance Plan - {} - {}==========".format(
            insurance_type.upper(),
            Enum.mark_cov_type_rev[constrains[const.MARK_COVERAGE][1]]))
        utils.print_data_frame(options, ["Index", "Option"])
        index = input("\nPlease select an option:")
        if index.strip() == "1":
            # Handle "Select Plans"
            instruction = "You can select a plan for detail information: "
            ind = display_in_pages(plans,
                                   attributes,
                                   instruction,
                                   showindex=True)
            if ind >= 0:
                plan_id = plans[ind][0]
                search_plan_detail_information(plan_id)

        elif index.strip() == "2":
            # Handle "Add Filter"
            if insurance_type == "medical":
                search_plan_add_filter_medical(constrains, detailed_constrains)
            else:
                search_plan_add_filter_dental(constrains, detailed_constrains)

        elif index.strip() == "3":
            # Handle "Remove Filter"
            search_plan_remove_filter(constrains, detailed_constrains,
                                      insurance_type)

        elif index.strip() == "4":
            # Handle "Quit"
            print("Bye.")
            return

        else:
            print("Invalid Index.")
Exemple #4
0
def test_cli(query_arguments=testqueries):
    """run several complex queries and print their results to stdout"""
    for arg in query_arguments:
        book_list = Books(Results(Query(arg)))
        print "{0}:\n\n".format(arg)
        for book in book_list.books:
            print book.title, book.year
Exemple #5
0
def gen_textplans(query):
    """
    debug function: generates all text plans for a query.
    
    :type query: ``int`` or ``list`` of ``str``
    :param query: can be the index of a test query (e.g. 4) OR a list of 
    query parameters (e.g. ["-k", "phonology", "-l", "German"])
    
    :rtype: ``TextPlans``
    :return: a ``TextPlans`` instance, containing a number of text plans
    """
    textplans = []
    if type(query) is int:
        books = Books(Results(Query(testqueries[query])))
        return TextPlans(AllMessages(AllPropositions(AllFacts(books))))
    if type(query) is list:
        books = Books(Results(Query(query)))
        return TextPlans(AllMessages(AllPropositions(AllFacts(books))))
Exemple #6
0
def genallmessages(query):
    """
    debug function: generates all messages plans for a query.
    
    :type query: ``int`` or ``list`` of ``str``
    :param query: can be the index of a test query (e.g. 4) OR a list of 
    query parameters (e.g. ["-k", "phonology", "-l", "German"])
    
    :rtype: ``AllMessages``
    :return: all messages that could be generated for the query
    """
    if isinstance(query, int):
        books = Books(Results(Query(testqueries[query])))
        return AllMessages(AllPropositions(AllFacts(books)))
    elif isinstance(query, list):
        books = Books(Results(Query(query)))
        return AllMessages(AllPropositions(AllFacts(books)))
    elif isinstance(query, Query):
        books = Books(Results(query))
        return AllMessages(AllPropositions(AllFacts(books)))
Exemple #7
0
def genprops(querynumber=10):
    """    
    generates all propositions for all books in the database concerning a 
    specific query.
    
    :type querynumber: ``int``
    :param querynumber: the index of a query from the predefined list of 
    test queries (named 'testqueries')
    
    :rtype: ``AllPropositions``
    """
    books = Books(Results(Query(testqueries[querynumber])))
    return AllPropositions(AllFacts(books))
 def get_scores(self):
     query = Query.get_by_query(self.query)
     if query is not None:
         details = query["details"]
         result = pd.DataFrame(details)
         dictionary = {
             "author": result["author"],
             "title": result["title"],
             "url": result["url"],
             "year": result["year"],
             "score": result["score"]
         }
         return dictionary
     else:
         transform = self.vectorizer.fit_transform(self.phrase)
         scores = (transform[0, :] * transform[1:, :].T).A[0]
         self.dataset["score"] = scores
         result = self.dataset.sort_values(by="score", ascending=False).head(10)
         dictionary = {
             "author": result["author"],
             "title": result["title"],
             "url": result["url"],
             "year": result["year"],
             "score": result["score"]
         }
         query = Query(query=self.query)
         query.save()
         for i in range(len(dictionary["author"])):
             author = list(dictionary["author"])[i].lstrip()
             title = list(dictionary["title"])[i].lstrip()
             url = list(dictionary["url"])[i].lstrip()
             year = list(dictionary["year"])[i]
             score = float(list(dictionary["score"])[i])
             details = Details(author=author, title=title, url=url, year=year, score=score, query_id=query.id)
             details.save()
         return dictionary
Exemple #9
0
def genmessages(booknumber=0, querynumber=10):
    """
    generates all messages for a book regarding a specific database query.
    
    :type booknumber: ``int``
    :param booknumber: the index of the book from the results list ("0" 
    would be the first book with the highest score)
    
    :type querynumber: ``int``
    :param querynumber: the index of a query from the predefined list of 
    test queries (named 'testqueries')
    
    :rtype: ``list`` of ``Message``s
    """
    books = Books(Results(Query(testqueries[querynumber])))
    am = AllMessages(AllPropositions(AllFacts(books)))

    for message in am.books[booknumber].messages.values():
        message.freeze()
        #freeze messages, so Rule()s can be tested against them
    return am.books[booknumber].messages.values()
Exemple #10
0
def handle_tobacco_search():
    """
    OPTION - Search Plans based on tobacco preference

    This option need "Age" information from user.
    Then it is able to find all plans based on user's tobacco preference
    """
    print("\n==============Tobacco User Friendly Insurance Plan==============")
    # age
    instruction = "\nWhat is the age of searching? (1-99):"
    values = list(str(i) for i in range(1, 100))
    age = wait_input(instruction, values)
    if age == -1:
        return

    # Wellness
    instruction = "\nDo you need tobacco wellness program? (yes/no):"
    values = ["yes", "no"]
    wellness = wait_input(instruction, values)
    if wellness == -1:
        return
    wellness_indicator = False
    if wellness == "yes":
        wellness_indicator = True

    # Print plans and select plan to get detail information
    results = Query.get_tobacco_insurance(wellness=wellness_indicator, age=age)
    headers = [
        "Plan ID", "Non Tobacco User Average Rate", "Tobacco User Average Rate"
    ]
    if results:
        instruction = "You can select a plan for detail information: "
        ind = display_in_pages(results, headers, instruction, showindex=True)
        if ind >= 0:
            plan_id = results[ind][0]
            search_plan_detail_information(plan_id)
    else:
        print("\nNo plans found.")
        input("\nPress any key to continue.")
Exemple #11
0
async def process_choose_new_deadline(message: Message, state: FSMContext):
    if match('\\d{2}.\\d{2}.\\d{4}', message.text) is None:
        await message.reply('Дата не соотвествует формату\n'
                            'Введите дату в формате ДД.ММ.ГГГГ')
        return

    await state.update_data(new_deadline=str(message.text))
    user_data = await state.get_data()
    query = Query(subject=user_data['subject'],
                  task=user_data['task'],
                  deadline='.'.join(reversed(user_data['new_deadline'].split('.'))))
    if user_data['type'] == QueryTypes.ADD:
        Database.add(query)
        await message.answer(f'Дедлайн {user_data["task"]} '
                             f'по предмету {user_data["subject"]} '
                             f'от {user_data["new_deadline"]} был добавлен')
    else:  # QueryTypes.UPD or DEL
        Database.update(query, user_data['deadline'])
        await message.answer(f'Дедлайн {user_data["task"]} '
                             f'по предмету {user_data["subject"]} '
                             f'был перенесён с {user_data["deadline"]} '
                             f'на {user_data["new_deadline"]}')

    await state.finish()
Exemple #12
0
def main():
    """
    This is the pypolibox commandline interface. It allows you to query
    the database and generate book recommendatins, which will either be
    handed to OpenCCG for generating sentences or printed to stdout in
    an XML format representing the text plans.
    """
    query = Query(sys.argv[1:])

    output_format = query.query_args.output_format
    valid_output_formats = ['openccg', 'hlds', 'textplan-xml', 'textplan-featstruct']
    if output_format not in valid_output_formats:
        sys.stderr.write("Output format must be one of: {}\n".format(valid_output_formats))
        sys.exit(1)

    try:
        lexicalize_messageblocks = \
            __import__("lexicalize_messageblocks_%s" % query.query_args.output_language, globals(), locals(), [], -1)
    except ImportError:
        raise

    try:
        lexicalization = \
            __import__("lexicalization_%s" % query.query_args.output_language, globals(), locals(), [], -1)
    except ImportError:
        raise

    lexicalize_message_block = lexicalize_messageblocks.lexicalize_message_block
    phrase2sentence = lexicalization.phrase2sentence


    textplans = generate_textplans(query)

    if output_format == 'openccg':
        openccg = initialize_openccg(lang=query.query_args.output_language)
        print "{} text plans will be generated.".format(len(textplans.document_plans))
        for i, textplan in enumerate(textplans.document_plans):
            print "Generating text plan #%i:\n" % i
            check_and_realize_textplan(openccg, textplan, lexicalize_message_block, phrase2sentence)
    elif output_format == 'hlds':
        from copy import deepcopy
        from hlds import (Diamond, Sentence, diamond2sentence,
            add_nom_prefixes, create_hlds_file)

        for i, textplan in enumerate(textplans.document_plans):
            print "Text plan #%i:\n" % i

            # TODO: refactor to avoid code duplication w/
            # check_and_realize_textplan()
            msg_blocks = linearize_textplan(textplan)
            for msg_block in msg_blocks:
                try:
                    lexicalized_msg_block = lexicalize_message_block(msg_block)
                    print "The {0} message block can be realized " \
                          "as follows:\n".format(msg_block[Feature("msgType")])
                    for lexicalized_phrase in lexicalized_msg_block:
                        lexicalized_sentence = phrase2sentence(lexicalized_phrase)

                        # TODO: refactor to avoid duplication w/ OpenCCG.realize
                        temp_sentence = deepcopy(lexicalized_sentence)

                        if isinstance(lexicalized_sentence, Diamond):
                            temp_sentence = diamond2sentence(temp_sentence)

                        add_nom_prefixes(temp_sentence)
                        print create_hlds_file(temp_sentence,
                            mode="realize", output="xml")

                except NotImplementedError, err:
                    print err
                    print "The message block contains these messages:\n", msg_block, \
                          "\n\n**********\n\n"
Exemple #13
0
def handle_find_avg_rate():
    """
    OPTION - Get Average Individual Rate for all available state.

    This option need receive "age" and "metal level" information from user.
    Then list the average individual rate for different state.
    """
    print("\n==============Average Individual Rate==============")

    # 1. Decide insurance type
    instruction = "\nWhich type of insurance do you want to query? (medical/dental): "
    values = ["medical", "dental"]
    insurance_type = wait_input(instruction, values)

    if insurance_type == -1:
        return

    # 2. Decide Metal Level
    instruction = "\nWhich metal level are you looking for:"
    if insurance_type == "medical":
        keys = list(Enum.m_metal_type.keys())
        utils.print_series(keys, "Metal Level", showindex=True)
    else:
        keys = list(Enum.d_metal_type.keys())
        utils.print_series(keys, "Metal Level", showindex=True)

    values = list(str(i) for i in range(len(keys)))
    value = wait_input(instruction, values)
    if value == -1:
        return
    metal_level_id = Enum.m_metal_type[keys[int(value)]] if insurance_type == "medical" \
        else Enum.d_metal_type[keys[int(value)]]

    # 3. Decide age for query
    instruction = "\nWhat is the age of searching? (1-99):"
    values = list(str(i) for i in range(1, 100))
    age = wait_input(instruction, values)

    if age == -1:
        return

    # 4. Get time intervals
    time_intervals = Query.get_time_intervals(metal_level_id=metal_level_id,
                                              age=age)
    utils.print_data_frame(time_intervals,
                           ["Effective Date", "Expiration Date"],
                           showindex=True)
    instruction = "\nPlease choose a time intervals:"
    values = list(str(i) for i in range(len(time_intervals)))
    index = wait_input(instruction, values)
    if index == -1:
        return
    index = int(index)
    effective_date = time_intervals[index][0]
    expiration_date = time_intervals[index][1]

    # 5. Query for results
    results = Query.get_avg_rate(metal_level_id=metal_level_id,
                                 age=age,
                                 effective_date=effective_date,
                                 expiration_date=expiration_date,
                                 insurance_type=insurance_type)
    utils.print_data_frame(results, ["State", "Individual Rate (average)"])

    input("\nPress any key to continue.")
Exemple #14
0
from database import Database, Query

db = Database()
query_object1 = Query()

print("test4 ok!")
Exemple #15
0
def search_plan_detail_information(plan_id):
    """
    Sub Menu - Looking for detail information of selected plan

    :param plan_id: plan ID
    """
    options = list()
    options.append((1, "Disease Programs"))
    options.append((2, "Plan Benefits"))
    options.append((3, "Plan Detail"))
    options.append((4, "Quit"))
    while True:
        print("\n==========Plan Information==========")
        utils.print_data_frame(options, ["Index", "Option"])
        instruction = "\nPlease select an option:"
        values = list(str(i) for i in range(1, 1 + len(options)))
        index = wait_input(instruction, values)
        if index == -1:
            return

        if index == '1':
            # Display disease programs the plan offered
            disease_str = Mongo.get_disease_programs(const.COL_MEDICAL_DISEASE,
                                                     plan_id)
            if disease_str is None:
                print("\nDisease Programs are not offered for this plan.")
            else:
                disease_list = disease_str.split(",")
                utils.print_series(disease_list, "Disease Program")

            input("\nPress any key to continue.")

        elif index == '2':
            # Display benefits the plan covered
            attr_db = [const.BENEFIT_NAME]
            attr_output = ["Benefit Name"]
            constrains = dict()
            constrains[const.PLAN_ID] = (const.EQUAL, plan_id)
            info = Query.plain_query(attr_db,
                                     const.TABLE_BENEFIT,
                                     constrains,
                                     order_by=const.BENEFIT_NAME)
            display_in_pages(info, attr_output)

        elif index == '3':
            # Display the general information of the plan
            attr_db = [
                const.PLAN_ID, const.PLAN_VAR_NAME, const.PLAN_STATE,
                const.PLAN_TYPE, const.QHP_TYPE, const.IS_NEW_PLAN,
                const.CHILD_ONLY, const.EFFECTIVE_DATE, const.EXPIRATION_DATE,
                const.URL_BROCHURE
            ]
            constrains = dict()
            constrains[const.PLAN_ID] = (const.EQUAL, plan_id)
            info = Query.plain_query_one(attr_db, const.TABLE_PLAN, constrains)
            plan_info = list()
            plan_info.append(("Plan ID", info[0]))
            plan_info.append(("Plan Name", info[1]))
            plan_info.append(("State", info[2]))
            plan_info.append(("Plan Type", Enum.plan_type_rev[info[3]]))
            plan_info.append(("QHP Type", Enum.qhp_type_rev[info[4]]))
            plan_info.append(("Is New Plan", ("No", "Yes")[info[5]]))
            plan_info.append(
                ("Child Option", Enum.child_only_type_rev[info[6]]))
            plan_info.append(("Effective Date", info[7]))
            plan_info.append(("Expiration Date", info[8]))
            plan_info.append(("URL", info[9]))
            utils.print_single_data(plan_info)
            input("\nPress any key to continue.")

        elif index == '4' or index == 'quit':
            return
        else:
            print("Invalid Index.")
Exemple #16
0
from database import Connect, Query

template_search_dir = os.getcwd()
output_file_dir = os.getcwd() + "/output/"
timestamp = datetime.utcnow().strftime('%s')

file_output_name = "importa_participante_" + timestamp
f = open(output_file_dir + file_output_name, 'a')

con = Connect(user='******',
              password='******',
              hostname='200.160.11.109',
              db='ptt')
cursor = con.mariadb().cursor()
q_cobranca = Query(['*'])
cursor.execute(q_cobranca.ptt_info_cobranca())
p_dict = dict()
participante_number = 0

template_env = Environment(loader=FileSystemLoader(template_search_dir))
c = template_env.get_template('template_insere_as')

for p in cursor.fetchall():
    c_participante = con.mariadb().cursor()
    c_participante.execute(q_cobranca.ptt_participante_ix(p[0]))
    ix_query_res = c_participante.fetchall()
    c_participante.close()
    if len(ix_query_res) > 0:
        ix_list = [ix_id[0] for ix_id in ix_query_res]
    else:
Exemple #17
0
def search_plan_add_filter_medical(constrains, detail_constrains):
    """
    Add a filter for medical plan

    :param constrains: current constains on <plans> table
    :param detail_constrains: detail constrains on <medical_plans> table
    """
    filters = list()
    filters.append((1, "State"))
    filters.append((2, "Plan Type"))
    filters.append((3, "QHP Type"))
    filters.append((4, "Child Option"))
    filters.append((5, "Metal level"))
    filters.append((6, "Notice for pregnancy Required"))
    filters.append((7, "Wellness Program Offered"))
    filters.append((8, "Quit"))

    utils.print_data_frame(filters, ["Index", "Filter"])
    instruction = "\nPlease select an filter:"
    values = list(str(i) for i in range(1, 1 + len(filters)))
    index = wait_input(instruction, values)
    if index == -1:
        return
    if index.strip() == "1":
        # Decide constrains for state
        state_list = Query.get_plan_state()
        utils.print_data_frame(state_list, ["State"])
        instruction = "\nPlease select a state: "
        values = list(value[0] for value in state_list)
        state = wait_input(instruction, values)
        if state == -1:
            return
        constrains[const.PLAN_STATE] = (const.EQUAL, state)

    elif index.strip() == "2":
        # Decide constrains for plan type
        keys = list(Enum.plan_type.keys())
        utils.print_series(keys, "Plan Type", showindex=True)
        instruction = "\nWhich type of plan do you want?: "
        values = list(str(i) for i in range(len(keys)))
        index = wait_input(instruction, values)
        if index == -1:
            return
        constrains[const.PLAN_TYPE] = (const.EQUAL,
                                       Enum.plan_type[keys[int(index)]])

    elif index.strip() == "3":
        # Decide constrains for QHP type
        keys = list(Enum.qhp_type.keys())
        utils.print_series(keys, "QHP Type", showindex=True)
        instruction = "\nWhich QHP type do you want?: "
        values = list(str(i) for i in range(len(keys)))
        index = wait_input(instruction, values)
        if index == -1:
            return
        constrains[const.QHP_TYPE] = (const.EQUAL,
                                      Enum.qhp_type[keys[int(index)]])

    elif index.strip() == "4":
        # Decide constrains for child option
        keys = list(Enum.child_only_type.keys())
        utils.print_series(keys, "Child Option", showindex=True)
        instruction = "\nWhich child option do you want?: "
        values = list(str(i) for i in range(len(keys)))
        index = wait_input(instruction, values)
        if index == -1:
            return
        constrains[const.CHILD_ONLY] = (const.EQUAL,
                                        Enum.child_only_type[keys[int(index)]])

    elif index.strip() == "5":
        # Decide constrains for metal level
        keys = list(Enum.m_metal_type.keys())
        utils.print_series(keys, "Metal Level", showindex=True)
        instruction = "\nWhich metal level do you want?: "
        values = list(str(i) for i in range(len(keys)))
        index = wait_input(instruction, values)
        if index == -1:
            return
        detail_constrains[const.M_METAL_LEVEL] = (
            const.EQUAL, Enum.m_metal_type[keys[int(index)]])

    elif index.strip() == "6":
        # Decide constrains for pregnancy notice
        instruction = "\nWhether notice required for pregnancy?(yes/no): "
        values = ["yes", "no"]
        value = wait_input(instruction, values)
        if value == -1:
            return
        detail_constrains[const.PREG_NOTICE] = (
            const.EQUAL, True) if value == "yes" else (const.EQUAL, False)

    elif index.strip() == "7":
        # Decide constrains for wellness program of plan
        instruction = "\nDo you want wellness program included?(yes/no): "
        values = ["yes", "no"]
        value = wait_input(instruction, values)
        if value == -1:
            return
        detail_constrains[const.WELLNESS_OFFER] = (
            const.EQUAL, True) if value == "yes" else (const.EQUAL, False)

    elif index.strip() == "8":
        print("Quit.")
        return
    else:
        print("Invalid Index.")
Exemple #18
0
def search_plan_add_filter_dental(constrains, detail_constrains):
    """
    Add a filter for medical plan for dental plan

    :param constrains: current constains on <plans> table
    :param detail_constrains: detail constrains on <dental_plans> table
    """
    filters = list()
    filters.append((1, "State"))
    filters.append((2, "Plan Type"))
    filters.append((3, "QHP Type"))
    filters.append((4, "Child Option"))
    filters.append((5, "Metal level"))
    filters.append((6, "Quit"))

    utils.print_data_frame(filters, ["Index", "Filter"])
    instruction = "\nPlease select an filter:"
    values = list(str(i) for i in range(1, 1 + len(filters)))
    index = wait_input(instruction, values)
    if index == -1:
        return

    if index.strip() == "1":
        # Decide constrains for state
        state_list = Query.get_plan_state()
        utils.print_data_frame(state_list, ["State"])
        instruction = "\nPlease select a state: "
        values = list(value[0] for value in state_list)
        state = wait_input(instruction, values)
        if state == -1:
            return
        constrains[const.PLAN_STATE] = (const.EQUAL, state)

    elif index.strip() == "2":
        # Decide constrains for plan type
        keys = list(Enum.plan_type.keys())
        utils.print_series(keys, "Plan Type", showindex=True)
        instruction = "\nWhich type of plan do you want?: "
        values = list(str(i) for i in range(len(keys)))
        index = wait_input(instruction, values)
        if index == -1:
            return
        constrains[const.PLAN_TYPE] = (const.EQUAL,
                                       Enum.plan_type[keys[int(index)]])

    elif index.strip() == "3":
        # Decide constrains for QHP type
        keys = list(Enum.qhp_type.keys())
        utils.print_series(keys, "QHP Type", showindex=True)
        instruction = "\nWhich QHP type do you want?: "
        values = list(str(i) for i in range(len(keys)))
        index = wait_input(instruction, values)
        if index == -1:
            return
        constrains[const.QHP_TYPE] = (const.EQUAL,
                                      Enum.qhp_type[keys[int(index)]])

    elif index.strip() == "4":
        # Decide constrains for child option
        keys = list(Enum.child_only_type.keys())
        utils.print_series(keys, "Child Option", showindex=True)
        instruction = "\nWhich child option do you want?: "
        values = list(str(i) for i in range(len(keys)))
        index = wait_input(instruction, values)
        if index == -1:
            return
        constrains[const.CHILD_ONLY] = (const.EQUAL,
                                        Enum.child_only_type[keys[int(index)]])

    elif index.strip() == "5":
        # Decide constrains for metal level
        keys = list(Enum.d_metal_type.keys())
        utils.print_series(keys, "Metal Level", showindex=True)
        instruction = "\nWhich metal level do you want?: "
        values = list(str(i) for i in range(len(keys)))
        index = wait_input(instruction, values)
        if index == -1:
            return
        detail_constrains[const.M_METAL_LEVEL] = (
            const.EQUAL, Enum.d_metal_type[keys[int(index)]])

    elif index.strip() == "6":
        print("Quit.")
        return
    else:
        print("Invalid Index.")
@author: cjayb
"""

from database import Query
from analysis_dict import Anadict

# from mne import find_events, write_events
# from mne.fiff import Raw, pick_channels

import numpy as np
import multiprocessing
import subprocess

proj_code = 'MINDLAB2013_01-MEG-AttentionEmotionVisualTracking'

db = Query(proj_code=proj_code,verbose=True)
ad = Anadict(db, verbose=False)    

fs_bin = '/opt/local/freesurfer-releases/5.3.0/bin'
subjects_dir = ad._scratch_folder + '/fs_subjects_dir'

# Arno Klein, Jason Tourville. Frontiers in Brain Imaging Methods. 
# 6:171. DOI: 10.3389/fnins.2012.00171 
template = 'aparc.DKTatlas40'

n_processes = 4


def _parallel_task(command):
    """
        General purpose method to submit Unix executable-based analyses (e.g.
Exemple #20
0
def handle_search_eye_plan():
    """
    OPTION - Search Plan that covers Eye related benefits

    This option need "Age" information from user.
    And the option is able to provide plan information based on "Group", "Metal Level" and "Eye Benefits"
    """
    print("\n==============Eye Insurance Plan==============")

    # 1. Decides eye insurance plan type
    instruction = "\nWhich type of insurance do you want to query? :"
    options = ["Eye Exam", "Eye Glasses"]
    utils.print_series(options, "Option", showindex=True)
    values = list(str(i) for i in range(len(options)))
    value = wait_input(instruction, values)
    if value == -1:
        return
    insurance_type = options[int(value)]

    # 2. Decides groups
    instruction = "\nWhat is the group of searching? (Adult/ Child):"
    options = ["Adult", "Child"]
    utils.print_series(options, "Option", showindex=True)
    values = list(str(i) for i in range(len(options)))
    value = wait_input(instruction, values)
    if value == -1:
        return
    group_type = options[int(value)]

    # 3. Decides age
    instruction = "\nWhat is the age of searching? (1-99):"
    values = list(str(i) for i in range(1, 100))
    age = wait_input(instruction, values)
    if age == -1:
        return

    # 3. Decide Metal Level
    instruction = "\nWhich metal level are you looking for:"
    keys = list(Enum.m_metal_type.keys())
    utils.print_series(keys, "Metal Level", showindex=True)
    values = list(str(i) for i in range(len(keys)))

    value = wait_input(instruction, values)
    if value == -1:
        return
    metal_level_id = Enum.m_metal_type[keys[int(value)]]

    # Query for the result
    results = Query.get_eye_insurance(insurance_type=insurance_type,
                                      group_type=group_type,
                                      age=age,
                                      metal_level_id=metal_level_id)
    headers = [
        "Plan ID", "Effective Date", "Expiration Date", "Benefit Name",
        "Estimated Average", "Quantity Limit", "Unit Limit"
    ]
    if results:
        instruction = "You can select a plan for detail information: "
        ind = display_in_pages(results, headers, instruction, showindex=True)
        if ind >= 0:
            plan_id = results[ind][0]
            search_plan_detail_information(plan_id)
    else:
        print("\nNo plans found.")
        input("\nPress any key to continue.")