Discards courses that are not yet ready to be used for training or prediction.

@param \core_analytics\analysable $course
@param bool $fortraining
@return true|string
195559
public function is_valid_analysable(\core_analytics\analysable $course, $fortraining = true) {

        if (!$course->was_started()) {
            return get_string('coursenotyetstarted', 'course');
        }

        if (!$this->students = $course->get_students()) {
            return get_string('nocoursestudents', 'course');
        }

        if (!course_format_uses_sections($course->get_course_data()->format)) {
            // We can not split activities in time ranges.
            return get_string('nocoursesections', 'course');
        }

        if ($course->get_end() == 0) {
            // We require time end to be set.
            return get_string('nocourseendtime', 'course');
        }

        if ($course->get_end() < $course->get_start()) {
            return get_string('errorendbeforestart', 'course');
        }

        // A course that lasts longer than 1 year probably have wrong start or end dates.
        if ($course->get_end() - $course->get_start() > (YEARSECS + (WEEKSECS * 4))) {
            return get_string('coursetoolong', 'course');
        }

        // Finished courses can not be used to get predictions.
        if (!$fortraining && $course->is_finished()) {
            return get_string('coursealreadyfinished', 'course');
        }

        if ($fortraining) {
            // Ongoing courses data can not be used to train.
            if (!$course->is_finished()) {
                return get_string('coursenotyetfinished', 'course');
            }
        }

        return true;
    }
449158
public function can_delete_instance($instance) {
        global $DB;

        $context = context_course::instance($instance->courseid);
        if (!has_capability('enrol/category:config', $context)) {
            return false;
        }

        if (!enrol_is_enabled('category')) {
            return true;
        }
        // Allow delete only when no synced users here.
        return !$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id));
    }
419562
public function get_all_samples(\core_analytics\analysable $site) {
        global $DB;

        // Getting courses from DB instead of from the site as these samples
        // will be stored in memory and we just want the id.
        $select = 'id != 1';
        $courses = get_courses('all', 'c.sortorder ASC');
        unset($courses[SITEID]);

        $courseids = array_keys($courses);
        $sampleids = array_combine($courseids, $courseids);

        $courses = array_map(function($course) {
            return array('course' => $course, 'context' => \context_course::instance($course->id));
        }, $courses);

        // No related data attached.
        return array($sampleids, $courses);
    }
503745
public static function get_course_image($course) {
        global $CFG;
        $courseinlist = new \core_course_list_element($course);
        foreach ($courseinlist->get_course_overviewfiles() as $file) {
            if ($file->is_valid_image()) {
                $pathcomponents = [
                    '/pluginfile.php',
                    $file->get_contextid(),
                    $file->get_component(),
                    $file->get_filearea() . $file->get_filepath() . $file->get_filename()
                ];
                $path = implode('/', $pathcomponents);
                return (new moodle_url($path))->out();
            }
        }
        return false;
    }
949453
public function can_delete_full() {
        global $DB;
        if (!$this->id) {
            // Fool-proof.
            return false;
        }

        $context = $this->get_context();
        if (!$this->is_uservisible() ||
                !has_capability('moodle/category:manage', $context)) {
            return false;
        }

        // Check all child categories (not only direct children).
        $sql = context_helper::get_preload_record_columns_sql('ctx');
        $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
            ' FROM {context} ctx '.
            ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
            ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
                array($context->path. '/%', CONTEXT_COURSECAT));
        foreach ($childcategories as $childcat) {
            context_helper::preload_from_record($childcat);
            $childcontext = context_coursecat::instance($childcat->id);
            if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
                    !has_capability('moodle/category:manage', $childcontext)) {
                return false;
            }
        }

        // Check courses.
        $sql = context_helper::get_preload_record_columns_sql('ctx');
        $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
                    $sql. ' FROM {context} ctx '.
                    'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
                array('pathmask' => $context->path. '/%',
                    'courselevel' => CONTEXT_COURSE));
        foreach ($coursescontexts as $ctxrecord) {
            context_helper::preload_from_record($ctxrecord);
            if (!can_delete_course($ctxrecord->courseid)) {
                return false;
            }
        }

        return true;
    }
