Beispiel #1
0
def tweet(messageid=None):
    
    if id is None:
        return render_template(404)
    
    parz = Parsing()
    datum = parz.get_tweet(messageid)
    return render_template("message.html", datum=datum)
Beispiel #2
0
def tweeter(name=None):
    parz = Parsing()
    if name is None:
        data = parz.index_data()
        return render_template('tweetindex.html', data=data)
    else:
        data = parz.tweeter_data(name)

        return render_template('tweet.html', data=data)
Beispiel #3
0
 def __init__(self, id, nr):
     self.domain = Domain()
     self.phrasebase = Phrasebase()
     self.parsing = Parsing()
     self.evaluation = Evaluation(self.domain.getTopics(),
                                  self.domain.getPraise(),
                                  self.domain.getCriticism())
     super(L, self).__init__()
     self.ui = UI(nr)
     self.id = id
     L.totalCount += 1
     self.displayCount()
     self.running = True
Beispiel #4
0
def removeRareEntities(filePath):
    inFile = open(filePath, 'r')
    occurenceCountDict = {}
    p = Parsing()
    for line in inFile:
        if 'inv idx' in line:
            break
        elif ': ' in line and 'num preds' not in line and 'predicate' not in line and line != "":
            entities = p.extractEntities(line)
            if entities in occurenceCountDict:
                oldCount = occurenceCountDict[entities]
                newCount = oldCount + 1
                occurenceCountDict[entities] = newCount
            else:
                occurenceCountDict[entities] = 1
    rareEntitiesList = []
    for key, value in occurenceCountDict.items():
        if value < 3:
            rareEntitiesList.append(key)

    orig_stdout = sys.stdout
    f = open('GermanLoc#LocNoRareEntities.txt', 'w')
    sys.stdout = f

    inFile2 = open(filePath, 'r')
    for line in inFile2:
        if 'inv idx' in line:
            break
        elif ': ' in line and 'num preds' not in line and 'predicate' not in line and line != "":
            entities = p.extractEntities(line)
            if entities in rareEntitiesList:
                continue
            else:
                print(line.rstrip())
        else:
            print(line.rstrip())
    sys.stdout = orig_stdout
    f.close()
Beispiel #5
0
	group1 = parser.add_mutually_exclusive_group()
	group1.add_argument('-l', '--length', default='3', type=int, help='Choose the size of your puzzle between 3 and 70')
	group1.add_argument('-f', '--file', type=str, help='Name of your file, if this option is selected, ignore: -s/u')
	group2 = parser.add_mutually_exclusive_group()
	group2.add_argument('-s', '--solvable', action='store_true', help='Generate only solvable puzzle')
	group2.add_argument('-u', '--unsolvable', action='store_false', help='Generate only unsolvable puzzle')
	parser.add_argument('-a', '--anim', action='store_true' , help='Launch an animation of the resolution of the puzzle')
	return parser.parse_args(arg)

if __name__ == '__main__':
	arg = parse_argument(sys.argv[1:])

	if (arg.file):
		try:
			fd = open(arg.file, "r")
			parsing = Parsing(fd)
		except:
			sys.exit("Error - Openning error")
		start = parsing.puzzle
		goal = printspiral(spiral(int(sqrt(len(start)))))
		if (my_resolvable(parsing, start, goal) == 1):
			exit

	else:
		if arg.length < 71 and arg.length > 2:
			goal = printspiral(spiral(arg.length))
			solvable = None
			if (arg.solvable == True):
				solvable = True
			elif (arg.unsolvable == False):
				solvable = False
