@param GraphicQuestion $question
@param $answer

@return CorrectedAnswer
486522
public function correctAnswer(AbstractItem $question, $answer)
    {
        $corrected = new CorrectedAnswer();

        /** @var Area $area */
        foreach ($question->getAreas() as $area) {
            if (is_array($answer)) {
                foreach ($answer as $coords) {
                    if ($this->isPointInArea($area, $coords['x'], $coords['y'])) {
                        if ($area->getScore() > 0) {
                            $corrected->addExpected($area);
                        } else {
                            $corrected->addUnexpected($area);
                        }
                    } elseif ($area->getScore() > 0) {
                        $corrected->addMissing($area);
                    }
                }
            } elseif ($area->getScore() > 0) {
                $corrected->addMissing($area);
            }
        }

        return $corrected;
    }
175790
protected function askQuestion($question, $choices, $default)
	{
		// Ask until we get a valid response
		do
		{
			echo $question.' '.$choices.': ';
			
			$handle = fopen("php://stdin", "r");
			$line = fgets($handle);

			$response = trim($line);

			// Use default when no response is given
			if (empty($response))
				$response = $default;
		}
		while (!in_array($response, explode('/', $choices)));

		return $response;
	}
770699
public function removeAnswer(AnswerInterface $answer)
    {
        if ($this->hasAnswer($answer)) {
            $this->answers->removeElement($answer);
        }

        return $this;
    }
293066
public static function input($question, $default = null)
    {
        echo $question.': ';
        $handle = fopen ('php://stdin', 'r');

        $answer = fgets($handle);
        fclose($handle);

        $answer = trim($answer);

        if(!$answer) {
            $answer = $default;
        }

        return $answer;
    }
354977
public function find_right_answer($wrappedquestion) {
        // We only take into account *one* (the first) correct answer.
        while ($answer = array_shift($wrappedquestion->answers)) {
            if (!question_state::graded_state_for_fraction(
                    $answer->fraction)->is_incorrect()) {
                // Store this answer as a choice, only if this is a new one.
                $key = array_search($answer->answer, $this->choices);
                if ($key === false) {
                    $key = $answer->id;
                    $this->choices[$key] = $answer->answer;
                }
                return $key;
            }
        }
        // We should never get there.
        throw new coding_exception('shortanswerquestionwithoutrightanswer', $wrappedquestion->id);

    }
654253
public function expectAnswer(AbstractItem $question)
    {
        $expected = [];

        switch ($question->getSumMode()) {
            case GridQuestion::SUM_CELL:
                foreach ($question->getCells()->toArray() as $cell) {
                    if (0 < count($cell->getChoices())) {
                        $expected[] = $this->findCellExpectedAnswer($cell);
                    }
                }
                break;
            case GridQuestion::SUM_COLUMN:
                for ($i = 0; $i < $question->getColumns(); ++$i) {
                    // get cells where there is at least 1 expected answers for the current column (none possible)
                    foreach ($question->getCells() as $cell) {
                        // found a cell in this col with an expected answer
                        if ($cell->getCoordsX() === $i && 0 < count($cell->getChoices())) {
                            // all choices should have the same score
                            $scoreToApply = $cell->getChoices()[0]->getScore();
                            $expected[] = new GenericScore($scoreToApply);
                            break;
                        }
                    }
                }
                break;
            case GridQuestion::SUM_ROW:
                for ($i = 0; $i < $question->getRows(); ++$i) {
                    // get cells where there is at least 1 expected answers for the current row (none possible)
                    foreach ($question->getCells() as $cell) {
                        // found a cell in this row with an expected answer
                        if ($cell->getCoordsY() === $i && 0 < count($cell->getChoices())) {
                            // all choices should have the same score
                            $scoreToApply = $cell->getChoices()[0]->getScore();
                            $expected[] = new GenericScore($scoreToApply);
                            break;
                        }
                    }
                }
                break;
        }

        return $expected;
    }
69282
public function ask(SimpleQuestion $question)
    {
        return $this->question->ask(
            $this->input,
            $this->output,
            new Question(
                $this->buildQuestionText($question),
                $this->getPreResponse($question)
            )
        );
    }
17944
protected function render_question_text($question) {
        global $OUTPUT;

        $text = question_rewrite_question_preview_urls($question->questiontext, $question->id,
                $question->contextid, 'question', 'questiontext', $question->id,
                $this->context->id, 'quiz_statistics');

        return $OUTPUT->box(format_text($text, $question->questiontextformat,
                array('noclean' => true, 'para' => false, 'overflowdiv' => true)),
                'questiontext boxaligncenter generalbox boxwidthnormal mdl-align');
    }
