Add data specifc to numeric question types to a translator event.
@param [String => Mixed] $translatorevent
@param PHPObj $questionAttempt
@param PHPObj $question
@return [String => Mixed]
542080
public function numericStatement($translatorevent, $questionAttempt, $question) {

        $translatorevent['interaction_type'] = 'numeric';


        $correctAnswerId = null;
        foreach ($question->answers as $answer) {
            if (intval($answer->fraction) === 1) {
                $correctAnswerId = $answer->id;
            }
        }

        $tolerance = 0;
        $toleranceType = 2;
        $answersdata = [];
        if ($question->qtype == "numerical") {
            $answersdata = $question->numerical->answers;
        } else if (strpos($question->qtype, 'calculated') === 0) {
            $answersdata = $question->calculated->answers;
        }

        if (!is_null($correctAnswerId) && count($answersdata) > 0) {
            foreach ($answersdata as $answerdata) {
                if(isset($answerdata->answer)){
                    if ($answerdata->answer == $correctAnswerId) {
                        $tolerance = floatval($answerdata->tolerance);
                        if (isset($answerdata->tolerancetype)) {
                            $toleranceType = intval($answerdata->tolerancetype);
                        }
                    }
                }
            }
        }

        $rigthtanswer = floatval($questionAttempt->rightanswer);
        if ($tolerance > 0) {
            $toleranceMax = $rigthtanswer + $tolerance;
            $toleranceMin = $rigthtanswer - $tolerance;
            switch ($toleranceType) {
                case 1:
                    $toleranceMax = $rigthtanswer + ($rigthtanswer * $tolerance);
                    $toleranceMin = $rigthtanswer - ($rigthtanswer * $tolerance);
                    break;
                case 3:
                    $toleranceMax = $rigthtanswer + ($rigthtanswer * $tolerance);
                    $toleranceMin = $rigthtanswer / (1 + $tolerance);
                    break;
                default:
                    break;
            }
            $rigthtanswerstring = strval($toleranceMin) . '[:]' . strval($toleranceMax);
            $translatorevent['interaction_correct_responses'] = [$rigthtanswerstring];
        } else {
            $translatorevent['interaction_correct_responses'] = [$questionAttempt->rightanswer];
        }

        return $translatorevent;
    }
1253507
public function import_from_xml($data, $question, qformat_xml $format, $extra=null) {
        $question_type = $data['@']['type'];
        if ($question_type != $this->name()) {
            return false;
        }

        $extraquestionfields = $this->extra_question_fields();
        if (!is_array($extraquestionfields)) {
            return false;
        }

        // Omit table name.
        array_shift($extraquestionfields);
        $qo = $format->import_headers($data);
        $qo->qtype = $question_type;

        foreach ($extraquestionfields as $field) {
            $qo->$field = $format->getpath($data, array('#', $field, 0, '#'), '');
        }

        // Run through the answers.
        $answers = $data['#']['answer'];
        $a_count = 0;
        $extraanswersfields = $this->extra_answer_fields();
        if (is_array($extraanswersfields)) {
            array_shift($extraanswersfields);
        }
        foreach ($answers as $answer) {
            $ans = $format->import_answer($answer);
            if (!$this->has_html_answers()) {
                $qo->answer[$a_count] = $ans->answer['text'];
            } else {
                $qo->answer[$a_count] = $ans->answer;
            }
            $qo->fraction[$a_count] = $ans->fraction;
            $qo->feedback[$a_count] = $ans->feedback;
            if (is_array($extraanswersfields)) {
                foreach ($extraanswersfields as $field) {
                    $qo->{$field}[$a_count] =
                        $format->getpath($answer, array('#', $field, 0, '#'), '');
                }
            }
            ++$a_count;
        }
        return $qo;
    }