Beispiel #6
0
def main():
    try:
        if len(argv) < 3:
            print('''Options:\nparse_messages [group name]
				\rparse_participants [group name]\nget_statistics [group name | date from | date until]'''
                  )
            return 1
        parse = Parsing(argv[2])
        if argv[1] == "parse_messages":
            if len(argv) == 3:
                mod = 0
            elif len(argv) == 4:
                mod = int(argv[3])
            elif len(argv) == 5:
                mod = list()
                mod.append(datetime.strptime(argv[3], '%Y-%m-%d'))
                mod.append(datetime.strptime(argv[4], '%Y-%m-%d'))
            else:
                return 1
            parse.parse_messages(mod)
        elif argv[1] == "parse_participants":
            parse.parse_participants()
        elif argv[1] == "get_statistics":
            if len(argv) < 5:
                print('Invalid argument')
                return 1
            datum_range = parse.get_datum_range(argv[3], argv[4])
            if datum_range:
                print(
                    "There are %i messages during this period.\nDo you want to proceed?[y/n]"
                    % datum_range[0])
            else:
                print("There are no messages during this period.")
                return
            if 'y' in input():
                parse.get_message_range(argv[3], argv[4], datum_range[1])
                print('Done')
        parse.finish()
        return 0
    except KeyboardInterrupt:
        print('Terminating...', end='\r')
        parse.finish()
        print('Terminated...')
        return 0
    except:
        print("Invalid argument")
        return 0
from pprint import pprint

from graph import Graph
from parsing import get_file, Parsing, Table

if __name__ == '__main__':
    code = get_file('cont.go')
    lexemes = Parsing().parsing_lexeme(code)
    table_lexemes = Table().get_table()
    # pprint(table_lexemes)
    graph = Graph(table_lexemes[2:])
    graph.stmt()
    print(graph.get_variable_table())
    #graph = graph.get_abstract_syntax_trees()
    # pprint(graph)
    # RecursiveDescent(graph).output()
Beispiel #8
0
def main():
    "Using argparse to get events or search meetup"
    parser = argparse.ArgumentParser(description='TGmeetup')
    parser.add_argument(
        '-u',
        '--update',
        help='Update the events.json infomation.',
        action="store_true")
    parser.add_argument(
        '-c',
        '--country',
        type=str,
        help='This is a country code which follow ISO 3166-1 alpha-2.')
    parser.add_argument('-t', '--city', type=str, help='This is a city name.')
    parser.add_argument(
        '-n',
        '--name',
        type=str,
        help='This is a community short name.')
    parser.add_argument(
        '-k',
        '--keyword',
        type=str,
        help='This is a keyword of community. \
              This could help find the related community.')
    args = parser.parse_args()
    parsing = Parsing()
    if args.city is not None or args.keyword is not None or args.name is not None:
        if args.name is not None and args.city is None and args.keyword is None:
            # Show the group info (default country = Taiwan)
            result = parsing.show_organization_info(args.name, args.country)
            print(
                "The information of \"" +
                result["title"] +
                "\" in " +
                result["city"] +
                " (" +
                result["countrycode"] +
                ")")
            print(json.dumps(result, indent=2, sort_keys=False))
        elif args.city is not None and args.name is None and args.keyword is None:
            # List all the meetup in the city (default country = Taiwan)
            result = parsing.get_meetup_via_city(args.city, args.country)
            print_result(result)
        elif args.keyword is not None and args.city is None and args.name is None:
            # List all the meetup related to this keyword (default country =
            # Taiwan)
            result = parsing.show_meetup_via_keyword(
                args.keyword, args.country)
            print_result(result)
        else:
            print(
                "Please just use one option, such as name,keyword or city, \
                 and country option.")
            print("eg.")
            print("tgmeetup -k keypord\n tgmeetup -n name\ntgmetup -t Hsinchu")
    else:
        if args.update:
            update()
            print("Update all the meetup infomation.")
        else:
            # List all group with event in the country(default country =
            # Taiwan).
            result = parsing.list_all_group_in_country(args.country)
            print_result(result)