983122
public function correctAnswer(AbstractItem $question, $answers)
    {
        $corrected = new CorrectedAnswer();

        if (!is_null($answers)) {
            switch ($question->getMode()) {
               case $question::MODE_FIND:
                  $foundUuids = [];

                  foreach ($answers->positions as $position) {
                      foreach ($question->getSelections()->toArray() as $selection) {
                          if ($position >= $selection->getBegin() && $position <= $selection->getEnd()) {
                              if ($selection->getScore() > 0) {
                                  if (!in_array($selection->getUuid(), $foundUuids)) {
                                      $foundUuids[] = $selection->getUuid();
                                      $corrected->addExpected($selection);
                                  }
                              } else {
                                  $corrected->addUnexpected($selection);
                              }
                          }
                      }
                  }

                  $bestAnswers = $this->expectAnswer($question);
                  $uuids = array_map(function ($selection) {
                      return $selection->getUuid();
                  }, $bestAnswers);

                  if ($question->getPenalty() > 0) {
                      $penaltyTimes = $answers['tries'] - count($foundUuids);

                      for ($i = 0; $i < $penaltyTimes; ++$i) {
                          $unexpected = new Selection();
                          $unexpected->setScore(-1 * $question->getPenalty());
                          $corrected->addUnexpected($unexpected);
                      }
                  }

                  foreach ($uuids as $uuid) {
                      if (!in_array($uuid, $foundUuids)) {
                          $corrected->addMissing($question->getSelection($uuid));
                      }
                  }

                  return $corrected;

               case $question::MODE_SELECT:
                  foreach ($answers['selections'] as $selectionId) {
                      $selection = $question->getSelection($selectionId);
                      $selection->getScore() > 0 ? $corrected->addExpected($selection) : $corrected->addUnexpected($selection);
                  }

                  $bestAnswers = $this->expectAnswer($question);
                  $uuids = array_map(function ($selection) {
                      return $selection->getUuid();
                  }, $bestAnswers);

                  foreach ($uuids as $uuid) {
                      if (!in_array($uuid, $answers['selections'])) {
                          $corrected->addMissing($question->getSelection($uuid));
                      }
                  }

                  return $corrected;
               case $question::MODE_HIGHLIGHT:
                  $foundElements = [];

                  if (isset($answers['highlights'])) {
                      foreach ($answers['highlights'] as $highlightAnswer) {
                          if ($colorSelection = $question->getColorSelection(['color_uuid' => $highlightAnswer['colorId'], 'selection_uuid' => $highlightAnswer['selectionId']])) {
                              $colorSelection->getScore() > 0 ? $corrected->addExpected($colorSelection) : $corrected->addUnexpected($colorSelection);

                              $foundElements[] = ['color_uuid' => $highlightAnswer['colorId'], 'selection_uuid' => $highlightAnswer['selectionId']];
                          }
                      }
                  }
                  $bestAnswers = $this->expectAnswer($question);
                  $elements = array_map(function ($colorSelection) {
                      //id always returns null as of now
                      return ['color_uuid' => $colorSelection->getColor()->getUuid(), 'selection_uuid' => $colorSelection->getSelection()->getUuid()];
                  }, $bestAnswers);

                  $addedMissing = 0;

                  foreach ($elements as $element) {
                      if (!in_array($element, $foundElements)) {
                          ++$addedMissing;
                          $corrected->addMissing($question->getColorSelection(['color_uuid' => $element['color_uuid'], 'selection_uuid' => $element['selection_uuid']]));
                      }
                  }

                  if ($question->getPenalty() > 0) {
                      $penaltyTimes = count($question->getSelections()) - count($foundElements);

                      for ($i = 0; $i < $penaltyTimes; ++$i) {
                          $unexpected = new Selection();
                          $unexpected->setScore(-1 * $question->getPenalty());
                          $corrected->addUnexpected($unexpected);
                      }
                  }

                  return $corrected;
            }
        }
    }