971115
private function autocomplete(OutputInterface $output, Question $question, $inputStream, callable $autocomplete): string
    {
        $ret = '';

        $i = 0;
        $ofs = -1;
        $matches = $autocomplete($ret);
        $numMatches = \count($matches);

        $sttyMode = shell_exec('stty -g');

        // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
        shell_exec('stty -icanon -echo');

        // Add highlighted text style
        $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));

        // Read a keypress
        while (!feof($inputStream)) {
            $c = fread($inputStream, 1);

            // as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false.
            if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) {
                shell_exec(sprintf('stty %s', $sttyMode));
                throw new RuntimeException('Aborted.');
            } elseif ("\177" === $c) { // Backspace Character
                if (0 === $numMatches && 0 !== $i) {
                    --$i;
                    // Move cursor backwards
                    $output->write("\033[1D");
                }

                if (0 === $i) {
                    $ofs = -1;
                    $matches = $autocomplete($ret);
                    $numMatches = \count($matches);
                } else {
                    $numMatches = 0;
                }

                // Pop the last character off the end of our string
                $ret = substr($ret, 0, $i);
            } elseif ("\033" === $c) {
                // Did we read an escape sequence?
                $c .= fread($inputStream, 2);

                // A = Up Arrow. B = Down Arrow
                if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
                    if ('A' === $c[2] && -1 === $ofs) {
                        $ofs = 0;
                    }

                    if (0 === $numMatches) {
                        continue;
                    }

                    $ofs += ('A' === $c[2]) ? -1 : 1;
                    $ofs = ($numMatches + $ofs) % $numMatches;
                }
            } elseif (\ord($c) < 32) {
                if ("\t" === $c || "\n" === $c) {
                    if ($numMatches > 0 && -1 !== $ofs) {
                        $ret = (string) $matches[$ofs];
                        // Echo out remaining chars for current match
                        $output->write(substr($ret, $i));
                        $i = \strlen($ret);

                        $matches = array_filter(
                            $autocomplete($ret),
                            function ($match) use ($ret) {
                                return '' === $ret || 0 === strpos($match, $ret);
                            }
                        );
                        $numMatches = \count($matches);
                        $ofs = -1;
                    }

                    if ("\n" === $c) {
                        $output->write($c);
                        break;
                    }
                }

                continue;
            } else {
                if ("\x80" <= $c) {
                    $c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]);
                }

                $output->write($c);
                $ret .= $c;
                ++$i;

                $numMatches = 0;
                $ofs = 0;

                foreach ($autocomplete($ret) as $value) {
                    // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
                    if (0 === strpos($value, $ret)) {
                        $matches[$numMatches++] = $value;
                    }
                }
            }

            // Erase characters from cursor to end of line
            $output->write("\033[K");

            if ($numMatches > 0 && -1 !== $ofs) {
                // Save cursor position
                $output->write("\0337");
                // Write highlighted text
                $output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $i)).'</hl>');
                // Restore cursor position
                $output->write("\0338");
            }
        }

        // Reset stty so it behaves normally again
        shell_exec(sprintf('stty %s', $sttyMode));

        return $ret;
    }