class AnalisadorSemantico:
    '''
    Clase principal encargada de llevar a cabo el parsing y ademas analizar la semantica de la declaraciones de 
    funciones, varibales, condicionales, entre otras.
    '''
    def __init__(self, nombre_archivo):
        self._parsing = Parsing()
        self._lista_tokens = []
        self.lista_errores = []
        self._tokenize(nombre_archivo)

    def _tokenize(self, _nombre_archivo):
        archivo = open(_nombre_archivo, 'r')
        contador_linea = 1
        for linea in archivo.readlines():
            tokens = tokenize(linea)
            self._lista_tokens.append({
                'linea': contador_linea,
                'tokens': tokens
            })
            contador_linea += 1

    def analizar(self):
        self.parse()
        tabla = self._parsing.obtenerTabla()
        self._analisis_semantico_declaraciones(tabla)
        self._analisis_semantico_identificadores(tabla)
        self._mostrar_errores()

    def parse(self):
        for i in self._lista_tokens:
            linea = i['linea']
            tokens = i['tokens']
            error = self._parsing.parse(tokens, linea)
            if (error != ""):
                self.lista_errores.append(error)

    def analisis_semantico_declaraciones(self, tabla):
        self._analisis_semantico_declaraciones(tabla)

    def _analisis_semantico_identificadores(self, tabla):
        '''
        Verifica que las variables se encuentren declaradas y su ambito sea el correspondiente
        '''
        interes = {'int', 'string', 'float', 'identificador'}
        for tokens in self._lista_tokens:
            if (tokens['tokens']):
                resultado = self._analizador_elementos(tokens['tokens'])

                if resultado == 'ASIGNACION':
                    llave = tabla.buscar_simbolo(
                        tokens['tokens'][0][0]
                    )  #verifica que la variable que esta a la izquierda del
                    #operador de asignacion este en la tabla
                    if llave:
                        lista_asignaciones = self._extraer_asignaciones(
                            tokens['tokens'])
                        for asignacion in lista_asignaciones:
                            if asignacion[1] == 'identificador':
                                valor = tabla.buscar_simbolo(
                                    asignacion[0]
                                )  #se verifica que la variable que va a ser asignada este en la tabla
                                if valor:
                                    if not valor['tipo'] == llave[
                                            'tipo']:  #si la variable esta en la tabla se verifica que sea del mismo tipo
                                        salida = "Error - linea: {}. Asignacion de tipo '{}' incorrecta.".format(
                                            tokens['linea'], valor['tipo'])
                                        self.lista_errores.append(salida)
                            else:  #si no es una variable es un tipo dato primitivo
                                tipo_valor = self._tipo_dato_checker(
                                    llave['tipo'], asignacion[0])
                                if not tipo_valor:
                                    salida = "Error - linea: {}. Asignacion de tipo '{}' incorrecta.".format(
                                        tokens['linea'], llave['tipo'])
                                    self.lista_errores.append(salida)
                    else:
                        salida = "Error - linea: {}. '{}' no esta declarado.".format(
                            tokens['linea'], tokens['tokens'][0][0])
                        self.lista_errores.append(salida)

                elif resultado == 'CONDICIONAL':
                    lista_asignaciones = self._extraer_asignaciones(
                        tokens['tokens'])
                    if len(lista_asignaciones
                           ) > 1:  #caso en que hayan dos elementos comparados
                        if lista_asignaciones[0][
                                1] == 'identificador' and lista_asignaciones[1][
                                    1] == 'identificador':  #caso de que ambos elementos sean variables
                            elemento1 = tabla.buscar_simbolo(
                                lista_asignaciones[0][0])
                            elemento2 = tabla.buscar_simbolo(
                                lista_asignaciones[1][0])
                            if not elemento1 or not elemento2:
                                if not elemento1:
                                    salida = "Error - linea: {}. '{}' no esta declarado.".format(
                                        tokens['linea'],
                                        lista_asignaciones[0][0])
                                    self.lista_errores.append(salida)
                                else:
                                    salida = "Error - linea: {}. '{}' no esta declarado.".format(
                                        tokens['linea'],
                                        lista_asignaciones[1][0])
                                    self.lista_errores.append(salida)
                        elif lista_asignaciones[0][
                                1] == 'identificador' or lista_asignaciones[1][
                                    1] == 'identificador':  #caso de que solo haya una variable y el otro sea algun tipo de dato primitivo
                            elemento1 = lista_asignaciones[0]
                            elemento2 = lista_asignaciones[1]
                            if elemento1[1] == 'identificador':
                                encontrado = tabla.buscar_simbolo(elemento1[0])
                                if encontrado:
                                    if not elemento2[1] == encontrado['tipo']:
                                        salida = "Error - linea: {}. Comparacion de tipo '{}' incorrecta.".format(
                                            tokens['linea'],
                                            encontrado['tipo'])
                                        self.lista_errores.append(salida)
                                else:
                                    salida = "Error - linea: {}. '{}' no esta declarado.".format(
                                        tokens['linea'], elemento1[0])
                                    self.lista_errores.append(salida)
                            else:
                                encontrado = tabla.buscar_simbolo(elemento2[0])
                                if encontrado:
                                    if not elemento1[1] == encontrado['tipo']:
                                        salida = "Error - linea: {}. Comparacion de tipo '{}' incorrecta.".format(
                                            tokens['linea'],
                                            encontrado['tipo'])
                                        self.lista_errores.append(salida)
                                else:
                                    salida = "Error - linea: {}. '{}' no esta declarado.".format(
                                        tokens['linea'], elemento2[0])
                                    self.lista_errores.append(salida)
                        else:
                            elemento1 = lista_asignaciones[0]
                            elemento2 = lista_asignaciones[1]
                            if not elemento1[1] == elemento2[
                                    2]:  #caso de que los datos primitivos no sean del mismo tipo
                                salida = "Error - linea: {}. Comparacion de tipo '{}' incorrecta.".format(
                                    tokens['linea'], elemento1[1])
                                self.lista_errores.append(salida)
                    else:  #en caso de que el condicional solo tenga un elemento dentro
                        if lista_asignaciones[0][
                                1] == 'identificador':  #caso de que ambos elementos sean variables
                            elemento1 = tabla.buscar_simbolo(
                                lista_asignaciones[0][0])
                            if not elemento1:
                                salida = "Error - linea: {}. '{}' no esta declarado.".format(
                                    tokens['linea'], lista_asignaciones[0][0])
                                self.lista_errores.append(salida)

                elif resultado == 'ASIGNACION_FUNCION':
                    tipos = {'string', 'int', 'float', 'void'}
                    parametros = []
                    if tokens['tokens'][0][0] in tipos:
                        parametros = self._extraer_parametros(tokens['tokens'])

                        for parametro in parametros:
                            if not parametro in tabla.obtener_tabla().keys():
                                salida = "Error - linea: {}. '{}' no esta declarado.".format(
                                    tokens['linea'], parametro)
                                self.lista_errores.append(salida)
                            else:
                                if tabla.obtener_tabla(
                                )[parametro]['ambito'] != 'global':
                                    salida = "Error - linea: {}. '{}' no esta declarado.".format(
                                        tokens['linea'], parametro)
                                    self.lista_errores.append(salida)

    def _extraer_parametros(self, linea):
        '''
        Utilizado para extraer los parametros que se encuentran entre parentesis en una funcion
        '''
        lista_parametros = []  #se guardan los parametros de la linea de tokens
        parametro_auxiliar = []
        contador_parentesis = 0

        for i in range(0, len(linea) + 1):  #recorre la linea de tokens
            if linea[i][1] == 'parentesis':
                if contador_parentesis < 1:
                    contador_parentesis += 1
                else:  #si el token vuelve a ser un parentesis significa que es el parentesis que cierra
                    lista_parametros += parametro_auxiliar  #lo que este en parametro_auxiliar se agrega a la lista de parametros
                    break
            elif contador_parentesis > 0:
                if linea[i][
                        1] == 'coma':  #si el token es una coma todo lo que este en el parametro_auxiliar se agrega a la lista de parametros
                    if len(parametro_auxiliar) > 0:
                        lista_parametros.append(parametro_auxiliar)
                        parametro_auxiliar = []
                elif linea[i][
                        1] != 'coma':  #si el token actual no es una coma, es parte del parametro (tipo, identificador, =, valor)
                    parametro_auxiliar.append(
                        linea[i][0])  #se agrega al parameto_auxiliar
        return lista_parametros

    def _extraer_asignaciones(self, linea_token):
        interes = {'identificador', 'int', 'string', 'float'}
        lista_asignaciones = []
        for i in range(0, len(linea_token)):
            if linea_token[i][1] in interes:
                lista_asignaciones.append(linea_token[i])

        return lista_asignaciones

    def _analizador_elementos(self, tokens):
        operador_asignacion = False
        condicional = False
        parentesis_abre = False
        parentesis_cierra = False
        palabra_tipo = False

        for token in tokens:
            if token[1] == 'tipo':
                palabra_tipo = True
            if token[1] == 'asignacion':
                operador_asignacion = True
            if token[1] == 'parentesis':
                if token[0] == '(':
                    parentesis_abre = True
                else:
                    parentesis_cierra = True
            if token[1] == 'condicicional':
                condicional = True

        if condicional and parentesis_abre:
            return 'CONDICIONAL'
        elif operador_asignacion and parentesis_abre:
            return 'ASIGNACION_FUNCION'
        elif operador_asignacion and not palabra_tipo:
            return 'ASIGNACION'
        else:
            return 'NONE'

    def _analisis_semantico_declaraciones(self, tabla):
        '''
        Verifica que las asignaciones sean del mismo tipo en las declaraciones
        '''

        errores = queue.Queue()

        for key, value in tabla.obtener_tabla().items():
            tipo = value['tipo']
            valor = value['valor']
            if valor:
                if self._tipo_dato_checker(tipo, valor):
                    continue
                else:
                    if valor in tabla.obtener_tabla():
                        elemento_tabla = tabla.obtener_tabla()[valor]
                        if tipo == elemento_tabla['tipo']:
                            continue
                        else:
                            errores.put(value)
                    else:
                        errores.put(value)
        if not errores.empty():
            while not errores.empty():
                value = errores.get()
                salida = "Error - linea: {}. Asignacion de tipo '{}' incorrecta.".format(
                    value['linea'], value['tipo'])
                self.lista_errores.append(salida)

    def _obtener_tabla(self):
        return self._parsing.obtenerTabla()

    def _tipo_dato_checker(self, tipo, valor):
        if tipo == 'int':
            return self._verifica_int(valor)
        elif tipo == 'float':
            return self._verifica_float(valor)
        elif tipo == 'string':
            return self._verifica_string(valor)

    def _verifica_int(self, int):
        return int.isdigit()

    def _verifica_float(self, entrada):
        try:
            float(entrada)
            return True
        except ValueError:
            return False

    def _verifica_string(self, entrada):
        token = re.compile(r'"[a-zA-Z0-9_]*"')
        objeto_encontrado = token.match(entrada)
        if objeto_encontrado:
            return True
        return False

    def _mostrar_errores(self):
        print()
        if len(self.lista_errores) > 0:
            for error in self.lista_errores:
                print(error)
        else:
            print("El programa se encuentra libre de errores!")
        print()
 def __init__(self, nombre_archivo):
     self._parsing = Parsing()
     self._lista_tokens = []
     self.lista_errores = []
     self._tokenize(nombre_archivo)