146594
public function course_updated($inserted, $course, $data) {
        global $DB;

        if ($inserted) {
            if (isset($data->enrol_guest_status_0)) {
                $fields = array('status'=>$data->enrol_guest_status_0);
                if ($fields['status'] == ENROL_INSTANCE_ENABLED) {
                    $fields['password'] = $data->enrol_guest_password_0;
                } else {
                    if ($this->get_config('requirepassword')) {
                        $fields['password'] = generate_password(20);
                    }
                }
                $this->add_instance($course, $fields);
            } else {
                if ($this->get_config('defaultenrol')) {
                    $this->add_default_instance($course);
                }
            }

        } else {
            $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'enrol'=>'guest'));
            foreach ($instances as $instance) {
                $i = $instance->id;

                if (isset($data->{'enrol_guest_status_'.$i})) {
                    $reset = ($instance->status != $data->{'enrol_guest_status_'.$i});

                    $instance->status       = $data->{'enrol_guest_status_'.$i};
                    $instance->timemodified = time();
                    if ($instance->status == ENROL_INSTANCE_ENABLED) {
                        if ($instance->password !== $data->{'enrol_guest_password_'.$i}) {
                            $reset = true;
                        }
                        $instance->password = $data->{'enrol_guest_password_'.$i};
                    }
                    $DB->update_record('enrol', $instance);
                    \core\event\enrol_instance_updated::create_from_record($instance)->trigger();

                    if ($reset) {
                        $context = context_course::instance($course->id);
                        $context->mark_dirty();
                    }
                }
            }
        }
    }
149660
public function delete_instance() {
        global $DB;
        $result = true;

        foreach ($this->submissionplugins as $plugin) {
            if (!$plugin->delete_instance()) {
                print_error($plugin->get_error());
                $result = false;
            }
        }
        foreach ($this->feedbackplugins as $plugin) {
            if (!$plugin->delete_instance()) {
                print_error($plugin->get_error());
                $result = false;
            }
        }

        // Delete files associated with this assignment.
        $fs = get_file_storage();
        if (! $fs->delete_area_files($this->context->id) ) {
            $result = false;
        }

        $this->delete_all_overrides();

        // Delete_records will throw an exception if it fails - so no need for error checking here.
        $DB->delete_records('assign_submission', array('assignment' => $this->get_instance()->id));
        $DB->delete_records('assign_grades', array('assignment' => $this->get_instance()->id));
        $DB->delete_records('assign_plugin_config', array('assignment' => $this->get_instance()->id));
        $DB->delete_records('assign_user_flags', array('assignment' => $this->get_instance()->id));
        $DB->delete_records('assign_user_mapping', array('assignment' => $this->get_instance()->id));

        // Delete items from the gradebook.
        if (! $this->delete_grades()) {
            $result = false;
        }

        // Delete the instance.
        // We must delete the module record after we delete the grade item.
        $DB->delete_records('assign', array('id'=>$this->get_instance()->id));

        return $result;
    }
98095
public function delete_course_completion_data() {
        global $DB;

        $DB->delete_records('course_completions', array('course' => $this->course_id));
        $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));

        // Difficult to find affected users, just purge all completion cache.
        cache::make('core', 'completion')->purge();
        cache::make('core', 'coursecompletion')->purge();
    }
1231306
public function add_instance($course, array $fields = null) {
        global $DB;

        $instanceid = parent::add_instance($course, $fields);

        // Add additional data to our table.
        $data = new stdClass();
        $data->enrolid = $instanceid;
        $data->timecreated = time();
        $data->timemodified = $data->timecreated;
        foreach ($fields as $field => $value) {
            $data->$field = $value;
        }

        $DB->insert_record('enrol_lti_tools', $data);

        return $instanceid;
    }
419971
public static function course_reset_ended($event) {
        if (!empty(self::$resetinprogress)) {
            if (!empty($event->other['reset_options']['reset_groups_remove'])) {
                lesson_process_group_deleted_in_course($event->courseid);
            }
        }

        self::$resetinprogress = null;
    }
2167
public static function delete_all_publications($advertised = true, $shared = true) {
        global $DB;

        if (!$advertised && !$shared) {
            // Nothing to do.
            return true;
        }

        $params = ['huburl' => HUB_MOODLEORGHUBURL];
        if (!$advertised || !$shared) {
            // Retrieve ONLY advertised or ONLY shared.
            $params['enrollable'] = $advertised ? 1 : 0;
        }

        if (!$publications = $DB->get_records('course_published', $params)) {
            // Nothing to unpublish.
            return true;
        }

        foreach ($publications as $publication) {
            $hubcourseids[] = $publication->hubcourseid;
        }

        api::unregister_courses($hubcourseids);

        // Delete the published courses from local db.
        $DB->delete_records('course_published', $params);
        return true;
    }
69605
public function can_delete_instance($instance) {
        $context = context_course::instance($instance->courseid);
        if (!has_capability('enrol/ldap:manage', $context)) {
            return false;
        }

        if (!enrol_is_enabled('ldap')) {
            return true;
        }

        if (!$this->get_config('ldap_host') or !$this->get_config('objectclass') or !$this->get_config('course_idnumber')) {
            return true;
        }

        // TODO: connect to external system and make sure no users are to be enrolled in this course
        return false;
    }
