Пример #1
0
def get_answer(question):
    """
    :param question: String with the question.
    :return: Filled Answer object.
    """
    a = Answer(Question(question))

    checked = check_keywords(a.q)
    if not checked:
        a.text = 'Didn\'t understand the question'
        return a

    # print warning on weird keywords
    # (XXX: should we give up on these questions instead?)
    check_unknowns(a)
    if len(a.q.unknown) > 0:
        print 'we have no information on these words:', a.q.unknown

    found_sources, found_anything = get_content_elastic(a, search_all=False)

    if found_sources:
        gen_features(a)
        a.text = answer_all(a)
        return a

    if not found_anything:
        a.text = 'Absolutely no result'
    else:
        a.text = 'No result'
    return a
Пример #2
0
    def operate(self, topic):
        self.topic_detail(topic)

        while True:
            op = raw_input("Topic$ ")
            if op == "answer":
                answer = Answer()
                answer_list, replies = self.answer(topic)
                answer.operate(answer_list, replies)
            elif op == "author":
                user = self.author_info(topic)
                user.operate(user)
            elif op == "thx":
                print termcolor.colored(u"暂不支持!", "red")
            elif op == "ignore":
                print termcolor.colored(u"暂不支持!", "red")
            elif op == "collect":
                self.collect(topic)
            elif op == "help":
                self.help()
            elif op == "back":
                break
            elif op == "clear":
                clear()
            else:
                self.error()
Пример #3
0
def crossover(crossover_answers: List[Answer], count: int, individuals: List[Individual]) -> List[Answer]:
    selected_old_answers = roulette_wheel(crossover_answers, count)

    crossover_point1: int = int(len(crossover_answers[0].chromosome) / 3)
    crossover_point2: int = int(crossover_point1 * 2)

    new_answers: List[Answer] = []
    for index in range(0, len(selected_old_answers), 2):
        temp_chromosome1 = \
            selected_old_answers[index].chromosome[:crossover_point1] + \
            selected_old_answers[index + 1].chromosome[crossover_point1:crossover_point2] + \
            selected_old_answers[index].chromosome[crossover_point2:]

        temp_chromosome1 = mutation(temp_chromosome1)

        total_value, total_weight = calculate_answer_weight_value(individuals, temp_chromosome1)

        if total_weight <= knapsack_capacity:
            new_answers.append(Answer(temp_chromosome1, total_weight, total_value))

        temp_chromosome2 = \
            selected_old_answers[index + 1].chromosome[:crossover_point1] + \
            selected_old_answers[index].chromosome[crossover_point1:crossover_point2] + \
            selected_old_answers[index + 1].chromosome[crossover_point2:]

        temp_chromosome2 = mutation(temp_chromosome2)

        total_value, total_weight = calculate_answer_weight_value(individuals, temp_chromosome2)

        if total_weight <= knapsack_capacity:
            new_answers.append(Answer(temp_chromosome2, total_weight, total_value))

    selected_new_answers = roulette_wheel(selected_old_answers + new_answers, count)

    return selected_new_answers
Пример #4
0
def question(request, question_id):
    if request.GET.get('preview_key'):
        return preview_with_key(request, question_id)
    user_data = UserData(request.session)
    q = get_object_or_404(Question, Q(id=question_id), Q(state='PUB') | Q(state='RET'))
    q.mark_viewed()
    d = {}
    d['answered'] = False
    d['question'] = q
    d['dismissed_training_msg'] = user_data.dismissed_training_msg
    if request.GET.get('did_answer'):
        d['answered'] = True
        answer = Answer(q, request)
        answer.register_given_answer()
        user_data.register_attempt(answer)
        if answer.correct:
            d['correct_result'] = True
            user_data.register_correct_answer(question_id)
    d['total_questions'] = Question.objects.filter(state='PUB').count()
    d['user_data'] = user_data
    d['show_hint'] = request.GET.get('show_hint', False)
    d['title'] = ' - Question #%d' % q.pk
    d['attempts_required'] = max(0, 3 - user_data.attempts_given_for(question_id))
    save_user_data(user_data, request.session)
    return render(request, 'quiz/index.html', d)
Пример #5
0
def question(request, question_id):
    if request.GET.get('preview_key'):
        return preview_with_key(request, question_id)
    user_data = UserData(request.session)
    q = get_object_or_404(Question, Q(id=question_id),
                          Q(state='PUB') | Q(state='RET'))
    q.mark_viewed()
    d = {}
    d['answered'] = False
    d['question'] = q
    d['dismissed_training_msg'] = user_data.dismissed_training_msg
    if request.GET.get('did_answer'):
        d['answered'] = True
        answer = Answer(q, request)
        answer.register_given_answer()
        user_data.register_attempt(answer)
        if answer.correct:
            d['correct_result'] = True
            user_data.register_correct_answer(question_id)
    d['total_questions'] = Question.objects.filter(state='PUB').count()
    d['user_data'] = user_data
    d['show_hint'] = request.GET.get('show_hint', False)
    d['title'] = ' - Question #%d' % q.pk
    d['attempts_required'] = max(0,
                                 3 - user_data.attempts_given_for(question_id))
    save_user_data(user_data, request.session)
    return render(request, 'quiz/index.html', d)