Beispiel #11
0
from parsing import Parsing
from dominant import Dominant
from darsi import Darsi
from rollershop import Rollershop
from wakepark import Wakepark
import urllib.request
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
import time
import keyboard
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
parsing = Parsing()
sys.setrecursionlimit(100000)

shops = {
    'Dominant': Dominant(),
    'FAMILY BOARDSHOP': Wakepark(),
    'Rollershop': Rollershop(),
    'Darsi': Darsi(),
}

# # get main_page
# for name in shops.keys():
#     print(name)
# page_doc = parsing.get_page_doc(shops[name])
#     print(page_doc)
Beispiel #12
0
            nodeList = labelDict[i[1]['label']]
            nodeList.append(i[0])
            labelDict[i[1]['label']] = nodeList

    for i, j in labelDict.items():
        print(i, j)

    #max_key, max_value = max(d.items(), key = lambda x: len(set(x[1])))
    #print(max_key,max_value)


if __name__ == "__main__":
    print("Hello Graph Aligner")

    #extract the German only entity set
    c = Parsing()
    entitySet = EntitySet()
    vectorMap = VectorMap()
    discardThisVectorMap, germanEntitySet = c.parse(
        "GermanLoc#LocNoRareEntities.txt", entitySet, vectorMap)

    #extract the English only entity set
    freshVectorMap = VectorMap()
    freshEntitySet = EntitySet()
    discardThisVectorMap, englishEntitySet = c.parse(
        "/afs/inf.ed.ac.uk/user/s17/s1782911/location#location.txt",
        freshEntitySet, freshVectorMap)

    #calculate the intersection of those sets. This is the overlap of entities
    intersection = list(englishEntitySet.intersection(germanEntitySet.toSet()))
    print("the overlap between the tow sets is ", len(intersection))