118655
protected final function add_answer($count, $label = null, $required = false, $format= '') {
        if ($label === null) {
            $label = get_string('answer', 'lesson');
        }

        if ($format == LESSON_ANSWER_HTML) {
            $this->_form->addElement('editor', 'answer_editor['.$count.']', $label,
                    array('rows' => '4', 'columns' => '80'),
                    array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
            $this->_form->setType('answer_editor['.$count.']', PARAM_RAW);
            $this->_form->setDefault('answer_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
        } else {
            $this->_form->addElement('text', 'answer_editor['.$count.']', $label,
                    array('size' => '50', 'maxlength' => '200'));
            $this->_form->setType('answer_editor['.$count.']', PARAM_TEXT);
        }

        if ($required) {
            $this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
        }
    }
524314
public static function submit_tags_form($questionid, $contextid, $formdata) {
        global $DB, $CFG;

        $data = [];
        $result = ['status' => false];

        // Parameter validation.
        $params = self::validate_parameters(self::submit_tags_form_parameters(), [
            'questionid' => $questionid,
            'contextid' => $contextid,
            'formdata' => $formdata
        ]);

        $editingcontext = \context::instance_by_id($contextid);
        self::validate_context($editingcontext);
        parse_str($params['formdata'], $data);

        if (!$question = $DB->get_record_sql('
                SELECT q.*, qc.contextid
                FROM {question} q
                JOIN {question_categories} qc ON qc.id = q.category
                WHERE q.id = ?', [$questionid])) {
            print_error('questiondoesnotexist', 'question');
        }

        require_once($CFG->libdir . '/questionlib.php');
        require_once($CFG->dirroot . '/question/type/tags_form.php');

        $cantag = question_has_capability_on($question, 'tag');
        $questioncontext = \context::instance_by_id($question->contextid);
        $contexts = new \question_edit_contexts($editingcontext);

        $formoptions = [
            'editingcontext' => $editingcontext,
            'questioncontext' => $questioncontext,
            'contexts' => $contexts->all()
        ];

        $mform = new \core_question\form\tags(null, $formoptions, 'post', '', null, $cantag, $data);

        if ($validateddata = $mform->get_data()) {
            if ($cantag) {
                if (isset($validateddata->tags)) {
                    // Due to a mform bug, if there's no tags set on the tag element, it submits the name as the value.
                    // The only way to discover is checking if the tag element is an array.
                    $tags = is_array($validateddata->tags) ? $validateddata->tags : [];

                    core_tag_tag::set_item_tags('core_question', 'question', $validateddata->id,
                        $questioncontext, $tags);

                    $result['status'] = true;
                }

                if (isset($validateddata->coursetags)) {
                    $coursetags = is_array($validateddata->coursetags) ? $validateddata->coursetags : [];
                    core_tag_tag::set_item_tags('core_question', 'question', $validateddata->id,
                        $editingcontext->get_course_context(false), $coursetags);

                    $result['status'] = true;
                }
            }
        }

        return $result;
    }
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;
    }
551777
public function process_matching($xml, &$questions) {
        if ($this->getpath($xml, array('POOL', '#', 'QUESTION_MATCH'), false, false)) {
            $matchquestions = $this->getpath($xml,
                    array('POOL', '#', 'QUESTION_MATCH'), false, false);
        } else {
            return;
        }
        // Blackboard questions can't be imported in core Moodle without a loss in data,
        // as core match question don't allow HTML in subanswers. The contributed ddmatch
        // question type support HTML in subanswers.
        // The ddmatch question type is not part of core, so we need to check if it is defined.
        $ddmatchisinstalled = question_bank::is_qtype_installed('ddmatch');

        foreach ($matchquestions as $thisquestion) {

            $question = $this->process_common($thisquestion);
            if ($ddmatchisinstalled) {
                $question->qtype = 'ddmatch';
            } else {
                $question->qtype = 'match';
            }

            $correctfeedback = $this->getpath($thisquestion,
                    array('#', 'GRADABLE', 0, '#', 'FEEDBACK_WHEN_CORRECT', 0, '#'),
                    '', true);
            $incorrectfeedback = $this->getpath($thisquestion,
                    array('#', 'GRADABLE', 0, '#', 'FEEDBACK_WHEN_INCORRECT', 0, '#'),
                    '', true);
            $question->correctfeedback = $this->cleaned_text_field($correctfeedback);
            // As there is no partially correct feedback we use incorrect one.
            $question->partiallycorrectfeedback = $this->cleaned_text_field($incorrectfeedback);
            $question->incorrectfeedback = $this->cleaned_text_field($incorrectfeedback);

            $choices = $this->getpath($thisquestion,
                    array('#', 'CHOICE'), false, false); // Blackboard "choices" are Moodle subanswers.
            $answers = $this->getpath($thisquestion,
                    array('#', 'ANSWER'), false, false); // Blackboard "answers" are Moodle subquestions.
            $correctanswers = $this->getpath($thisquestion,
                    array('#', 'GRADABLE', 0, '#', 'CORRECTANSWER'), false, false); // Mapping between choices and answers.
            $mappings = array();
            foreach ($correctanswers as $correctanswer) {
                if ($correctanswer) {
                    $correctchoiceid = $this->getpath($correctanswer,
                                array('@', 'choice_id'), '', true);
                    $correctanswerid = $this->getpath($correctanswer,
                            array('@', 'answer_id'),
                            '', true);
                    $mappings[$correctanswerid] = $correctchoiceid;
                }
            }

            foreach ($choices as $choice) {
                if ($ddmatchisinstalled) {
                    $choicetext = $this->cleaned_text_field($this->getpath($choice,
                            array('#', 'TEXT', 0, '#'), '', true));
                } else {
                    $choicetext = trim(strip_tags($this->getpath($choice,
                            array('#', 'TEXT', 0, '#'), '', true)));
                }

                if ($choicetext != '') { // Only import non empty subanswers.
                    $subquestion = '';
                    $choiceid = $this->getpath($choice,
                            array('@', 'id'), '', true);
                    $fiber = array_search($choiceid, $mappings);
                    $fiber = array_keys ($mappings, $choiceid);
                    foreach ($fiber as $correctanswerid) {
                        // We have found a correspondance for this choice so we need to take the associated answer.
                        foreach ($answers as $answer) {
                            $currentanswerid = $this->getpath($answer,
                                    array('@', 'id'), '', true);
                            if (strcmp ($currentanswerid, $correctanswerid) == 0) {
                                $subquestion = $this->getpath($answer,
                                        array('#', 'TEXT', 0, '#'), '', true);
                                break;
                            }
                        }
                        $question->subquestions[] = $this->cleaned_text_field($subquestion);
                        $question->subanswers[] = $choicetext;
                    }

                    if ($subquestion == '') { // Then in this case, $choice is a distractor.
                        $question->subquestions[] = $this->text_field('');
                        $question->subanswers[] = $choicetext;
                    }
                }
            }

            // Verify that this matching question has enough subquestions and subanswers.
            $subquestioncount = 0;
            $subanswercount = 0;
            $subanswers = $question->subanswers;
            foreach ($question->subquestions as $key => $subquestion) {
                $subquestion = $subquestion['text'];
                $subanswer = $subanswers[$key];
                if ($subquestion != '') {
                    $subquestioncount++;
                }
                $subanswercount++;
            }
            if ($subquestioncount < 2 || $subanswercount < 3) {
                    $this->error(get_string('notenoughtsubans', 'qformat_blackboard_six', $question->questiontext));
            } else {
                $questions[] = $question;
            }

        }
    }
155960
public function text($name, $question, $required = false)
    {
        if (is_string($question)) {
            output()->write(
                (new Format())
                    ->setString(language()->getLine($question))
                    ->setSpace(1)
            );
        } elseif ($question instanceof Format or $question instanceof Text) {
            output()->write($question);
        }

        $standardInput = input()->standard();

        if ($required === true and empty($standardInput)) {
            $requiredText = (new Format())
                ->setColor((new Color())->setBackground(Color::RED))
                ->setString(' ' . language()->getLine('REQUIRED') . ' ')
                ->setIndent(1)
                ->__toString();

            $this->text($name, str_replace($requiredText, '', $question) . $requiredText, $required);

            return;
        }

        $_POST[ $name ] = $standardInput;
    }
1127179
private function convertQuestion(Question $question)
    {
        $questionData = $question->toArray();

        $buttons = Collection::make($question->getButtons())->map(function ($button) {
            if ($button['type'] === 'select') {
                return $button;
            }

            return array_merge([
                'name' => $button['name'],
                'text' => $button['text'],
                'image_url' => $button['image_url'],
                'type' => $button['type'],
                'value' => $button['value'],
            ], $button['additional']);
        })->toArray();
        $questionData['actions'] = $buttons;

        return $questionData;
    }
267994
private function askForDocument(InputInterface $input, OutputInterface $output, QuestionHelper $dialog)
    {
        do {
            $retry = true;
            $question = new Question($dialog->getQuestion('The Document shortcut name', $input->getOption('document')), $input->getOption('document'));
            $question->setValidator(array(
                'IsmaAmbrosi\Bundle\GeneratorBundle\Command\Validators',
                'validateDocumentName',
            ), $input->getOption('document'));
            $document = $dialog->ask($input, $output, $question);

            list($bundle, $document) = $this->parseShortcutNotation($document);

            try {
                $b = $this->getKernel()->getBundle($bundle);

                if (!file_exists($b->getPath().'/Document/'.str_replace('\\', '/', $document).'.php')) {
                    $retry = false;
                } else {
                    $output->writeln(sprintf('<bg=red>Document "%s:%s" already exists</>.', $bundle, $document));
                }
            } catch (\Exception $e) {
                $output->writeln(sprintf('<bg=red>Bundle "%s" does not exist.</>', $bundle));
            }
        } while ($retry);
        $input->setOption('document', $bundle.':'.$document);

        return array($bundle, $document);
    }
589407
public function preSetData(FormEvent $event)
    {
        try{
            $form = $event->getForm();
            $parentForm = $form->getParent();
            $parentData = $parentForm->getData();

            // First, we get the entity class
            $entityClass = get_class($parentData);

            // Then, we get the field list from the entity class metadata using the annotation reader
            $translatableFields = $this->getTranslatableFields($entityClass);

            //Case where there is data (edit);
            if ($parentData && method_exists($parentData, 'getId') && $parentData->getId()) {

                // We get the entity manager and its translations
                $em = $this->doctrineService->getManagerForClass($entityClass);
                
                if (!$em) {
                    $em = $this->doctrineService->getManager('default');
                }

                $repository = $em->getRepository($this->translation_class);
                $translations = $repository->findTranslations($parentData);

                // Iterating over the enabled locales
                foreach ($this->localeList as $locale) {
                    // Case of the default locale : do not display the form
                    if ($locale != $this->currentLocale) {

                        // We first add the fields without translation
                        $this->addTranslationlessFieldsForLocale($translatableFields, $parentForm, $form, $locale);

                        // If the locale has its translation
                        if (isset ($translations[$locale])) {
                            // then we get its data per field
                            // this way if a field has a translation it will automatically be filled
                            foreach($translations[$locale] as $field => $translation) {
                                if ($parentForm->has($field)) {
                                    // Here we have to first retrieve the field type in the parent form
                                    $fieldType = $parentForm->get($field)->getConfig()->getType()->getInnerType();
                                    // and then set the form type and the data
                                    $fieldAttr = $parentForm->get($field)->getConfig()->getOption('attr');
                                    $form->add(sprintf("%s-%s", $field, $locale), $fieldType, array('data' => $translation, 'required' => false, 'attr' => array_merge($fieldAttr, array('data-field-name' => $field, 'data-locale' => $locale))));
                                }
                            }
                        }
                    }
                }

                // end of the process
                return;
            }

            // Here case where there is an entity but empty one.
            $this->addTranslationlessFields($translatableFields, $parentForm, $form);

        } catch (\Exception $e) {
            // Case of a non entity object given to the parent form.
            // Unstranslatable case, throw exception
            $secondException = new \Exception("The object that was given to the form you wanted to translate isn't an entity one. Untranslatable in this case.", $e->getCode(), $e);
            throw $secondException;
        }
    }
32593
public function hasSameTranslationUnitSource( tao_helpers_translation_TranslationUnit $translationUnit)
    {
        $returnValue = (bool) false;

        
        $returnValue = $this->getSource() == $translationUnit->getSource();
        

        return (bool) $returnValue;
    }
696864
public function askQuestion(InteractiveQuestion $question, $position = null, InputInterface $input = null)
    {
        $text = ($position !== null ? $position .') ' : null) . $question->getFormatedText();

        if ($this->dialogHelper instanceof QuestionHelper) {
            if (!$input) {
                throw new \InvalidArgumentException('With symfony 3, the input stream may not be null');
            }
            $q = new Question($text, $question->getDefault());
            $q->setValidator($question->getValidator());
            if ($question->isHiddenAnswer()) {
                $q->setHidden(true);
            }

            return $this->dialogHelper->ask($input, $this, $q);
        }

        if ($this->dialogHelper instanceof DialogHelper) {

            if ($question->isHiddenAnswer()) {
                return $this->dialogHelper->askHiddenResponseAndValidate($this, $text, $question->getValidator(), false);
            }

            return $this->dialogHelper->askAndValidate($this, $text, $question->getValidator(), false, $question->getDefault());
        }

        throw new \RuntimeException("Invalid dialogHelper");
    }
502981
private function askForDocument(InputInterface $input, OutputInterface $output, QuestionHelper $dialog)
    {
        $question = new Question($dialog->getQuestion('The Document shortcut name', $input->getOption('document')), $input->getOption('document'));
        $question->setValidator(array(
            'IsmaAmbrosi\Bundle\GeneratorBundle\Command\Validators',
            'validateDocumentName',
        ));

        $document = $dialog->ask($input, $output, $question, false, $input->getOption('document'));
        $input->setOption('document', $document);
        list($bundle, $document) = $this->parseShortcutNotation($document);

        return array($document, $bundle);
    }
614620
public function import_match($question) {
        // Get common parts.
        $qo = $this->import_headers($question);

        // Header parts particular to matching.
        $qo->qtype = 'match';
        $qo->shuffleanswers = $this->trans_single($this->getpath($question,
                array('#', 'shuffleanswers', 0, '#'), 1));

        // Run through subquestions.
        $qo->subquestions = array();
        $qo->subanswers = array();
        foreach ($question['#']['subquestion'] as $subqxml) {
            $qo->subquestions[] = $this->import_text_with_files($subqxml,
                    array(), '', $this->get_format($qo->questiontextformat));

            $answers = $this->getpath($subqxml, array('#', 'answer'), array());
            $qo->subanswers[] = $this->getpath($subqxml,
                    array('#', 'answer', 0, '#', 'text', 0, '#'), '', true);
        }

        $this->import_combined_feedback($qo, $question, true);
        $this->import_hints($qo, $question, true, false, $this->get_format($qo->questiontextformat));

        return $qo;
    }
1043561
public function answerQuestion($questionId, $message)
    {
        /** @var QuestionsHandler $handler */
        $handler = $this->requestHandler();
        return $handler->answerQuestion($questionId, $message);
    }
129570
public function hasSameTranslationUnitSubject( tao_helpers_translation_RDFTranslationUnit $translationUnit)
    {
        $returnValue = (bool) false;

        
        $returnValue = $this->getSubject() == $translationUnit->getSubject();
        

        return (bool) $returnValue;
    }