Пример #6
0
    def test_Q1_all(self):
        pointlist, textfdist, slist, rulelist = self.parse_Q1()
        manuallist = [
            9, 7, 9, 7, 7, 10, 7, 7, 7, 7, 7, 1, 2, 2, 0, 1, 2, 2, 1, 1, 8, 9,
            4, 9, 7, 9, 0, 7, 4, 10, 7, 7
        ]
        minmaxerr = 0
        minrd = 0
        minerrcount = 0
        for i in range(10):
            maxerr = 0
            errcount = 0
            var = 0
            rd = random.uniform(0.32, 0.36)
            debug_print_without_newline("rd = ")
            print rd

            # Create the appropriate class instance for Answer
            # TODO: Remove abAnswer method overrides altogether and do everything via proper subclassing (RTFM!!!).
            ## OLD: ans = abAnswer(dist_threshold=rd, multisen_matchrate=0.3, sen_threshold=rd, multisen_threshold=0.4)
            ans = None
            if (USE_OVERRIDES):
                ans = abAnswer(dist_threshold=rd,
                               multisen_matchrate=0.3,
                               sen_threshold=rd,
                               multisen_threshold=0.4)
            else:
                ans = Answer()
                self.dist_threshold = rd
                self.multisen_matchrate = 0.3
                self.sen_threshold = rd
                self.multisen_threshold = 0.4

            # Test all cases in Q1 directory
            for root, dirs, files in os.walk('algo/testdata/raw/Q1'):
                if 'Standard' in dirs:
                    dirs.remove('Standard')
                for idx in range(0, 32):
                    ansfile = 'Q1_SS' + str(idx + 1) + '.docx.txt'
                    filePath = os.path.join(root, ansfile)
                    fh = file(filePath, "r")
                    anstext = fh.read()
                    fh.close()
                    # TODO: Always use freq dist for student text (not standard)
                    if (USE_STUDENT_TEXT_DIST):
                        textfdist = get_student_text_distribution(
                            anstext, textfdist)
                    mark, marklist, ommited = ans.Analysis(
                        anstext, textfdist, slist, pointlist, rulelist)
                    err = mark - manuallist[idx]
                    maxerr += math.fabs(err)
                    var += err**2
                    errcount += 1 if math.fabs(err) > 3 else 0
                    print("%s\t%d\t%s\t%d" % (ansfile, mark, marklist, err))
                    if errcount < minerrcount:
                        minerrcount = errcount
                        minmaxerr = maxerr
                        minrd = rd
            print "maxerr:%d, maxvar:%d, errcount:%d" % (maxerr, var, errcount)
        print "minmaxerr:%d rd:%d count:%d" % (minmaxerr, minrd, minerrcount)
Пример #7
0
    def get(self, date):
        answer = Answer()
        totalEnquetesAnswers = []
        converted_date = datetime.datetime.strptime(
            str(date) + " 00:00:00", "%Y-%m-%d %H:%M:%S")
        possibleMeals = [1, 2, 3]

        for meal in possibleMeals:
            enquete = Enquete.query.find_by_meal(converted_date, meal)
            data = None
            if enquete is not None:
                data = enquete.to_json()
                for enqueteAnswers in data['answers']:
                    totalEnquetesAnswers.append(enqueteAnswers)
            else:
                data = None

            answer.content.update({meal: data})

        answer.content.update(
            {0: {
                'answers': totalEnquetesAnswers,
                'meal': 0
            }})

        return answer.to_json()
Пример #8
0
def get_answer(question):
    """
    :param question: String with the question.
    :return: Filled Answer object.
    note: if question starts with '>>>', just ask elasticsearch
    """
    if question.startswith('>>>'):
        return ask_only(question[3:])
    a = Answer(Question(question))

    checked = check_keywords(a.q)
    if not checked:
        a.q.query += ' (' + ','.join(a.q.not_in_kw) + ' not in keywords)'
        a.text = 'Didn\'t understand the question'
        return a

    # print warning on weird keywords
    # (XXX: should we give up on these questions instead?)
    check_unknowns(a)
    if len(a.q.unknown) > 0:
        print 'we have no information on these words:', a.q.unknown

    found_sources, found_anything = get_content_elastic(a, search_all=False)

    if found_sources:
        gen_features(a)
        a.text = answer_all(a)
        return a

    if not found_anything:
        a.text = 'Absolutely no result'
    else:
        a.text = 'No result'
    return a
Пример #9
0
 def __init__(self):
     display_introduction()
     self.settings = Settings()
     self.answer = Answer(self.settings)
     self.strikes = Strikes()
     self.guessed_letters = []
     self.turn_number = 1