Beispiel #13
0
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from ambiguity import Ambiguity
from constraints import Constraints
from language_generation import LanguageGeneration
from parsing import Parsing
from ranges import Ranges
from resolution import Resolution

if __name__ == "__main__":
    # Creating TIMEX expressions from natural language using the Recognizer package.
    Ambiguity.date_ambiguity()
    Ambiguity.time_ambiguity()
    Ambiguity.date_time_ambiguity()
    Ranges.date_range()
    Ranges.time_range()

    # Manipulating TIMEX expressions in code using the TIMEX Datatype package.
    Parsing.examples()
    LanguageGeneration.examples()
    Resolution.examples()
    Constraints.examples()
Beispiel #14
0
import os

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
from telegram import Bot, Update
from telegram.utils.request import Request
from logging import getLogger

from bot_token import bot_token
from debug_for_bot import debug_requests, load_config
from keyboards_for_bot import available_shops_keyboard, available_categories_keyboard, back_button_logic
from some_data import shops, User
from parsing import Parsing

config = load_config(getLogger(__name__))
users = dict()
parsing = Parsing()


@debug_requests
def do_start(update: Update, context=CallbackContext):
    chat_id = update.message.chat_id
    if chat_id not in users.keys():
        users[chat_id] = User(chat_id)
        update.effective_chat.send_message(
            text='Select shop', reply_markup=available_shops_keyboard())
    else:
        users[chat_id].selected_shop = None
        users[chat_id].categories = None
        users[chat_id].selected_category = None
        update.effective_chat.send_message(
            text='Select shop', reply_markup=available_shops_keyboard())