740169
public static function remove_competency_from_course($courseid, $competencyid) {
        $params = self::validate_parameters(self::remove_competency_from_course_parameters(), array(
            'courseid' => $courseid,
            'competencyid' => $competencyid,
        ));
        self::validate_context(context_course::instance($params['courseid']));
        return api::remove_competency_from_course($params['courseid'], $params['competencyid']);
    }
151513
public function fill_per_analysable_caches(\core_analytics\analysable $analysable) {

        // Better to check it, we can not be 100% it will be a \core_analytics\course object.
        if ($analysable instanceof \core_analytics\course) {
            $this->fetch_student_grades($analysable);
        }
    }
38317
public function store_item($course) {
        global $CFG, $DB;

        require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');

        // As far as recycle bin is using MODE_AUTOMATED, it observes the backup_auto_storage
        // setting (storing backups @ real location. For recycle bin we want to ensure that
        // backup files are always stored in Moodle file area. In order to achieve that, we
        // hack the setting here via $CFG->forced_plugin_settings, so it won't interfere other
        // operations.  See MDL-65218 for more information.
        // This hack will be removed once recycle bin switches to use its own backup mode, with
        // own preferences and 100% appart from MODLE_AUTOMATED.
        // TODO: Remove this as part of MDL-65228.
        $CFG->forced_plugin_settings['backup'] = ['backup_auto_storage' => 0];

        // Backup the course.
        $user = get_admin();
        $controller = new \backup_controller(
            \backup::TYPE_1COURSE,
            $course->id,
            \backup::FORMAT_MOODLE,
            \backup::INTERACTIVE_NO,
            \backup::MODE_AUTOMATED,
            $user->id
        );
        $controller->execute_plan();

        // We don't need the forced setting anymore, hence unsetting it.
        // TODO: Remove this as part of MDL-65228.
        unset($CFG->forced_plugin_settings['backup']);

        // Grab the result.
        $result = $controller->get_results();
        if (!isset($result['backup_destination'])) {
            throw new \moodle_exception('Failed to backup activity prior to deletion.');
        }

        // Have finished with the controller, let's destroy it, freeing mem and resources.
        $controller->destroy();

        // Grab the filename.
        $file = $result['backup_destination'];
        if (!$file->get_contenthash()) {
            throw new \moodle_exception('Failed to backup activity prior to deletion (invalid file).');
        }

        // Record the activity, get an ID.
        $item = new \stdClass();
        $item->categoryid = $course->category;
        $item->shortname = $course->shortname;
        $item->fullname = $course->fullname;
        $item->timecreated = time();
        $binid = $DB->insert_record('tool_recyclebin_category', $item);

        // Create the location we want to copy this file to.
        $filerecord = array(
            'contextid' => \context_coursecat::instance($course->category)->id,
            'component' => 'tool_recyclebin',
            'filearea' => TOOL_RECYCLEBIN_COURSECAT_BIN_FILEAREA,
            'itemid' => $binid,
            'timemodified' => time()
        );

        // Move the file to our own special little place.
        $fs = get_file_storage();
        if (!$fs->create_file_from_storedfile($filerecord, $file)) {
            // Failed, cleanup first.
            $DB->delete_records('tool_recyclebin_category', array(
                'id' => $binid
            ));

            throw new \moodle_exception("Failed to copy backup file to recyclebin.");
        }

        // Delete the old file.
        $file->delete();

        // Fire event.
        $event = \tool_recyclebin\event\category_bin_item_created::create(array(
            'objectid' => $binid,
            'context' => \context_coursecat::instance($course->category)
        ));
        $event->trigger();
    }
1241701
protected function delete() {
        global $DB;
        $this->id = $DB->get_field_select('course', 'id', 'shortname = :shortname',
            array('shortname' => $this->shortname), MUST_EXIST);
        return delete_course($this->id, false);
    }
343564
public boolean trainOnCandidates() {

		List<String> corpus = loadTrainingCorpus(_trainingCorpusFile);

		List<List<Acronym>> trainingExtractedCandidates = new ArrayList<List<Acronym>>();

		for (Integer docID = 0; docID < corpus.size(); ++docID) {
			// Adds to training examples, all the extracted pairs from the
			// current document.
			trainingExtractedCandidates.add(extractCandidatePairs(corpus
					.get(docID)));
		}

		return _abbvHmm.train(trainingExtractedCandidates, null, true);
	}