Пример #10
0
def question(request, question_id):
    if request.GET.get('preview'):
        return preview(request, question_id)
    if request.GET.get('preview_key'):
        return preview_with_key(request, question_id)
    user_data = UserData(request.session)
    q = get_object_or_404(Question, id=question_id, published=True)
    d = {}
    d['answered'] = False
    d['question'] = q
    d['dismissed_training_msg'] = user_data.dismissed_training_msg
    if request.GET.get('did_answer'):
        d['answered'] = True
        answer = Answer(q, request)
        answer.register_given_answer()
        user_data.register_attempt(answer)
        if answer.correct:
            d['correct_result'] = True
            user_data.register_correct_answer(question_id)
    d['total_questions'] = Question.objects.filter(published=True).count()
    d['user_data'] = user_data
    d['show_hint'] = request.GET.get('show_hint', False)
    d['title'] = ' - Question #%d' % q.pk
    d['attempts_required'] = max(0, 3 - user_data.attempts_given_for(question_id))
    save_user_data(user_data, request.session)
    return render_to_response('quiz/index.html',
        d,
        context_instance=RequestContext(request)
        )
Пример #11
0
    def get(self, date):
        answer = Answer()
        totalEnquetesAnswers = []
        converted_date = datetime.datetime.strptime(str(date) + " 00:00:00", "%Y-%m-%d %H:%M:%S")
        possibleMeals = [
            1, 2, 3
        ]

        for meal in possibleMeals:
            enquete = Enquete.query.find_by_meal(converted_date, meal)
            data = None
            if enquete is not None:
                data = enquete.to_json()
                for enqueteAnswers in data['answers']:
                    totalEnquetesAnswers.append(enqueteAnswers)
            else:
                data = None

            answer.content.update({
                meal: data
            })

        answer.content.update({
            0: {
                'answers': totalEnquetesAnswers,
                'meal': 0
            }
        })


        return answer.to_json()
Пример #12
0
def get_answers(question, answers_dirpath):
    log('Answering "{}"'.format(question))

    question.documents = get_documents(answers_dirpath, question.qid)

    question_tokens = strip_function_words_from_question(question)
    q_words = [word.lower() for word in question_tokens]

    all_answers = []
    for doc in question.documents:
        all_answers += get_all_answers_ranked(question, q_words, doc)

    all_answers = list(set(all_answers))
    all_answers.sort(key=lambda x: x.rank, reverse=True)
    size = min(5, len(all_answers))
    if size < 5:
        warn('Found less than 5 answers for "{}". Appending NIL.'.format(
            question))
        all_answers.append(Answer.Nil(question.qid))
        size += 1

    answers = []
    for answer in all_answers[:size]:
        length = min(10, len(answer.tokens))
        if length < len(answer.tokens):
            warn('Truncating {} word answer to 10 words'.format(
                len(answer.tokens)))
        answers.append(
            Answer(answer.qid, answer.doc_id, answer.tokens[:length]))

    return answers
Пример #13
0
def loadSurvey(filename):
    from question import Question
    from answer import Answer
    survey = None
    f = open(filename, "r")
    if f is not None:
        s = ""
        b = f.read(512)
        while len(b):
            s += b
            b = f.read(512)
        f.close()
        sd = jsonpickle.decode(s)
        survey = Survey()
        survey.name = sd['name']
        survey.questions = {}
        for qd in sd['questions'].values():
            question = Question()
            question.id = qd['id']
            question.name = qd['name']
            question.answers = {}
            for ad in qd['answers'].values():
                answer = Answer()
                answer.id = ad['id']
                answer.value = ad['value']
                answer.selected = ad['selected']
                answer.editable = ad['editable']
                question.answers[answer.id] = answer
            survey.questions[question.id] = question
    return survey
Пример #14
0
    def post(self):
        answer = Answer()
        current_meal = self.get_current_meal()
        current_date = datetime.datetime.now()
        start_date = datetime.datetime(current_date.year, current_date.month, current_date.day)

        if current_meal is None:
            answer.status = 0
            answer.messages.append("No active poll")
            return answer.to_json()


        enquete = Enquete.query.find_by_meal(start_date, current_meal)

        if enquete is None:
            enquete = Enquete()
            enquete.date = current_date
            enquete.answers = []
            enquete.save()

        resposta = Resposta()
        resposta.card = int(request.form['card'])
        resposta.like_level = int(request.form['like'])
        resposta.comment = request.form['comment']

        enquete.answers.append(resposta)
        enquete.save()

        answer.status = 1
        return answer.to_json()
Пример #15
0
	def LoadAnswers(self):
		self.question = Answer.getFromId(self.questionAnswerId)
		answers = []
		for answerId in self.answersIds:
			ans = Answer.getFromId(answerId)
			if ans is not None:
				answers.append(ans)
		self.answers = answers
Пример #16
0
    def get(self):
        answer = Answer()
        answer.status = 1
        answer.content = {
            "app": "enquete-ru"
        }

        return answer.to_json()
Пример #17
0
 def __init__(self, **kwargs):
     debug_print(
         "Warning: Using shameless hack (abAnswer testing class): FIX ME!")
     Answer.__init__(self)
     self.dist_threshold = kwargs.get('dist_threshold') or 0.3
     self.multisen_matchrate = kwargs.get('multisen_matchrate') or 0.3
     self.sen_threshold = kwargs.get('sen_threshold') or 0.15
     self.multisen_threshold = kwargs.get('multisen_threshold') or 0.4
     nltk.data.path = [settings.NLTKDATAPATH]