Beispiel #15
0
class L(threading.Thread):
    totalCount = 0

    #Initialize all the components#
    def __init__(self, id, nr):
        self.domain = Domain()
        self.phrasebase = Phrasebase()
        self.parsing = Parsing()
        self.evaluation = Evaluation(self.domain.getTopics(),
                                     self.domain.getPraise(),
                                     self.domain.getCriticism())
        super(L, self).__init__()
        self.ui = UI(nr)
        self.id = id
        L.totalCount += 1
        self.displayCount()
        self.running = True

    def getUI(self):
        return self.ui

    #main method, organize the whole structure of the dialogue#
    def run(self):

        #setup
        self.parsing.setui(self.ui)
        warnings.filterwarnings(module='sklearn*',
                                action='ignore',
                                category=DeprecationWarning)

        #introductory greeting of the user, general explanations and so on
        self.intro()

        #getting stories to ask
        total_number = 6
        stories = self.organizeStories(total_number)

        #main loop for asking all stories
        for story in stories:
            self.askStory(story)

        #get the evaluation and tell it to the user
        eval = self.evaluation.evaluate()
        for e in eval:
            self.ui.tell(e)

        #say goodbye
        self.goodbye()

    #just for keeping track of how many lizas there are
    def displayCount(self):
        print(
            "I am the %d. Liza started here since the last restart of the program."
            % L.totalCount)

    #display a final goodbye message, and then a "system message" stating the liza has disconnected.
    def goodbye(self):
        self.ui.tell("Goodbye!")
        self.ui.info("Liza has disconnected.")
        sys.exit()

    #For asking if the user wants to take a break
    def askbreak(self):
        self.ui.tell("Do you want to continue with this?")
        answer = self.ui.listen()
        if (answer == ""):
            self.ui.tell(
                "Do you want to continue? If you don't reply, I have to assume that you are gone..."
            )
            answer = self.ui.listen()
            if (answer == ""):
                self.ui.tell("Well, okay... I guess we can't continue then.")
                self.goodbye()
        meaning = self.parsing.parse(answer)
        if meaning == "yes":
            self.ui.tell("Okay, great! So let's return to the questions.")
            return True
        self.ui.tell("Oh. I am sorry.")
        self.goodbye()

    #for asking a question and continuing until we finally got an answer
    def askForever(self, question):
        answer = ""
        time = 0
        self.ui.tell(question)
        self.ui.prompt()
        while True:
            time = time + 1
            answer = self.ui.listen()
            if answer == "" and time < 4:
                self.ui.tell(self.phrasebase.getReply("waiting"))
                self.ui.prompt()
            if answer == "" and time >= 4 and time < 7:
                self.ui.tell(self.phrasebase.getReply("worried_waiting"))
                self.ui.prompt()
            if time >= 7 and time < 10:
                continue
            if time >= 10:
                self.ui.tell(
                    "It seems that you are a bit distracted right now. Or maybe dead. ... ...I hope you are not dead. But because it's been a while since your last answer..."
                )
                self.ui.prompt()
                self.askbreak()
                time = 0
                self.ui.tell("So my question was: " + question)

            if answer != "":
                return answer

    def askStory(self, story):
        #if story type is already explained, go on
        #otherwise, explain
        if not self.domain.getExplained(story.group):
            self.ui.tell(self.phrasebase.getReply("new_topic"))
            self.ui.tell(self.domain.groups[story.group])
            answer = self.askForever(
                self.phrasebase.getReply("want_topic_explanation"))
            meaning = self.parsing.parse(answer)
            if meaning == "yes":
                self.ui.tell(self.domain.getExplanation(story.group))
                self.domain.setExplained(story.group)
                self.ui.tell("Now let's get to the question!")
            if meaning == "no":
                self.ui.tell("Ok, then let's get right to the question.")
            else:
                self.ui.tell("Oh, I really like to explain things.")
                self.ui.tell(self.domain.getExplanation(story.group))
                self.domain.setExplained(story.group)
                self.ui.tell("Now let's get to the question!")

        if (len(story.intro) > 0):
            answer = self.askForever(story.intro)
            meaning = self.parsing.parse(answer)
            if "yes" in meaning:
                self.ui.tell(story.introyes)
            elif "no" in meaning:
                self.ui.tell(story.introno)
            else:
                self.ui.tell(self.phrasebase.getReply("meaninglesses"))

        self.ui.tell(story.text)
        self.ui.tell(story.question)
        answer = self.ui.listenLong()

        if answer == "" or answer == None:
            print("seems like they don't know the answer...")
            self.ui.tell(self.phrasebase.getReply("offer_hint"))
            self.ui.prompt()
            answer = self.ui.listen()
            meaning = self.parsing.parse(answer)
            #print(answer)
            #print(meaning)
            if meaning == "yes":
                self.ui.tell(story.hint)
                self.ui.prompt()
            if meaning == "no":
                self.ui.tell("ok!")

            meaning = self.parsing.parse(answer)
            if not meaning == "correct" or meaning == "incorrect":
                answer = self.askForever(
                    self.phrasebase.getReply("introbla") + story.question)
                #print(answer)

        meaning = self.parsing.parseQuiz(answer, story)
        #print(meaning)

        if meaning == "whatquestion":
            self.ui.tell("The question was: " + story.question)

    #  if meaning == "hint":
    #    self.ui.tell(story.hint)
    #    answer = askForever(self.phrasebase.getReply("introbla") + story.question)

        if meaning == "explain":
            self.ui.tell(self.phrasebase.getReply("offer_explanation"))
            self.ui.prompt()
            answer = self.ui.listen()
            meaning = self.parsing.parse(answer)
            if meaning == "yes":
                self.ui.tell(story.explain)
                #explained the answer
                #student model: didn't know the answer
                return

            if meaning == "no":
                self.ui.tell("ok!")
            answer = self.askForever(
                self.phrasebase.getReply("introbla") + story.question)
            meaning = self.parsing.parse(answer)

        if meaning == "correct":
            if (randint(0, 1) > 0):
                self.askCalibration(True)
            self.ui.tell(
                story.answercorrect
            )  #you could also use self.phrasebase.getReply("correct")
            self.evaluation.answer(story, True)

            #student model: knew the answer

        elif meaning == "incorrect":
            if (randint(0, 1) > 0):
                self.askCalibration(False)

            self.evaluation.answer(story, False)
            self.ui.tell(
                story.answerincorrect
            )  #you could also use self.phrasebase.getReply("incorrect")
            self.ui.tell(self.phrasebase.getReply("offer_explanation"))
            self.ui.prompt()
            answer = self.ui.listen()
            meaning = self.parsing.parse(answer)
            if meaning == "yes":
                self.ui.tell(story.explain)

            return

    def askCalibration(self, correctness):
        self.ui.tell(self.phrasebase.getReply("howsure"))
        answer = self.ui.listen()
        percent = self.parsing.parsePercent(answer)
        self.evaluation.calibrate(correctness, percent)

    def organizeStories(self, total):
        storylist = []
        topic = 0
        for i in range(0, total):
            topic = topic % len(self.domain.getTopics())
            story = self.domain.getStory(topic)
            storylist.append(story)
            topic = topic + 1
        return storylist

    def intro(self):
        #the bot introduces itself
        answer = self.askForever(self.phrasebase.getReply("greetings"))
        meaning = self.parsing.parse(answer)
        #print(meaning)
        if "greet" in meaning or "yes" in meaning:
            self.ui.tell("Nice to meet you!")
        answer = self.askForever("You are a human, aren't you?")
        meaning = self.parsing.parse(answer)
        if meaning == "yes":
            self.ui.tell("Great! This means you can help me.")
        if meaning == "no":
            answer = self.askForever(
                "Are you sure? What is the sum of two and three?")
            meaning = self.parsing.parse(answer)
            if meaning == "five":
                self.ui.tell(
                    "See, you solved the captcha. You are sufficiently human for my purposes."
                )
            else:
                self.ui.tell("Very funny. You are definitely human.")

        self.ui.tell(
            "My programmers want me to teach you how to be rational, make good decisions and judge situations correctly."
        )
        answer = self.askForever("Do you want to be more rational?")

        meaning = self.parsing.parse(answer)

        if meaning == "yes":
            self.ui.tell("Yeah, that's the spirit!")

        if meaning == "no":
            answer = self.askForever(
                "Why would you think that? Rationality is just the ability to make good decisions. Do you want to be able to make good decisions?"
            )
            meaning = self.parsing.parse(answer)
            if meaning == "no":
                self.askbreak()

        self.ui.tell(
            "I will just try to ask you some questions, and try to explain to you what you could do better. If I do a bad job at explaning, just ask me, ok? I never taught humans before."
        )
        self.ui.tell(
            "So, let's see... the first thing I want you to know is that you don't have to be extremely intelligent to be rational. There are very intelligent people who do things that are not at all reasonable. The key to rational decisions is to know when not to follow your gut feelings, but to stop and actually think about the problem."
        )
        answer = self.askForever(
            "To get used to the whole situation - how about I ask you a test question? Just to make sure I am doing this teaching thing right. "
        )
        meaning = self.parsing.parse(answer)
        if meaning == "yes":
            self.ui.tell("Okay, thank you!")
        if meaning == "no":
            self.ui.tell("I would nevertheless like to ask the test question.")

        answer = self.askForever(
            "This is my first question: Do people need to follow their gut feelings to make rational decisions?"
        )
        meaning = self.parsing.parse(answer)
        if meaning == "no":
            self.ui.tell(
                "Amazing! I mean, it was easy, I know, but you did it. Very reasonable of you to say this! Now we can start with the actual teaching."
            )

        if meaning == "yes":
            self.ui.tell(
                "Uhm... no. This is a bit awkward. Following you gut feelings means not to think about something, but just go with what feels right. A lot of psychologists have shown that people tend to make a lot of mistakes when they make decisions that way."
            )
            answer = self.askForever("Do you still want to continue?")
            meaning = self.parsing.parse(answer)
            if meaning == "yes":
                self.ui.tell("Okay! Let's start with the actual teaching!")
            else:
                self.askbreak()