259801
public function update(Item $question, Answer $answer, array $answerData, $noFlush = false)
    {
        $errors = $this->validator->validate($answerData, [Validation::QUESTION => $question->getInteraction()]);
        if (count($errors) > 0) {
            throw new InvalidDataException('Answer is not valid', $errors);
        }

        // Update Answer with new data
        $this->serializer->deserialize($answerData, $answer);

        // Save to DB
        $this->om->persist($answer);

        if (!$noFlush) {
            $this->om->flush();
        }

        return $answer;
    }
913505
public function validateAnswer($answer, AbstractItem $question, array $options = [])
    {
        $options[Validation::QUESTION] = $question;

        return $this->getAnswerValidator()->validate($answer, $options);
    }
994329
public function askThenRemove(InputInterface $input, OverwritableOutputInterface $output, Question $question)
    {
        // Following suit of ask().
        if (!$input->isInteractive()) {
            return $question->getDefault();
        }

        $this->remove = true;
        $this->question = $question;
        $this->output = $output;
        $this->autocomplete = $this->question->getAutocompleterValues() !== null && $this->hasSttyAvailable();

        $this->output->capture();

        // Wrap normalizer to remove latest question & answer since
        // it is called for each iteration if answer is not valid.
        $normalizer = $question->getNormalizer();
        $question->setNormalizer(function ($value) use ($normalizer) {
            $this->output->remove();
            $this->output->capture();

            if (is_callable($normalizer)) {
                return $normalizer($value);
            }

            return $value;
        });

        try {
            $value = $this->ask($input, $this->output, $question);
        } finally {
            $this->remove = false;
            $this->question = null;
            $this->output->remove();
            $this->output = null;
        }

        return $value;
    }
304569
public function format_answer($answer, $context, $answerformat, $options = []) {
        $answer = file_rewrite_pluginfile_urls($answer, 'pluginfile.php', $context->id,
            'mod_lesson', 'essay_answers', $options->attemptid);
        return parent::format_answer($answer, $context, $answerformat, $options);
    }
223494
private function getCorrectAnswerForRowSumMode(AbstractItem $question, $answer)
    {
        $corrected = new CorrectedAnswer();

        if (!is_null($answer)) {
            // correct answers per row
            for ($i = 0; $i < $question->getRows(); ++$i) {
                // get cells where there is at least 1 expected answer for the current row (none possible)
                $rowCellsUuids = [];

                foreach ($question->getCells() as $cell) {
                    if ($cell->getCoordsY() === $i && $cell->isInput()) {
                        $rowCellsUuids[] = $cell->getUuid();
                    }
                }

                // if any answer is needed in this row
                if (!empty($rowCellsUuids)) {
                    // score will be applied only if all expected answers are there and valid
                    $all = true;

                    foreach ($rowCellsUuids as $expectedCellUuid) {
                        // if $expectedCellUuid found in answers
                        $givenAnwser = array_filter($answer, function ($given) use ($expectedCellUuid) {
                            return $given['cellId'] === $expectedCellUuid;
                        });
                        if (empty($givenAnwser)) {
                            $all = false;
                            break;
                        } else {
                            // check answer
                            $cell = $question->getCell($expectedCellUuid);
                            $currentAnswer = reset($givenAnwser);
                            $choice = $cell->getChoice($currentAnswer['text']);
                            // wrong or empty anwser -> score will not be applied
                            if (empty($choice) || (!empty($choice) && !$choice->isExpected())) {
                                $all = false;
                                break;
                            }
                        }
                    }

                    if ($all) {
                        $scoreToApply = $choice->getScore();
                        $corrected->addExpected(new GenericScore($scoreToApply));
                    } else {
                        $corrected->addPenalty(new GenericPenalty($question->getPenalty()));
                    }
                }
            }
        }

        return $corrected;
    }
561807
protected function make_answer($answer) {
        return new question_answer($answer->id, $answer->answer,
                    $answer->fraction, $answer->feedback, $answer->feedbackformat);
    }
80614
protected function parseAnswerLine(string $answer)
    {
        if (is_null($this->question)) {
            throw new SyntaxException(_('辞書は「Q,」で始めなければなりません。'));
        } elseif ($this->answers) {
            $this->answers .= ",$answer";
        } else {
            $this->answers = $answer;
        }
    }
1087376
private function convertQuestion(Question $question)
    {
        $replies = Collection::make($question->getButtons())->map(function ($button) {
            return array_merge([
                'type' => 'imBack',
                'title' => $button['text'],
                'value' => $button['text'].'<botman value="'.$button['value'].'" />',
            ], $button['additional']);
        });

        return $replies->toArray();
    }