Пример #18
0
 def setUp(self):
     global survey
     survey = Survey()
     q = survey.add(Question(1, "Question1"))
     q.add(Answer(1, "answer1"))
     q.add(Answer(2, "answer2"))
     q = survey.add(Question(2, "Question2"))
     q.add(Answer(3, "answer3"))
     q.add(Answer(4, "answer4"))
     q.add(Answer(5, "answer5"))
Пример #19
0
def main():
    print("loading config")
    try:
        config = configparser.RawConfigParser()
        configFilePath = "main.config"
        config.read(configFilePath)

        startingIndex = int(config.get("main-config", "starting-index"))
        date = config.get("main-config", "start-date").replace("/", "")
        fileLocation = config.get("main-config", "file-location")
        errorsLocation = config.get("main-config", "error-location")
        numQuestionsPerDay = int(
            config.get("main-config", "num-questions-per-day"))
        numToIncrement = int(config.get("main-config",
                                        "num-to-increment-date"))
    except:
        print("config load failed. halting")
        return

    print("config loaded. beginning scraping")

    numSinceHit = 0
    i = 0

    while True:
        index = i + startingIndex
        url = "https://answers.yahoo.com/question/index?qid=10" + date + str(
            index).zfill(5)  # the structure of a question id:
        print("testing " + url)  # 10YYMMDDIIIII i is a 5 digit index
        if isValidPage(url):  # that seems to be sequential
            numSinceHit = 0  # thats the old qid system the new one
            print("valid page found at " +
                  url)  # is a little different but its the same vibe
            try:
                ans = Answer(url)
                print("object generated, writing file")
                ans.writeJsonFile("10" + date + str(index).zfill(5),
                                  fileLocation)
                print("file written")
            except:
                print("error while generating object. logging")
                logErrors("10" + date + str(index).zfill(5), errorsLocation)
        else:
            numSinceHit += 1
            print("too many misses. incrementing date")
            if (numSinceHit == numToIncrement):
                numSinceHit = 0
                i = 0
                date = incrementDate(date)
        if i > numQuestionsPerDay:
            print("reached end of scope. incrementing date")
            numSinceHit = 0
            i = 0
            date = incrementDate(date)
        i += 1
Пример #20
0
    def get(self, year, month):
        answer = Answer()
        totalEnquetesAnswers = []
        enquetes = Enquete.query.find_by_month(int(year), int(month))
        for enquete in enquetes:
            data = enquete.to_json()
            for enqueteAnswers in data['answers']:
                totalEnquetesAnswers.append(enqueteAnswers)

        answer.content = totalEnquetesAnswers

        return answer.to_json()
Пример #21
0
    def get(self, date, meal):
        answer = Answer()
        converted_date = datetime.datetime.strptime(str(date) + " 00:00:00", "%Y-%m-%d %H:%M:%S")
        enquete = Enquete.query.find_by_meal(converted_date, meal)

        if enquete is not None:
            answer.content = enquete.to_json()
            answer.status = 1
        else:
            answer.status = 0

        return answer.to_json()
Пример #22
0
    def find_entity_query(self,
                          qtype,
                          inst,
                          prop_match_t=None,
                          prop_match2_t=None):
        """Transforms matched context into query parameters and performs query for
        queries to find entities

        Args:
            qtype (str): Matched type of query (what, who, where, etc.)
            inst (str): Matched instance of entity to match (Obama)
            action (str): Matched verb action (is, was, ran)
            prop_match_t (Tree): Matched property Tree
            prop_match2_t (Tree): Matched property Tree

        Returns:
            Answer: Answer from query, or empty Answer if None
        """

        props = []
        if prop_match_t:
            prop = match_rules(prop_match_t,
                               RULES[self.properties['lang']]['prop_rules'],
                               self.get_prop_tuple)

            if not prop:
                return

            props += prop

        if prop_match2_t:
            prop = match_rules(prop_match2_t,
                               RULES[self.properties['lang']]['prop_rules'],
                               self.get_prop_tuple)

            if not prop:
                return

            props += prop

        if not inst.isupper():
            inst = singularize(inst)

        ans = self.wd.find_entity(qtype, inst, props)
        if not ans:
            ans = Answer()

        ans.params = {
            'qtype': qtype,
            'inst': inst,
            'props': props,
        }
        return ans
Пример #23
0
    def __traversal_process(self, testdir):
        ans = Answer()
        for root, dirs, files in os.walk(testdir):
            if 'Standard' in dirs:
                dirs.remove('Standard')
            for stdfile in files:
                # Check for answer file (e.g., "ans_q8.txt")
                if 'ans' in stdfile:
                    testno = stdfile[4:-4]
                    self.logger.info("no:%s" % testno)
                    stdPath = os.path.join(root, stdfile)
                    if not os.path.isfile(stdPath):
                        self.logger.error("Test file doesn't exist:%s" %
                                          stdfile)
                        assert False
                    fh = file(stdPath, "r")
                    filetext = fh.read()
                    fh.close()
                    sinst = Standard()
                    pointlist, textfdist, slist = sinst.Analysis(filetext)

                    # Check schema file (e.g., "scheme_q8.txt")
                    schemename = 'scheme_' + testno + '.txt'
                    schemepath = os.path.join(root, schemename)
                    fr = file(schemepath, 'r')
                    scheme = self.__parsescheme(fr.read())
                    fr.close()
                    rulelist = self.__updaterulelist(scheme, pointlist)
                    print("ansfile\tmark\tmarklist")
                    for idx in range(0, 10):
                        # Check student response file (e.g., "stud9_q8.txt")
                        ansfile = 'stud' + str(idx + 1) + '_' + testno + '.txt'
                        ansPath = os.path.join(root, ansfile)
                        if os.path.isfile(ansPath):
                            fa = file(ansPath, 'r')
                            anstext = fa.read()
                            fa.close()
                            if anstext:
                                # TODO: Always use freq dist for student text (not standard)
                                if (USE_STUDENT_TEXT_DIST):
                                    textfdist = get_student_text_distribution(
                                        anstext, textfdist)
                                debug_print("Calling ans.Analysis%s" % str(
                                    (anstext, textfdist, slist, pointlist,
                                     rulelist)),
                                            level=4)
                                mark, marklist, ommited = ans.Analysis(
                                    anstext, textfdist, slist, pointlist,
                                    rulelist)
                            else:
                                mark = 0
                                marklist = []
                            print("%s\t%d\t%s" % (ansfile, mark, marklist))
Пример #24
0
    def get(self):
        answer = Answer()
        enquetes = models.Enquete.query.all()
        jsonEnquetes = []

        for enquete in enquetes:
            jsonEnquetes.append(enquete.to_json())

        answer.status = 1
        answer.content = jsonEnquetes

        return answer.to_json()
Пример #25
0
    def get(self):
        answer = Answer()
        totalEnquetesAnswers = []
        enquetes = Enquete.query.all()
        for enquete in enquetes:
            data = enquete.to_json()
            for enqueteAnswers in data['answers']:
                totalEnquetesAnswers.append(enqueteAnswers)

        answer.content = totalEnquetesAnswers

        return answer.to_json()
Пример #26
0
 def __init__(self, question: str):
     self.question: str = question
     """Content of the question."""
     self.__answer_a = Answer()
     """Content of the answer A"""
     self.__answer_b = Answer()
     """Content of the answer B"""
     self.__answer_c = Answer()
     """Content of the answer C"""
     self.__answer_d = Answer()
     """Content of the answer D"""
     self.__answer_column = 1
     """Number of columns for which the answer will be presented. Answers can be presented as 
Пример #27
0
    def get(self):
        answer = Answer()
        totalEnquetesAnswers = []
        enquetes = Enquete.query.all()
        for enquete in enquetes:
            data = enquete.to_json()
            for enqueteAnswers in data['answers']:
                totalEnquetesAnswers.append(enqueteAnswers)

        answer.content = totalEnquetesAnswers;


        return answer.to_json()
Пример #28
0
    def get(self, year, month):
        answer = Answer()
        totalEnquetesAnswers = []
        enquetes = Enquete.query.find_by_month(int(year), int(month))
        for enquete in enquetes:
            data = enquete.to_json()
            for enqueteAnswers in data['answers']:
                totalEnquetesAnswers.append(enqueteAnswers)

        answer.content = totalEnquetesAnswers;


        return answer.to_json()
Пример #29
0
        def txn():
            ans_key_name = "key_" + str(no) + "_" + str(pai)
            #answer = Answer.get_or_insert(ans_key_name, question_no=no, pai=pai)
            answer = Answer.get_by_key_name(ans_key_name)
            if answer is None:
                answer = Answer(key_name=ans_key_name, question_no=no, pai=pai)

            answer.vote_num += 1
            answer.put()

            logging.debug("increment_answer - No:%s Pai:%s Num:%s",
                          str(answer.question_no), str(answer.pai),
                          str(answer.vote_num))
Пример #30
0
    def get(self):
        answer = Answer()
        enquetes = models.Enquete.query.all()
        jsonEnquetes = []

        for enquete in enquetes:
            jsonEnquetes.append(
                enquete.to_json()
            )

        answer.status = 1
        answer.content = jsonEnquetes

        return answer.to_json()
Пример #31
0
    def answer_question(self, answerer, question, answer_content):
        answer = Answer(question, answerer, answer_content)
        self.database.insert_answer(answer)

        incident = self.get_incident_by_question(question)
        self.create_notification(
            incident, answerer.forename + ' ' + answerer.surname +
            ' answered a question on ' + incident.title)

        answer.date_answered = self.database.get_date_answered(answer)

        question.answers.append(answer)

        self.database.commit()
Пример #32
0
def ask_only(query):
    a = Answer(Question(preprocess_question(query)))
    check_unknowns(a)
    if len(a.q.unknown) > 0:
        print 'we have no information on these words:', a.q.unknown
    found_sources, found_anything = ask(a, query)
    if found_sources:
        gen_features(a)
        a.text = answer_all(a)
        a.text = 'Query only'
        return a
    if not found_anything:
        a.text = 'Absolutely no result'
    return a
Пример #33
0
    def subject_query(self,
                      qtype,
                      subject,
                      action,
                      jj=None,
                      prop=None,
                      prop2=None,
                      prop3=None):
        """Transforms matched context into query parameters and performs query

        Args:
            qtype: Matched type of query (what, who, where, etc.)
            subject: Matched subject (Obama)
            action: Matched verb action (is, was, ran)
            jj (optional): Matched adverb
            prop (optional): Matched prop
            prop2 (optional): Matched prop
            prop3 (optional): Matched prop

        Returns:
            Answer: Answer from query, or empty Answer if None
        """
        if jj == 'old':
            # How old is Obama?
            prop = 'age'

        if jj in ['tall', 'high']:
            # How tall is Yao Ming / Eifel tower?
            prop = 'height'

        if prop2:
            prop = prop + ' ' + prop2

        if prop3 and not prop:
            prop = prop3

        if not prop:
            if action not in ['is', 'was']:
                prop = action

        ans = self.get_property(qtype, subject, prop)
        if not ans:
            ans = Answer()

        ans.params = {
            'qtype': qtype,
            'subject': subject,
            'prop': prop,
        }
        return ans
Пример #34
0
def ask_only(query):
    a = Answer(Question(preprocess_question(query)))
    check_unknowns(a)
    if len(a.q.unknown) > 0:
        print 'we have no information on these words:', a.q.unknown
    found_sources, found_anything = ask(a, query)
    if found_sources:
        gen_features(a)
        a.text = answer_all(a)
        a.text = 'Query only'
        return a
    if not found_anything:
        a.text = 'Absolutely no result'
    return a
Пример #35
0
class Game:
    def __init__(self):
        display_introduction()
        self.settings = Settings()
        self.answer = Answer(self.settings)
        self.strikes = Strikes()
        self.guessed_letters = []
        self.turn_number = 1

    def did_win(self):
        return self.answer.letters.issubset(self.guessed_letters)

    def play(self):
        explain_rules()
        answer_guessed = False
        while not self.did_win() and not self.strikes.limit_reached():
            utils.clear_screen()
            utils.print_header("Turn {}".format(str(self.turn_number)))
            turn = Turn(self.answer, self.guessed_letters, self.strikes)
            if self.answer.equals(turn.guess):
                answer_guessed = True
                break
            self.guessed_letters.append(turn.guess)
            if turn.guess not in self.answer.lower():
                self.strikes.add(turn.guess)
            self.turn_number += 1
        self.end_game(answer_guessed)
        return self.play_again()

    def end_game(self, answer_guessed):
        utils.clear_screen()
        if self.did_win() or answer_guessed:
            title = " YOU WON "
            message = "Correct!"
        else:
            title = "GAME OVER"
            message = "Game over."
        utils.print_header(title)
        self.strikes.display_hangman()
        print("{} The answer was \"{}{}\"".format(message, self.answer,
                                                  "" if self.answer.ends_with_punctuation() else "."))

    def play_again(self):
        again = input("\nWould you like to play again? ").lower()
        yes_answers = ['y', 'yes']
        no_answers = ['n', 'no']
        while again not in yes_answers and again not in no_answers:
            self.play_again()
        return again in yes_answers
Пример #36
0
    def _onBtnPress(self, pressedBtn):
        if self._answerLocked:
            return

        mapping = {
            Application.BTN_A: 0,
            Application.BTN_B: 1,
            Application.BTN_C: 2,
            Application.BTN_D: 3,
        }
        answer = Answer(self.ui, self.activeQuestion, mapping[pressedBtn])
        correctBtn = next(k for k,v in mapping.items() if v == int(self.activeQuestion.getCorrectAnswer()))

        self.ui.highlightBtn(correctBtn, None if pressedBtn == correctBtn else pressedBtn)
        self._answerLocked = True
        self.send(answer.toDict(), True)
Пример #37
0
def fibonacci(f, a, b):
    n = 0
    for i in range(0, 100):
        if (b - a) / EPS < fibonacci_n(i):
            n = i
            break

    la = a + fibonacci_n(n - 2) / fibonacci_n(n) * (b - a)
    mu = a + fibonacci_n(n - 1) / fibonacci_n(n) * (b - a)
    f_la = f(la)
    f_mu = f(mu)
    for k in range(1, n - 1):
        if f_la > f_mu:
            a = la
            la = mu
            f_la = f_mu
            mu = a + fibonacci_n(n - k - 1) / fibonacci_n(n - k) * (b - a)
            f_mu = f(mu)
        else:
            b = mu
            mu = la
            f_mu = f_la
            la = a + fibonacci_n(n - k - 2) / fibonacci_n(n - k) * (b - a)
            f_la = f(la)

    mu = la + EPS
    f_mu = f(mu)
    if f_la < f_mu:
        b = mu
    else:
        a = la

    x = (b + a) / Decimal("2")
    return Answer(x, f(x))
 def extract_answers(self, url):
     page = 1
     answers = []
     try:
         max_pages = int(self.extract_max_answers_pages(url))
     except ConnectionError:
         raise ConnectionError('unable to connect to url'+url)
     else:
         while page <= max_pages:
             try:
                 web_page = handle_req_tries(self.url_base+url+'?page='+str(page), self.max_tries)
             except ConnectionError:
                 raise ConnectionError('unable to retrieve all answers')
             else:
                 souped_page = self.remove_br_tags(bs(web_page, 'html.parser'))
                 for answer in souped_page.find('div', {'id' : 'post_answer_body'}).findAll('div', {'class' : 'post_entry_right'}):
                     post_id = answer.find('div', {'class' : 'post_message'})['data-post_id']
                     answers.append(Answer(#answer.find('a')['id']
                         #, answer.find('a')['href']
                         self.concatenate_string_array(self.convert_a_tags(answer.find('div', {'class', 'post_message'})).contents)
                         , answer.find('time', {'class', 'mh_timestamp'})['data-timestamp']
                         , int(answer.find('span', {'id' : 'user_rating_count_Post_'+post_id}).contents[0])
                         , post_id))
                     page+=1
                 return answers
Пример #39
0
    def load(cls, poll_id: int) -> Optional['Poll']:
        with sqlite3.connect(DB_PATH) as conn:
            conn.row_factory = sqlite3.Row
            cur = conn.cursor()

            cur.execute(
                """
                SELECT
                    p.id         AS id,
                    p.owner_id   AS owner_id,
                    p.topic      AS topic,
                    u.first_name AS first_name,
                    u.last_name  AS last_name,
                    u.username   AS username
                  FROM polls p
                  JOIN users u
                    ON p.owner_id = u.id
                 WHERE p.id = ?
                 """, (poll_id, ))
            row: sqlite3.Row = cur.fetchone()

            if row is not None:
                user = User(row['owner_id'],
                            is_bot=False,
                            first_name=row['first_name'],
                            last_name=row['last_name'],
                            username=row['username'])
                poll = cls(user, row['topic'])
                poll.id = row['id']

                # next, load answers
                poll._answers = Answer.query(poll)

                return poll
Пример #40
0
	def from_dictionary(data):
		question = data['question']
		answer = Answer.from_dictionary(data['answer'])
		topics = data['topics']
		history = data['history']
		time = data['created_at']
		return Question(question, answer, topics, history, time)
Пример #41
0
def get_all_answers_ranked(question, question_words, doc):
    """Given a question and a document, get all the answers
    for this question from this document with their respective ranks
    """
    answers = []
    for sentence in doc.content:
        stripped_sentence = strip_function_words(sentence)
        # If there's no useful data, skip this...
        if not stripped_sentence:
            continue

        sentence_words, _, ner_classes = zip(*stripped_sentence)

        if question.qtype == Question.TYPE_WHEN:
            is_timey = get_time_type_for_words(sentence_words)
            ner_matches = [i for i, flag in enumerate(is_timey) if flag]
        else:
            ner_matches = []
            desired_ner_class = get_ner_classes_for_question(question)
            for i, ner_class in enumerate(ner_classes):
                if ner_class in desired_ner_class:
                    ner_matches.append(i)

        # If there is no relevant answer, skip this...
        if not ner_matches:
            continue

        # Extract and rank each relevant window...
        for i in ner_matches:
            candidate = get_window(sentence_words, i, 4)

            score = 0.0
            common = []
            for word in candidate:
                if word.lower() in question_words:
                    common.append(word.lower())
            score = len(common)

            # If there is no relevance, skip this answer...
            if not score:
                continue

            ans = Answer(question.qid, doc.doc_id, candidate)
            ans.rank = score
            answers.append(ans)

    return answers
Пример #42
0
class Variant8:
    a = Decimal("0")
    b = Decimal("1")
    answer = Answer(Decimal("0.5774"), Decimal("-0.3849"))

    @staticmethod
    def f(x):
        return x**Decimal("3") - x
Пример #43
0
class Variant7:
    a = Decimal("-10")
    b = Decimal("20")
    answer = Answer(Decimal("-1"), Decimal("-5"))

    @staticmethod
    def f(x):
        return x**Decimal("2") + Decimal("2") * x - Decimal(4)
Пример #44
0
class Variant3:
    a = Decimal("-2")
    b = Decimal("20")
    answer = Answer(Decimal("2"), Decimal("0"))

    @staticmethod
    def f(x):
        return (x - Decimal("2"))**Decimal("2")
Пример #45
0
	def build(self,title,text,tags,author):
		exists = db.questions.find_one(title)
		if exists is None:
			answer = Answer.build(author, text,title,True).save()
			quest = Question(title, tags, answer._id,).save()
			return quest
		else:
			raise askExceptions.NotExist('question',"Already exists with same title"+str(title))
Пример #46
0
    def get(self):
        answer = Answer()
        current_meal = self.get_current_meal()
        current_date = datetime.datetime.now()
        start_date = datetime.datetime(current_date.year, current_date.month,
                                       current_date.day)

        if current_meal is not None:
            enquete = Enquete.query.find_by_meal(start_date, current_meal)

            if enquete is not None:
                enquete_json = enquete.to_json()
            else:
                enquete_json = None

            answer.status = 1
            answer.content = {
                "current_meal": current_meal,
                "enquete": enquete_json
            }

            return answer.to_json()
        else:
            answer.status = 0

            return answer.to_json()
Пример #47
0
 def answer(self, request):
     debug_string = "IP:%s, quiz:%s, result:%s, answer:%s, answers:%d" %\
         (util.get_client_ip(request), self.quiz.key, request.GET.get('result', ''), request.GET.get('answer', ''), len(self.answers))
     logging.getLogger('quiz').debug(debug_string)
     answer = Answer(self.get_current_question(), request)
     answer.register_given_answer()
     if answer.correct:
         self.answers.append(QuestionStats(attempts=self.attempts, used_hint=self.used_hint))
         self._reset_question_state()
         self.previous_result = 'correct'
         self.previous_explanation = answer.question.explanation
     else:
         self.previous_result = 'incorrect'
         self.attempts += 1
     debug_string = "IP:%s, quiz:%s, question:#%d (%d/%d), given_result:%s, given_answer:%s, correct:%s" % \
         (answer.ip, self.quiz.key, answer.question.pk, len(self.answers), self.quiz.questions.count(), answer.given_result, answer.given_answer, answer.correct)
     logging.getLogger('quiz').debug(debug_string)
     return
Пример #48
0
def question(request, question_id):
    if request.REQUEST.get("preview"):
        return preview(request, question_id)
    user_data = UserData(request.session)
    q = get_object_or_404(Question, id=question_id, published=True)
    d = {}
    d["answered"] = False
    d["question"] = q
    if request.REQUEST.get("did_answer"):
        d["answered"] = True
        answer = Answer(q, request)
        answer.register_given_answer()
        if answer.correct:
            d["correct_result"] = True
            user_data.register_correct_answer(question_id)
    d["total_questions"] = Question.objects.filter(published=True).count()
    d["user_data"] = user_data
    d["show_hint"] = request.REQUEST.get("show_hint", False)
    save_user_data(user_data, request.session)
    return render_to_response("quiz/index.html", d, context_instance=RequestContext(request))
Пример #49
0
def process_answer_items(content, beautify=True):
    """
    Process response and generate dictionary with questions and URL
    :param content:
    :param beautify:
    :return:
    """
    answers = list()
    if "items" in content:
        items = content["items"]
        for item in items:
            answer = Answer()
            answer.id = item['answer_id']
            answer.body = item['body']
            answer.is_accepted = item['is_accepted']
            if beautify:
                formatter = Formatter()
                answer.body_clean = formatter.beautify(answer.body)
            answers.append(answer)
    return answers
Пример #50
0
    def get(self):
        answer = Answer()
        current_meal = self.get_current_meal()
        current_date = datetime.datetime.now()
        start_date = datetime.datetime(current_date.year, current_date.month, current_date.day)

        if current_meal is not None:
            enquete = Enquete.query.find_by_meal(start_date, current_meal)

            if enquete is not None:
                enquete_json = enquete.to_json()
            else:
                enquete_json = None

            answer.status = 1
            answer.content = {
                "current_meal": current_meal,
                "enquete": enquete_json
            }

            return answer.to_json()
        else:
            answer.status = 0

            return answer.to_json()
Пример #51
0
def answer_test():
    start = time.time()
    answer = Answer('http://www.zhihu.com/question/33488763/answer/56619442')
    answer.parser()
    print "Author is ", answer.get_author()
    print "Question url is ", answer.get_question_url()
    print "Question text is ", answer.get_question_text()
    print "Number of vote is ", answer.get_vote_num()
    print "Answer content is ", answer.get_content()
    print "Number of comment is ", answer.get_comment_num()
    print "Number of view is ", answer.get_view_num()
    print "Number of time being collected is ", answer.get_collected_num()
    print "Created time is ", answer.get_created_time()
    print "Last modified time is ", answer.get_last_modified_time()
    answer.save_answer_to_file()
    answer.save_all_comments()
    print "Answer robot vote rate is {0}".format(answer.save_all_voters_profile())  # might be time-consuming
    end = time.time()
    print "Time used is", end - start
Пример #52
0
answer_url = ""
voters_url = ""

questio_test = Question(question_url)
print "get_title:\t", questio_test.get_title()
print "get_detail:\t", questio_test.get_detail()
print "get_answers_num:\t", questio_test.get_answers_num()
print "get_followers_num:\t", questio_test.get_followers_num()
print "get_topics:\t", questio_test.get_topics()
print "get_all_answers:\t", questio_test.get_all_answers().next()
print "get_visit_times:\t", questio_test.get_visit_times()


print "\n" * 20

answer_test = Answer(questio_test.get_all_answers().next())

print "get_author\t", answer_test.get_author()
print "get_upvote\t", answer_test.get_upvote()
print "get_content\t", answer_test.get_content()
print "get_answerid\t", answer_test.get_answerid()

print "\n" * 20
voters_test = Voters(answer_test.get_answerid())
print "get_voters", voters_test.get_voters().next()


user_test = User(*voters_test.get_voters().next())

print "\n" * 20
print "get_user_id\t", user_test.get_user_id()
Пример #53
0
	def addAnswer(self,author, text):
		answer = Answer.build(author,text,self.title,False)
		self.answersIds.append(answer._id)
		self.save()
Пример #54
0
	def getAnswer(self, answerID):
		return Answer.getFromId(answerID)