text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

global $CFG;

require_once($CFG->dirroot . '/webservice/tests/helpers.php');

/**
 * External course functions unit tests
 *
 * @package    core_course
 * @category   external
 * @copyright  2012 Jerome Mouneyrac
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class core_course_externallib_testcase extends externallib_advanced_testcase {

    /**
     * Tests set up
     */
    protected function setUp() {
        global $CFG;
        require_once($CFG->dirroot . '/course/externallib.php');
    }

    /**
     * Tidy up open files that may be left open.
     */
    protected function tearDown() {
        gc_collect_cycles();
    }

    /**
     * Test create_categories
     */
    public function test_create_categories() {

        global $DB;

        $this->resetAfterTest(true);

        // Set the required capabilities by the external function
        $contextid = context_system::instance()->id;
        $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);

        // Create base categories.
        $category1 = new stdClass();
        $category1->name = 'Root Test Category 1';
        $category2 = new stdClass();
        $category2->name = 'Root Test Category 2';
        $category2->idnumber = 'rootcattest2';
        $category2->desc = 'Description for root test category 1';
        $category2->theme = 'base';
        $categories = array(
            array('name' => $category1->name, 'parent' => 0),
            array('name' => $category2->name, 'parent' => 0, 'idnumber' => $category2->idnumber,
                'description' => $category2->desc, 'theme' => $category2->theme)
        );

        $createdcats = core_course_external::create_categories($categories);

        // We need to execute the return values cleaning process to simulate the web service server.
        $createdcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdcats);

        // Initially confirm that base data was inserted correctly.
        $this->assertEquals($category1->name, $createdcats[0]['name']);
        $this->assertEquals($category2->name, $createdcats[1]['name']);

        // Save the ids.
        $category1->id = $createdcats[0]['id'];
        $category2->id = $createdcats[1]['id'];

        // Create on sub category.
        $category3 = new stdClass();
        $category3->name = 'Sub Root Test Category 3';
        $subcategories = array(
            array('name' => $category3->name, 'parent' => $category1->id)
        );

        $createdsubcats = core_course_external::create_categories($subcategories);

        // We need to execute the return values cleaning process to simulate the web service server.
        $createdsubcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdsubcats);

        // Confirm that sub categories were inserted correctly.
        $this->assertEquals($category3->name, $createdsubcats[0]['name']);

        // Save the ids.
        $category3->id = $createdsubcats[0]['id'];

        // Calling the ws function should provide a new sortorder to give category1,
        // category2, category3. New course categories are ordered by id not name.
        $category1 = $DB->get_record('course_categories', array('id' => $category1->id));
        $category2 = $DB->get_record('course_categories', array('id' => $category2->id));
        $category3 = $DB->get_record('course_categories', array('id' => $category3->id));

        // sortorder sequence (and sortorder) must be:
        // category 1
        //   category 3
        // category 2
        $this->assertGreaterThan($category1->sortorder, $category3->sortorder);
        $this->assertGreaterThan($category3->sortorder, $category2->sortorder);

        // Call without required capability
        $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
        $this->setExpectedException('required_capability_exception');
        $createdsubcats = core_course_external::create_categories($subcategories);

    }

    /**
     * Test delete categories
     */
    public function test_delete_categories() {
        global $DB;

        $this->resetAfterTest(true);

        // Set the required capabilities by the external function
        $contextid = context_system::instance()->id;
        $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);

        $category1  = self::getDataGenerator()->create_category();
        $category2  = self::getDataGenerator()->create_category(
                array('parent' => $category1->id));
        $category3  = self::getDataGenerator()->create_category();
        $category4  = self::getDataGenerator()->create_category(
                array('parent' => $category3->id));
        $category5  = self::getDataGenerator()->create_category(
                array('parent' => $category4->id));

        //delete category 1 and 2 + delete category 4, category 5 moved under category 3
        core_course_external::delete_categories(array(
            array('id' => $category1->id, 'recursive' => 1),
            array('id' => $category4->id)
        ));

        //check $category 1 and 2 are deleted
        $notdeletedcount = $DB->count_records_select('course_categories',
            'id IN ( ' . $category1->id . ',' . $category2->id . ',' . $category4->id . ')');
        $this->assertEquals(0, $notdeletedcount);

        //check that $category5 as $category3 for parent
        $dbcategory5 = $DB->get_record('course_categories', array('id' => $category5->id));
        $this->assertEquals($dbcategory5->path, $category3->path . '/' . $category5->id);

         // Call without required capability
        $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
        $this->setExpectedException('required_capability_exception');
        $createdsubcats = core_course_external::delete_categories(
                array(array('id' => $category3->id)));
    }

    /**
     * Test get categories
     */
    public function test_get_categories() {
        global $DB;

        $this->resetAfterTest(true);

        $generatedcats = array();
        $category1data['idnumber'] = 'idnumbercat1';
        $category1data['name'] = 'Category 1 for PHPunit test';
        $category1data['description'] = 'Category 1 description';
        $category1data['descriptionformat'] = FORMAT_MOODLE;
        $category1  = self::getDataGenerator()->create_category($category1data);
        $generatedcats[$category1->id] = $category1;
        $category2  = self::getDataGenerator()->create_category(
                array('parent' => $category1->id));
        $generatedcats[$category2->id] = $category2;
        $category6  = self::getDataGenerator()->create_category(
                array('parent' => $category1->id, 'visible' => 0));
        $generatedcats[$category6->id] = $category6;
        $category3  = self::getDataGenerator()->create_category();
        $generatedcats[$category3->id] = $category3;
        $category4  = self::getDataGenerator()->create_category(
                array('parent' => $category3->id));
        $generatedcats[$category4->id] = $category4;
        $category5  = self::getDataGenerator()->create_category(
                array('parent' => $category4->id));
        $generatedcats[$category5->id] = $category5;

        // Set the required capabilities by the external function.
        $context = context_system::instance();
        $roleid = $this->assignUserCapability('moodle/category:manage', $context->id);

        // Retrieve category1 + sub-categories except not visible ones
        $categories = core_course_external::get_categories(array(
            array('key' => 'id', 'value' => $category1->id),
            array('key' => 'visible', 'value' => 1)), 1);

        // We need to execute the return values cleaning process to simulate the web service server.
        $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);

        // Check we retrieve the good total number of categories.
        $this->assertEquals(2, count($categories));

        // Check the return values
        foreach ($categories as $category) {
            $generatedcat = $generatedcats[$category['id']];
            $this->assertEquals($category['idnumber'], $generatedcat->idnumber);
            $this->assertEquals($category['name'], $generatedcat->name);
            // Description was converted to the HTML format.
            $this->assertEquals($category['description'], format_text($generatedcat->description, FORMAT_MOODLE, array('para' => false)));
            $this->assertEquals($category['descriptionformat'], FORMAT_HTML);
        }

        // Check different params.
        $categories = core_course_external::get_categories(array(
            array('key' => 'id', 'value' => $category1->id),
            array('key' => 'idnumber', 'value' => $category1->idnumber),
            array('key' => 'visible', 'value' => 1)), 0);

        // We need to execute the return values cleaning process to simulate the web service server.
        $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);

        $this->assertEquals(1, count($categories));

        // Retrieve categories from parent.
        $categories = core_course_external::get_categories(array(
            array('key' => 'parent', 'value' => $category3->id)), 1);
        $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);

        $this->assertEquals(2, count($categories));

        // Retrieve all categories.
        $categories = core_course_external::get_categories();

        // We need to execute the return values cleaning process to simulate the web service server.
        $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);

        $this->assertEquals($DB->count_records('course_categories'), count($categories));

        // Call without required capability (it will fail cause of the search on idnumber).
        $this->unassignUserCapability('moodle/category:manage', $context->id, $roleid);
        $this->setExpectedException('moodle_exception');
        $categories = core_course_external::get_categories(array(
            array('key' => 'id', 'value' => $category1->id),
            array('key' => 'idnumber', 'value' => $category1->idnumber),
            array('key' => 'visible', 'value' => 1)), 0);
    }

    /**
     * Test update_categories
     */
    public function test_update_categories() {
        global $DB;

        $this->resetAfterTest(true);

        // Set the required capabilities by the external function
        $contextid = context_system::instance()->id;
        $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);

        // Create base categories.
        $category1data['idnumber'] = 'idnumbercat1';
        $category1data['name'] = 'Category 1 for PHPunit test';
        $category1data['description'] = 'Category 1 description';
        $category1data['descriptionformat'] = FORMAT_MOODLE;
        $category1  = self::getDataGenerator()->create_category($category1data);
        $category2  = self::getDataGenerator()->create_category(
                array('parent' => $category1->id));
        $category3  = self::getDataGenerator()->create_category();
        $category4  = self::getDataGenerator()->create_category(
                array('parent' => $category3->id));
        $category5  = self::getDataGenerator()->create_category(
                array('parent' => $category4->id));

        // We update all category1 attribut.
        // Then we move cat4 and cat5 parent: cat3 => cat1
        $categories = array(
            array('id' => $category1->id,
                'name' => $category1->name . '_updated',
                'idnumber' => $category1->idnumber . '_updated',
                'description' => $category1->description . '_updated',
                'descriptionformat' => FORMAT_HTML,
                'theme' => $category1->theme),
            array('id' => $category4->id, 'parent' => $category1->id));

        core_course_external::update_categories($categories);

        // Check the values were updated.
        $dbcategories = $DB->get_records_select('course_categories',
                'id IN (' . $category1->id . ',' . $category2->id . ',' . $category2->id
                . ',' . $category3->id . ',' . $category4->id . ',' . $category5->id .')');
        $this->assertEquals($category1->name . '_updated',
                $dbcategories[$category1->id]->name);
        $this->assertEquals($category1->idnumber . '_updated',
                $dbcategories[$category1->id]->idnumber);
        $this->assertEquals($category1->description . '_updated',
                $dbcategories[$category1->id]->description);
        $this->assertEquals(FORMAT_HTML, $dbcategories[$category1->id]->descriptionformat);

        // Check that category4 and category5 have been properly moved.
        $this->assertEquals('/' . $category1->id . '/' . $category4->id,
                $dbcategories[$category4->id]->path);
        $this->assertEquals('/' . $category1->id . '/' . $category4->id . '/' . $category5->id,
                $dbcategories[$category5->id]->path);

        // Call without required capability.
        $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
        $this->setExpectedException('required_capability_exception');
        core_course_external::update_categories($categories);
    }

    /**
     * Test create_courses
     */
    public function test_create_courses() {
        global $DB;

        $this->resetAfterTest(true);

        // Enable course completion.
        set_config('enablecompletion', 1);
        // Enable course themes.
        set_config('allowcoursethemes', 1);

        // Set the required capabilities by the external function
        $contextid = context_system::instance()->id;
        $roleid = $this->assignUserCapability('moodle/course:create', $contextid);
        $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);

        $category  = self::getDataGenerator()->create_category();

        // Create base categories.
        $course1['fullname'] = 'Test course 1';
        $course1['shortname'] = 'Testcourse1';
        $course1['categoryid'] = $category->id;
        $course2['fullname'] = 'Test course 2';
        $course2['shortname'] = 'Testcourse2';
        $course2['categoryid'] = $category->id;
        $course2['idnumber'] = 'testcourse2idnumber';
        $course2['summary'] = 'Description for course 2';
        $course2['summaryformat'] = FORMAT_MOODLE;
        $course2['format'] = 'weeks';
        $course2['showgrades'] = 1;
        $course2['newsitems'] = 3;
        $course2['startdate'] = 1420092000; // 01/01/2015
        $course2['numsections'] = 4;
        $course2['maxbytes'] = 100000;
        $course2['showreports'] = 1;
        $course2['visible'] = 0;
        $course2['hiddensections'] = 0;
        $course2['groupmode'] = 0;
        $course2['groupmodeforce'] = 0;
        $course2['defaultgroupingid'] = 0;
        $course2['enablecompletion'] = 1;
        $course2['completionnotify'] = 1;
        $course2['lang'] = 'en';
        $course2['forcetheme'] = 'base';
        $course3['fullname'] = 'Test course 3';
        $course3['shortname'] = 'Testcourse3';
        $course3['categoryid'] = $category->id;
        $course3['format'] = 'topics';
        $course3options = array('numsections' => 8,
            'hiddensections' => 1,
            'coursedisplay' => 1);
        $course3['courseformatoptions'] = array();
        foreach ($course3options as $key => $value) {
            $course3['courseformatoptions'][] = array('name' => $key, 'value' => $value);
        }
        $courses = array($course1, $course2, $course3);

        $createdcourses = core_course_external::create_courses($courses);

        // We need to execute the return values cleaning process to simulate the web service server.
        $createdcourses = external_api::clean_returnvalue(core_course_external::create_courses_returns(), $createdcourses);

        // Check that right number of courses were created.
        $this->assertEquals(3, count($createdcourses));

        // Check that the courses were correctly created.
        foreach ($createdcourses as $createdcourse) {
            $courseinfo = course_get_format($createdcourse['id'])->get_course();

            if ($createdcourse['shortname'] == $course2['shortname']) {
                $this->assertEquals($courseinfo->fullname, $course2['fullname']);
                $this->assertEquals($courseinfo->shortname, $course2['shortname']);
                $this->assertEquals($courseinfo->category, $course2['categoryid']);
                $this->assertEquals($courseinfo->idnumber, $course2['idnumber']);
                $this->assertEquals($courseinfo->summary, $course2['summary']);
                $this->assertEquals($courseinfo->summaryformat, $course2['summaryformat']);
                $this->assertEquals($courseinfo->format, $course2['format']);
                $this->assertEquals($courseinfo->showgrades, $course2['showgrades']);
                $this->assertEquals($courseinfo->newsitems, $course2['newsitems']);
                $this->assertEquals($courseinfo->startdate, $course2['startdate']);
                $this->assertEquals($courseinfo->numsections, $course2['numsections']);
                $this->assertEquals($courseinfo->maxbytes, $course2['maxbytes']);
                $this->assertEquals($courseinfo->showreports, $course2['showreports']);
                $this->assertEquals($courseinfo->visible, $course2['visible']);
                $this->assertEquals($courseinfo->hiddensections, $course2['hiddensections']);
                $this->assertEquals($courseinfo->groupmode, $course2['groupmode']);
                $this->assertEquals($courseinfo->groupmodeforce, $course2['groupmodeforce']);
                $this->assertEquals($courseinfo->defaultgroupingid, $course2['defaultgroupingid']);
                $this->assertEquals($courseinfo->completionnotify, $course2['completionnotify']);
                $this->assertEquals($courseinfo->lang, $course2['lang']);
                $this->assertEquals($courseinfo->theme, $course2['forcetheme']);

                // We enabled completion at the beginning of the test.
                $this->assertEquals($courseinfo->enablecompletion, $course2['enablecompletion']);

            } else if ($createdcourse['shortname'] == $course1['shortname']) {
                $courseconfig = get_config('moodlecourse');
                $this->assertEquals($courseinfo->fullname, $course1['fullname']);
                $this->assertEquals($courseinfo->shortname, $course1['shortname']);
                $this->assertEquals($courseinfo->category, $course1['categoryid']);
                $this->assertEquals($courseinfo->summaryformat, FORMAT_HTML);
                $this->assertEquals($courseinfo->format, $courseconfig->format);
                $this->assertEquals($courseinfo->showgrades, $courseconfig->showgrades);
                $this->assertEquals($courseinfo->newsitems, $courseconfig->newsitems);
                $this->assertEquals($courseinfo->maxbytes, $courseconfig->maxbytes);
                $this->assertEquals($courseinfo->showreports, $courseconfig->showreports);
                $this->assertEquals($courseinfo->groupmode, $courseconfig->groupmode);
                $this->assertEquals($courseinfo->groupmodeforce, $courseconfig->groupmodeforce);
                $this->assertEquals($courseinfo->defaultgroupingid, 0);
            } else if ($createdcourse['shortname'] == $course3['shortname']) {
                $this->assertEquals($courseinfo->fullname, $course3['fullname']);
                $this->assertEquals($courseinfo->shortname, $course3['shortname']);
                $this->assertEquals($courseinfo->category, $course3['categoryid']);
                $this->assertEquals($courseinfo->format, $course3['format']);
                $this->assertEquals($courseinfo->hiddensections, $course3options['hiddensections']);
                $this->assertEquals($courseinfo->numsections, $course3options['numsections']);
                $this->assertEquals($courseinfo->coursedisplay, $course3options['coursedisplay']);
            } else {
                throw moodle_exception('Unexpected shortname');
            }
        }

        // Call without required capability
        $this->unassignUserCapability('moodle/course:create', $contextid, $roleid);
        $this->setExpectedException('required_capability_exception');
        $createdsubcats = core_course_external::create_courses($courses);
    }

    /**
     * Test delete_courses
     */
    public function test_delete_courses() {
        global $DB, $USER;

        $this->resetAfterTest(true);

        // Admin can delete a course.
        $this->setAdminUser();
        // Validate_context() will fail as the email is not set by $this->setAdminUser().
        $USER->email = 'emailtopass@example.com';

        $course1  = self::getDataGenerator()->create_course();
        $course2  = self::getDataGenerator()->create_course();
        $course3  = self::getDataGenerator()->create_course();

        // Delete courses.
        $result = core_course_external::delete_courses(array($course1->id, $course2->id));
        $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
        // Check for 0 warnings.
        $this->assertEquals(0, count($result['warnings']));

        // Check $course 1 and 2 are deleted.
        $notdeletedcount = $DB->count_records_select('course',
            'id IN ( ' . $course1->id . ',' . $course2->id . ')');
        $this->assertEquals(0, $notdeletedcount);

        // Try to delete non-existent course.
        $result = core_course_external::delete_courses(array($course1->id));
        $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
        // Check for 1 warnings.
        $this->assertEquals(1, count($result['warnings']));

        // Try to delete Frontpage course.
        $result = core_course_external::delete_courses(array(0));
        $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
        // Check for 1 warnings.
        $this->assertEquals(1, count($result['warnings']));

         // Fail when the user has access to course (enrolled) but does not have permission or is not admin.
        $student1 = self::getDataGenerator()->create_user();
        $studentrole = $DB->get_record('role', array('shortname' => 'student'));
        $this->getDataGenerator()->enrol_user($student1->id,
                                              $course3->id,
                                              $studentrole->id);
        $this->setUser($student1);
        $result = core_course_external::delete_courses(array($course3->id));
        $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
        // Check for 1 warnings.
        $this->assertEquals(1, count($result['warnings']));

         // Fail when the user is not allow to access the course (enrolled) or is not admin.
        $this->setGuestUser();
        $this->setExpectedException('require_login_exception');

        $result = core_course_external::delete_courses(array($course3->id));
        $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
    }

    /**
     * Test get_courses
     */
    public function test_get_courses () {
        global $DB;

        $this->resetAfterTest(true);

        $generatedcourses = array();
        $coursedata['idnumber'] = 'idnumbercourse1';
        $coursedata['fullname'] = 'Course 1 for PHPunit test';
        $coursedata['summary'] = 'Course 1 description';
        $coursedata['summaryformat'] = FORMAT_MOODLE;
        $course1  = self::getDataGenerator()->create_course($coursedata);
        $generatedcourses[$course1->id] = $course1;
        $course2  = self::getDataGenerator()->create_course();
        $generatedcourses[$course2->id] = $course2;
        $course3  = self::getDataGenerator()->create_course(array('format' => 'topics'));
        $generatedcourses[$course3->id] = $course3;

        // Set the required capabilities by the external function.
        $context = context_system::instance();
        $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
        $this->assignUserCapability('moodle/course:update',
                context_course::instance($course1->id)->id, $roleid);
        $this->assignUserCapability('moodle/course:update',
                context_course::instance($course2->id)->id, $roleid);
        $this->assignUserCapability('moodle/course:update',
                context_course::instance($course3->id)->id, $roleid);

        $courses = core_course_external::get_courses(array('ids' =>
            array($course1->id, $course2->id)));

        // We need to execute the return values cleaning process to simulate the web service server.
        $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);

        // Check we retrieve the good total number of categories.
        $this->assertEquals(2, count($courses));

        foreach ($courses as $course) {
            $dbcourse = $generatedcourses[$course['id']];
            $this->assertEquals($course['idnumber'], $dbcourse->idnumber);
            $this->assertEquals($course['fullname'], $dbcourse->fullname);
            // Summary was converted to the HTML format.
            $this->assertEquals($course['summary'], format_text($dbcourse->summary, FORMAT_MOODLE, array('para' => false)));
            $this->assertEquals($course['summaryformat'], FORMAT_HTML);
            $this->assertEquals($course['shortname'], $dbcourse->shortname);
            $this->assertEquals($course['categoryid'], $dbcourse->category);
            $this->assertEquals($course['format'], $dbcourse->format);
            $this->assertEquals($course['showgrades'], $dbcourse->showgrades);
            $this->assertEquals($course['newsitems'], $dbcourse->newsitems);
            $this->assertEquals($course['startdate'], $dbcourse->startdate);
            $this->assertEquals($course['numsections'], $dbcourse->numsections);
            $this->assertEquals($course['maxbytes'], $dbcourse->maxbytes);
            $this->assertEquals($course['showreports'], $dbcourse->showreports);
            $this->assertEquals($course['visible'], $dbcourse->visible);
            $this->assertEquals($course['hiddensections'], $dbcourse->hiddensections);
            $this->assertEquals($course['groupmode'], $dbcourse->groupmode);
            $this->assertEquals($course['groupmodeforce'], $dbcourse->groupmodeforce);
            $this->assertEquals($course['defaultgroupingid'], $dbcourse->defaultgroupingid);
            $this->assertEquals($course['completionnotify'], $dbcourse->completionnotify);
            $this->assertEquals($course['lang'], $dbcourse->lang);
            $this->assertEquals($course['forcetheme'], $dbcourse->theme);
            $this->assertEquals($course['enablecompletion'], $dbcourse->enablecompletion);
            if ($dbcourse->format === 'topics') {
                $this->assertEquals($course['courseformatoptions'], array(
                    array('name' => 'numsections', 'value' => $dbcourse->numsections),
                    array('name' => 'hiddensections', 'value' => $dbcourse->hiddensections),
                    array('name' => 'coursedisplay', 'value' => $dbcourse->coursedisplay),
                ));
            }
        }

        // Get all courses in the DB
        $courses = core_course_external::get_courses(array());

        // We need to execute the return values cleaning process to simulate the web service server.
        $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);

        $this->assertEquals($DB->count_records('course'), count($courses));
    }

    /**
     * Create a course with contents
     * @return array A list with the course object and course modules objects
     */
    private function prepare_get_course_contents_test() {
        $course  = self::getDataGenerator()->create_course();
        $forumdescription = 'This is the forum description';
        $forum = $this->getDataGenerator()->create_module('forum',
            array('course' => $course->id, 'intro' => $forumdescription),
            array('showdescription' => true));
        $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
        $data = $this->getDataGenerator()->create_module('data', array('assessed' => 1, 'scale' => 100, 'course' => $course->id));
        $datacm = get_coursemodule_from_instance('page', $data->id);
        $page = $this->getDataGenerator()->create_module('page', array('course' => $course->id));
        $pagecm = get_coursemodule_from_instance('page', $page->id);
        $labeldescription = 'This is a very long label to test if more than 50 characters are returned.
                So bla bla bla bla <b>bold bold bold</b> bla bla bla bla.';
        $label = $this->getDataGenerator()->create_module('label', array('course' => $course->id,
            'intro' => $labeldescription));
        $labelcm = get_coursemodule_from_instance('label', $label->id);
        $url = $this->getDataGenerator()->create_module('url', array('course' => $course->id,
            'name' => 'URL: % & $ ../', 'section' => 2));
        $urlcm = get_coursemodule_from_instance('url', $url->id);

        // Set the required capabilities by the external function.
        $context = context_course::instance($course->id);
        $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
        $this->assignUserCapability('moodle/course:update', $context->id, $roleid);

        return array($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm);
    }

    /**
     * Test get_course_contents
     */
    public function test_get_course_contents() {
        $this->resetAfterTest(true);

        list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();

        $sections = core_course_external::get_course_contents($course->id, array());
        // We need to execute the return values cleaning process to simulate the web service server.
        $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);

        // Check that forum and label descriptions are correctly returned.
        $firstsection = array_shift($sections);
        $lastsection = array_pop($sections);

        $modinfo = get_fast_modinfo($course);
        $testexecuted = 0;
        foreach ($firstsection['modules'] as $module) {
            if ($module['id'] == $forumcm->id and $module['modname'] == 'forum') {
                $cm = $modinfo->cms[$forumcm->id];
                $formattedtext = format_text($cm->content, FORMAT_HTML,
                    array('noclean' => true, 'para' => false, 'filter' => false));
                $this->assertEquals($formattedtext, $module['description']);
                $this->assertEquals($forumcm->instance, $module['instance']);
                $testexecuted = $testexecuted + 1;
            } else if ($module['id'] == $labelcm->id and $module['modname'] == 'label') {
                $cm = $modinfo->cms[$labelcm->id];
                $formattedtext = format_text($cm->content, FORMAT_HTML,
                    array('noclean' => true, 'para' => false, 'filter' => false));
                $this->assertEquals($formattedtext, $module['description']);
                $this->assertEquals($labelcm->instance, $module['instance']);
                $testexecuted = $testexecuted + 1;
            }
        }
        $this->assertEquals(2, $testexecuted);

        // Check that the only return section has the 5 created modules.
        $this->assertCount(4, $firstsection['modules']);
        $this->assertCount(1, $lastsection['modules']);

        try {
            $sections = core_course_external::get_course_contents($course->id,
                                                                    array(array("name" => "invalid", "value" => 1)));
            $this->fail('Exception expected due to invalid option.');
        } catch (moodle_exception $e) {
            $this->assertEquals('errorinvalidparam', $e->errorcode);
        }
    }

    /**
     * Test get_course_contents excluding modules
     */
    public function test_get_course_contents_excluding_modules() {
        $this->resetAfterTest(true);

        list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();

        // Test exclude modules.
        $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludemodules", "value" => 1)));

        // We need to execute the return values cleaning process to simulate the web service server.
        $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);

        $firstsection = array_shift($sections);
        $lastsection = array_pop($sections);

        $this->assertEmpty($firstsection['modules']);
        $this->assertEmpty($lastsection['modules']);
    }

    /**
     * Test get_course_contents excluding contents
     */
    public function test_get_course_contents_excluding_contents() {
        $this->resetAfterTest(true);

        list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();

        // Test exclude modules.
        $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludecontents", "value" => 1)));

        // We need to execute the return values cleaning process to simulate the web service server.
        $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);

        foreach ($sections as $section) {
            foreach ($section['modules'] as $module) {
                // Only resources return contents.
                if (isset($module['contents'])) {
                    $this->assertEmpty($module['contents']);
                }
            }
        }
    }

    /**
     * Test get_course_contents filtering by section number
     */
    public function test_get_course_contents_section_number() {
        $this->resetAfterTest(true);

        list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();

        // Test exclude modules.
        $sections = core_course_external::get_course_contents($course->id, array(array("name" => "sectionnumber", "value" => 0)));

        // We need to execute the return values cleaning process to simulate the web service server.
        $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);

        $this->assertCount(1, $sections);
        $this->assertCount(4, $sections[0]['modules']);
    }

    /**
     * Test get_course_contents filtering by cmid
     */
    public function test_get_course_contents_cmid() {
        $this->resetAfterTest(true);

        list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();

        // Test exclude modules.
        $sections = core_course_external::get_course_contents($course->id, array(array("name" => "cmid", "value" => $forumcm->id)));

        // We need to execute the return values cleaning process to simulate the web service server.
        $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);

        $this->assertCount(2, $sections);
        $this->assertCount(1, $sections[0]['modules']);
        $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
    }

    /**
     * Test get_course_contents filtering by cmid and section
     */
    public function test_get_course_contents_section_cmid() {
        $this->resetAfterTest(true);

        list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();

        // Test exclude modules.
        $sections = core_course_external::get_course_contents($course->id, array(
                                                                        array("name" => "cmid", "value" => $forumcm->id),
                                                                        array("name" => "sectionnumber", "value" => 0)
                                                                        ));

        // We need to execute the return values cleaning process to simulate the web service server.
        $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);

        $this->assertCount(1, $sections);
        $this->assertCount(1, $sections[0]['modules']);
        $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
    }

    /**
     * Test get_course_contents filtering by modname
     */
    public function test_get_course_contents_modname() {
        $this->resetAfterTest(true);

        list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();

        // Test exclude modules.
        $sections = core_course_external::get_course_contents($course->id, array(array("name" => "modname", "value" => "forum")));

        // We need to execute the return values cleaning process to simulate the web service server.
        $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);

        $this->assertCount(2, $sections);
        $this->assertCount(1, $sections[0]['modules']);
        $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
    }

    /**
     * Test get_course_contents filtering by modname
     */
    public function test_get_course_contents_modid() {
        $this->resetAfterTest(true);

        list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();

        // Test exclude modules.
        $sections = core_course_external::get_course_contents($course->id, array(
                                                                            array("name" => "modname", "value" => "page"),
                                                                            array("name" => "modid", "value" => $pagecm->instance),
                                                                            ));

        // We need to execute the return values cleaning process to simulate the web service server.
        $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);

        $this->assertCount(2, $sections);
        $this->assertCount(1, $sections[0]['modules']);
        $this->assertEquals("page", $sections[0]['modules'][0]["modname"]);
        $this->assertEquals($pagecm->instance, $sections[0]['modules'][0]["instance"]);
    }

    /**
     * Test duplicate_course
     */
    public function test_duplicate_course() {
        $this->resetAfterTest(true);

        // Create one course with three modules.
        $course  = self::getDataGenerator()->create_course();
        $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
        $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
        $forumcontext = context_module::instance($forum->cmid);
        $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
        $datacontext = context_module::instance($data->cmid);
        $datacm = get_coursemodule_from_instance('page', $data->id);
        $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
        $pagecontext = context_module::instance($page->cmid);
        $pagecm = get_coursemodule_from_instance('page', $page->id);

        // Set the required capabilities by the external function.
        $coursecontext = context_course::instance($course->id);
        $categorycontext = context_coursecat::instance($course->category);
        $roleid = $this->assignUserCapability('moodle/course:create', $categorycontext->id);
        $this->assignUserCapability('moodle/course:view', $categorycontext->id, $roleid);
        $this->assignUserCapability('moodle/restore:restorecourse', $categorycontext->id, $roleid);
        $this->assignUserCapability('moodle/backup:backupcourse', $coursecontext->id, $roleid);
        $this->assignUserCapability('moodle/backup:configure', $coursecontext->id, $roleid);
        // Optional capabilities to copy user data.
        $this->assignUserCapability('moodle/backup:userinfo', $coursecontext->id, $roleid);
        $this->assignUserCapability('moodle/restore:userinfo', $categorycontext->id, $roleid);

        $newcourse['fullname'] = 'Course duplicate';
        $newcourse['shortname'] = 'courseduplicate';
        $newcourse['categoryid'] = $course->category;
        $newcourse['visible'] = true;
        $newcourse['options'][] = array('name' => 'users', 'value' => true);

        $duplicate = core_course_external::duplicate_course($course->id, $newcourse['fullname'],
                $newcourse['shortname'], $newcourse['categoryid'], $newcourse['visible'], $newcourse['options']);

        // We need to execute the return values cleaning process to simulate the web service server.
        $duplicate = external_api::clean_returnvalue(core_course_external::duplicate_course_returns(), $duplicate);

        // Check that the course has been duplicated.
        $this->assertEquals($newcourse['shortname'], $duplicate['shortname']);
    }

    /**
     * Test update_courses
     */
    public function test_update_courses() {
        global $DB, $CFG, $USER, $COURSE;

        // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this
        // trick because we are both updating and getting (for testing) course information
        // in the same request and core_course_external::update_courses()
        // is overwriting $COURSE all over the time with OLD values, so later
        // use of get_course() fetches those OLD values instead of the updated ones.
        // See MDL-39723 for more info.
        $origcourse = clone($COURSE);

        $this->resetAfterTest(true);

        // Set the required capabilities by the external function.
        $contextid = context_system::instance()->id;
        $roleid = $this->assignUserCapability('moodle/course:update', $contextid);
        $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
        $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
        $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
        $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
        $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
        $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
        $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid);

        // Create category and course.
        $category1  = self::getDataGenerator()->create_category();
        $category2  = self::getDataGenerator()->create_category();
        $originalcourse1 = self::getDataGenerator()->create_course();
        self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid);
        $originalcourse2 = self::getDataGenerator()->create_course();
        self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid);

        // Course values to be updated.
        $course1['id'] = $originalcourse1->id;
        $course1['fullname'] = 'Updated test course 1';
        $course1['shortname'] = 'Udestedtestcourse1';
        $course1['categoryid'] = $category1->id;
        $course2['id'] = $originalcourse2->id;
        $course2['fullname'] = 'Updated test course 2';
        $course2['shortname'] = 'Updestedtestcourse2';
        $course2['categoryid'] = $category2->id;
        $course2['idnumber'] = 'Updatedidnumber2';
        $course2['summary'] = 'Updaated description for course 2';
        $course2['summaryformat'] = FORMAT_HTML;
        $course2['format'] = 'topics';
        $course2['showgrades'] = 1;
        $course2['newsitems'] = 3;
        $course2['startdate'] = 1420092000; // 01/01/2015.
        $course2['numsections'] = 4;
        $course2['maxbytes'] = 100000;
        $course2['showreports'] = 1;
        $course2['visible'] = 0;
        $course2['hiddensections'] = 0;
        $course2['groupmode'] = 0;
        $course2['groupmodeforce'] = 0;
        $course2['defaultgroupingid'] = 0;
        $course2['enablecompletion'] = 1;
        $course2['lang'] = 'en';
        $course2['forcetheme'] = 'base';
        $courses = array($course1, $course2);

        $updatedcoursewarnings = core_course_external::update_courses($courses);
        $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
                                                                    $updatedcoursewarnings);
        $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line.

        // Check that right number of courses were created.
        $this->assertEquals(0, count($updatedcoursewarnings['warnings']));

        // Check that the courses were correctly created.
        foreach ($courses as $course) {
            $courseinfo = course_get_format($course['id'])->get_course();
            if ($course['id'] == $course2['id']) {
                $this->assertEquals($course2['fullname'], $courseinfo->fullname);
                $this->assertEquals($course2['shortname'], $courseinfo->shortname);
                $this->assertEquals($course2['categoryid'], $courseinfo->category);
                $this->assertEquals($course2['idnumber'], $courseinfo->idnumber);
                $this->assertEquals($course2['summary'], $courseinfo->summary);
                $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat);
                $this->assertEquals($course2['format'], $courseinfo->format);
                $this->assertEquals($course2['showgrades'], $courseinfo->showgrades);
                $this->assertEquals($course2['newsitems'], $courseinfo->newsitems);
                $this->assertEquals($course2['startdate'], $courseinfo->startdate);
                $this->assertEquals($course2['numsections'], $courseinfo->numsections);
                $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes);
                $this->assertEquals($course2['showreports'], $courseinfo->showreports);
                $this->assertEquals($course2['visible'], $courseinfo->visible);
                $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections);
                $this->assertEquals($course2['groupmode'], $courseinfo->groupmode);
                $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce);
                $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid);
                $this->assertEquals($course2['lang'], $courseinfo->lang);

                if (!empty($CFG->allowcoursethemes)) {
                    $this->assertEquals($course2['forcetheme'], $courseinfo->theme);
                }

                if (completion_info::is_enabled_for_site()) {
                    $this->assertEquals($course2['enabledcompletion'], $courseinfo->enablecompletion);
                }
            } else if ($course['id'] == $course1['id']) {
                $this->assertEquals($course1['fullname'], $courseinfo->fullname);
                $this->assertEquals($course1['shortname'], $courseinfo->shortname);
                $this->assertEquals($course1['categoryid'], $courseinfo->category);
                $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
                $this->assertEquals('topics', $courseinfo->format);
                $this->assertEquals(5, $courseinfo->numsections);
                $this->assertEquals(0, $courseinfo->newsitems);
                $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
            } else {
                throw moodle_exception('Unexpected shortname');
            }
        }

        $courses = array($course1);
        // Try update course without update capability.
        $user = self::getDataGenerator()->create_user();
        $this->setUser($user);
        $this->unassignUserCapability('moodle/course:update', $contextid, $roleid);
        self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
        $updatedcoursewarnings = core_course_external::update_courses($courses);
        $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
                                                                    $updatedcoursewarnings);
        $this->assertEquals(1, count($updatedcoursewarnings['warnings']));

        // Try update course category without capability.
        $this->assignUserCapability('moodle/course:update', $contextid, $roleid);
        $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid);
        $user = self::getDataGenerator()->create_user();
        $this->setUser($user);
        self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
        $course1['categoryid'] = $category2->id;
        $courses = array($course1);
        $updatedcoursewarnings = core_course_external::update_courses($courses);
        $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
                                                                    $updatedcoursewarnings);
        $this->assertEquals(1, count($updatedcoursewarnings['warnings']));

        // Try update course fullname without capability.
        $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
        $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid);
        $user = self::getDataGenerator()->create_user();
        $this->setUser($user);
        self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
        $updatedcoursewarnings = core_course_external::update_courses($courses);
        $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
                                                                    $updatedcoursewarnings);
        $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
        $course1['fullname'] = 'Testing fullname without permission';
        $courses = array($course1);
        $updatedcoursewarnings = core_course_external::update_courses($courses);
        $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
                                                                    $updatedcoursewarnings);
        $this->assertEquals(1, count($updatedcoursewarnings['warnings']));

        // Try update course shortname without capability.
        $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
        $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
        $user = self::getDataGenerator()->create_user();
        $this->setUser($user);
        self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
        $updatedcoursewarnings = core_course_external::update_courses($courses);
        $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
                                                                    $updatedcoursewarnings);
        $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
        $course1['shortname'] = 'Testing shortname without permission';
        $courses = array($course1);
        $updatedcoursewarnings = core_course_external::update_courses($courses);
        $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
                                                                    $updatedcoursewarnings);
        $this->assertEquals(1, count($updatedcoursewarnings['warnings']));

        // Try update course idnumber without capability.
        $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
        $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
        $user = self::getDataGenerator()->create_user();
        $this->setUser($user);
        self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
        $updatedcoursewarnings = core_course_external::update_courses($courses);
        $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
                                                                    $updatedcoursewarnings);
        $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
        $course1['idnumber'] = 'NEWIDNUMBER';
        $courses = array($course1);
        $updatedcoursewarnings = core_course_external::update_courses($courses);
        $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
                                                                    $updatedcoursewarnings);
        $this->assertEquals(1, count($updatedcoursewarnings['warnings']));

        // Try update course summary without capability.
        $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
        $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid);
        $user = self::getDataGenerator()->create_user();
        $this->setUser($user);
        self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
        $updatedcoursewarnings = core_course_external::update_courses($courses);
        $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
                                                                    $updatedcoursewarnings);
        $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
        $course1['summary'] = 'New summary';
        $courses = array($course1);
        $updatedcoursewarnings = core_course_external::update_courses($courses);
        $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
                                                                    $updatedcoursewarnings);
        $this->assertEquals(1, count($updatedcoursewarnings['warnings']));

        // Try update course with invalid summary format.
        $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
        $user = self::getDataGenerator()->create_user();
        $this->setUser($user);
        self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
        $updatedcoursewarnings = core_course_external::update_courses($courses);
        $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
                                                                    $updatedcoursewarnings);
        $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
        $course1['summaryformat'] = 10;
        $courses = array($course1);
        $updatedcoursewarnings = core_course_external::update_courses($courses);
        $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
                                                                    $updatedcoursewarnings);
        $this->assertEquals(1, count($updatedcoursewarnings['warnings']));

        // Try update course visibility without capability.
        $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid);
        $user = self::getDataGenerator()->create_user();
        $this->setUser($user);
        self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
        $course1['summaryformat'] = FORMAT_MOODLE;
        $courses = array($course1);
        $updatedcoursewarnings = core_course_external::update_courses($courses);
        $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
                                                                    $updatedcoursewarnings);
        $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
        $course1['visible'] = 0;
        $courses = array($course1);
        $updatedcoursewarnings = core_course_external::update_courses($courses);
        $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
                                                                    $updatedcoursewarnings);
        $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
    }

    /**
     * Test delete course_module.
     */
    public function test_delete_modules() {
        global $DB;

        // Ensure we reset the data after this test.
        $this->resetAfterTest(true);

        // Create a user.
        $user = self::getDataGenerator()->create_user();

        // Set the tests to run as the user.
        self::setUser($user);

        // Create a course to add the modules.
        $course = self::getDataGenerator()->create_course();

        // Create two test modules.
        $record = new stdClass();
        $record->course = $course->id;
        $module1 = self::getDataGenerator()->create_module('forum', $record);
        $module2 = self::getDataGenerator()->create_module('assign', $record);

        // Check the forum was correctly created.
        $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));

        // Check the assignment was correctly created.
        $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));

        // Check data exists in the course modules table.
        $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
                array('module1' => $module1->cmid, 'module2' => $module2->cmid)));

        // Enrol the user in the course.
        $enrol = enrol_get_plugin('manual');
        $enrolinstances = enrol_get_instances($course->id, true);
        foreach ($enrolinstances as $courseenrolinstance) {
            if ($courseenrolinstance->enrol == "manual") {
                $instance = $courseenrolinstance;
                break;
            }
        }
        $enrol->enrol_user($instance, $user->id);

        // Assign capabilities to delete module 1.
        $modcontext = context_module::instance($module1->cmid);
        $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);

        // Assign capabilities to delete module 2.
        $modcontext = context_module::instance($module2->cmid);
        $newrole = create_role('Role 2', 'role2', 'Role 2 description');
        $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);

        // Deleting these module instances.
        core_course_external::delete_modules(array($module1->cmid, $module2->cmid));

        // Check the forum was deleted.
        $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));

        // Check the assignment was deleted.
        $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));

        // Check we retrieve no data in the course modules table.
        $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
                array('module1' => $module1->cmid, 'module2' => $module2->cmid)));

        // Call with non-existent course module id and ensure exception thrown.
        try {
            core_course_external::delete_modules(array('1337'));
            $this->fail('Exception expected due to missing course module.');
        } catch (dml_missing_record_exception $e) {
            $this->assertEquals('invalidcoursemodule', $e->errorcode);
        }

        // Create two modules.
        $module1 = self::getDataGenerator()->create_module('forum', $record);
        $module2 = self::getDataGenerator()->create_module('assign', $record);

        // Since these modules were recreated the user will not have capabilities
        // to delete them, ensure exception is thrown if they try.
        try {
            core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
            $this->fail('Exception expected due to missing capability.');
        } catch (moodle_exception $e) {
            $this->assertEquals('nopermissions', $e->errorcode);
        }

        // Unenrol user from the course.
        $enrol->unenrol_user($instance, $user->id);

        // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
        try {
            core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
            $this->fail('Exception expected due to being unenrolled from the course.');
        } catch (moodle_exception $e) {
            $this->assertEquals('requireloginerror', $e->errorcode);
        }
    }

    /**
     * Test import_course into an empty course
     */
    public function test_import_course_empty() {
        global $USER;

        $this->resetAfterTest(true);

        $course1  = self::getDataGenerator()->create_course();
        $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id, 'name' => 'Forum test'));
        $page = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'name' => 'Page test'));

        $course2  = self::getDataGenerator()->create_course();

        $course1cms = get_fast_modinfo($course1->id)->get_cms();
        $course2cms = get_fast_modinfo($course2->id)->get_cms();

        // Verify the state of the courses before we do the import.
        $this->assertCount(2, $course1cms);
        $this->assertEmpty($course2cms);

        // Setup the user to run the operation (ugly hack because validate_context() will
        // fail as the email is not set by $this->setAdminUser()).
        $this->setAdminUser();
        $USER->email = 'emailtopass@example.com';

        // Import from course1 to course2.
        core_course_external::import_course($course1->id, $course2->id, 0);

        // Verify that now we have two modules in both courses.
        $course1cms = get_fast_modinfo($course1->id)->get_cms();
        $course2cms = get_fast_modinfo($course2->id)->get_cms();
        $this->assertCount(2, $course1cms);
        $this->assertCount(2, $course2cms);

        // Verify that the names transfered across correctly.
        foreach ($course2cms as $cm) {
            if ($cm->modname === 'page') {
                $this->assertEquals($cm->name, $page->name);
            } else if ($cm->modname === 'forum') {
                $this->assertEquals($cm->name, $forum->name);
            } else {
                $this->fail('Unknown CM found.');
            }
        }
    }

    /**
     * Test import_course into an filled course
     */
    public function test_import_course_filled() {
        global $USER;

        $this->resetAfterTest(true);

        // Add forum and page to course1.
        $course1  = self::getDataGenerator()->create_course();
        $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
        $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));

        // Add quiz to course 2.
        $course2  = self::getDataGenerator()->create_course();
        $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));

        $course1cms = get_fast_modinfo($course1->id)->get_cms();
        $course2cms = get_fast_modinfo($course2->id)->get_cms();

        // Verify the state of the courses before we do the import.
        $this->assertCount(2, $course1cms);
        $this->assertCount(1, $course2cms);

        // Setup the user to run the operation (ugly hack because validate_context() will
        // fail as the email is not set by $this->setAdminUser()).
        $this->setAdminUser();
        $USER->email = 'emailtopass@example.com';

        // Import from course1 to course2 without deleting content.
        core_course_external::import_course($course1->id, $course2->id, 0);

        $course2cms = get_fast_modinfo($course2->id)->get_cms();

        // Verify that now we have three modules in course2.
        $this->assertCount(3, $course2cms);

        // Verify that the names transfered across correctly.
        foreach ($course2cms as $cm) {
            if ($cm->modname === 'page') {
                $this->assertEquals($cm->name, $page->name);
            } else if ($cm->modname === 'forum') {
                $this->assertEquals($cm->name, $forum->name);
            } else if ($cm->modname === 'quiz') {
                $this->assertEquals($cm->name, $quiz->name);
            } else {
                $this->fail('Unknown CM found.');
            }
        }
    }

    /**
     * Test import_course with only blocks set to backup
     */
    public function test_import_course_blocksonly() {
        global $USER, $DB;

        $this->resetAfterTest(true);

        // Add forum and page to course1.
        $course1  = self::getDataGenerator()->create_course();
        $course1ctx = context_course::instance($course1->id);
        $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
        $block = $this->getDataGenerator()->create_block('online_users', array('parentcontextid' => $course1ctx->id));

        $course2  = self::getDataGenerator()->create_course();
        $course2ctx = context_course::instance($course2->id);
        $initialblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
        $initialcmcount = count(get_fast_modinfo($course2->id)->get_cms());

        // Setup the user to run the operation (ugly hack because validate_context() will
        // fail as the email is not set by $this->setAdminUser()).
        $this->setAdminUser();
        $USER->email = 'emailtopass@example.com';

        // Import from course1 to course2 without deleting content, but excluding
        // activities.
        $options = array(
            array('name' => 'activities', 'value' => 0),
            array('name' => 'blocks', 'value' => 1),
            array('name' => 'filters', 'value' => 0),
        );

        core_course_external::import_course($course1->id, $course2->id, 0, $options);

        $newcmcount = count(get_fast_modinfo($course2->id)->get_cms());
        $newblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
        // Check that course modules haven't changed, but that blocks have.
        $this->assertEquals($initialcmcount, $newcmcount);
        $this->assertEquals(($initialblockcount + 1), $newblockcount);
    }

    /**
     * Test import_course into an filled course, deleting content.
     */
    public function test_import_course_deletecontent() {
        global $USER;
        $this->resetAfterTest(true);

        // Add forum and page to course1.
        $course1  = self::getDataGenerator()->create_course();
        $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
        $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));

        // Add quiz to course 2.
        $course2  = self::getDataGenerator()->create_course();
        $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));

        $course1cms = get_fast_modinfo($course1->id)->get_cms();
        $course2cms = get_fast_modinfo($course2->id)->get_cms();

        // Verify the state of the courses before we do the import.
        $this->assertCount(2, $course1cms);
        $this->assertCount(1, $course2cms);

        // Setup the user to run the operation (ugly hack because validate_context() will
        // fail as the email is not set by $this->setAdminUser()).
        $this->setAdminUser();
        $USER->email = 'emailtopass@example.com';

        // Import from course1 to course2,  deleting content.
        core_course_external::import_course($course1->id, $course2->id, 1);

        $course2cms = get_fast_modinfo($course2->id)->get_cms();

        // Verify that now we have two modules in course2.
        $this->assertCount(2, $course2cms);

        // Verify that the course only contains the imported modules.
        foreach ($course2cms as $cm) {
            if ($cm->modname === 'page') {
                $this->assertEquals($cm->name, $page->name);
            } else if ($cm->modname === 'forum') {
                $this->assertEquals($cm->name, $forum->name);
            } else {
                $this->fail('Unknown CM found: '.$cm->name);
            }
        }
    }

    /**
     * Ensure import_course handles incorrect deletecontent option correctly.
     */
    public function test_import_course_invalid_deletecontent_option() {
        $this->resetAfterTest(true);

        $course1  = self::getDataGenerator()->create_course();
        $course2  = self::getDataGenerator()->create_course();

        $this->setExpectedException('moodle_exception', get_string('invalidextparam', 'webservice', -1));
        // Import from course1 to course2, with invalid option
        core_course_external::import_course($course1->id, $course2->id, -1);;
    }

    /**
     * Test view_course function
     */
    public function test_view_course() {

        $this->resetAfterTest();

        // Course without sections.
        $course = $this->getDataGenerator()->create_course(array('numsections' => 5), array('createsections' => true));
        $this->setAdminUser();

        // Redirect events to the sink, so we can recover them later.
        $sink = $this->redirectEvents();

        $result = core_course_external::view_course($course->id, 1);
        $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
        $events = $sink->get_events();
        $event = reset($events);

        // Check the event details are correct.
        $this->assertInstanceOf('\core\event\course_viewed', $event);
        $this->assertEquals(context_course::instance($course->id), $event->get_context());
        $this->assertEquals(1, $event->other['coursesectionnumber']);

        $result = core_course_external::view_course($course->id);
        $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
        $events = $sink->get_events();
        $event = array_pop($events);
        $sink->close();

        // Check the event details are correct.
        $this->assertInstanceOf('\core\event\course_viewed', $event);
        $this->assertEquals(context_course::instance($course->id), $event->get_context());
        $this->assertEmpty($event->other);

    }
}


text:
package com.meancat.usefully.messaging.mapping;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;

import com.meancat.usefully.messaging.messages.Message;

/**
 * A Mapping of all Handlers that are in TARGET_CLASS and are notated by MESSAGE_ANNOTATION
 */
public abstract class ClassMessageHandlerMapping<TARGET_CLASS, MESSAGE_ANNOTATION extends Annotation> {
    private static final Logger logger = LoggerFactory.getLogger(ClassMessageHandlerMapping.class);

    protected Map<Class<?>, Method> classMappings = new HashMap<>();

    protected abstract Class<TARGET_CLASS> getTargetClass();
    protected abstract Class<MESSAGE_ANNOTATION> getHandlerAnnotationClass();

    protected ClassMessageHandlerMapping() {
        for (Method method : getTargetClass().getMethods()) {
            MESSAGE_ANNOTATION mapping = AnnotationUtils.findAnnotation(method, getHandlerAnnotationClass());
            if (mapping != null) {
                Class<?>[] paramTypes = method.getParameterTypes();
                if (paramTypes != null && paramTypes.length > 0) {
                    Class<?> mappingKey = paramTypes[paramTypes.length - 1];
                    String msgType = mappingKey.getSimpleName();
                    logger.debug("Mapping '{}'.'{}' with type {}",
                            getTargetClass().getSimpleName(),
                            method.getName(),
                            msgType);
                    classMappings.put(mappingKey, method);
                }
            }
        }
    }

    public Method getMapping(Message message) {
        return classMappings.get(message.getPayloadClass());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.ctrip.zeus.dao.mapper;

import com.ctrip.zeus.dao.entity.NginxConfSlb;
import com.ctrip.zeus.dao.entity.NginxConfSlbExample;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface NginxConfSlbMapper {
    long countByExample(NginxConfSlbExample example);

    int deleteByExample(NginxConfSlbExample example);

    int deleteByPrimaryKey(Long id);

    int insert(NginxConfSlb record);

    int insertSelective(NginxConfSlb record);

    NginxConfSlb selectOneByExample(NginxConfSlbExample example);

    NginxConfSlb selectOneByExampleSelective(@Param("example") NginxConfSlbExample example, @Param("selective") NginxConfSlb.Column ... selective);

    NginxConfSlb selectOneByExampleWithBLOBs(NginxConfSlbExample example);

    List<NginxConfSlb> selectByExampleSelective(@Param("example") NginxConfSlbExample example, @Param("selective") NginxConfSlb.Column ... selective);

    List<NginxConfSlb> selectByExampleWithBLOBs(NginxConfSlbExample example);

    List<NginxConfSlb> selectByExample(NginxConfSlbExample example);

    NginxConfSlb selectByPrimaryKeySelective(@Param("id") Long id, @Param("selective") NginxConfSlb.Column ... selective);

    NginxConfSlb selectByPrimaryKey(Long id);

    int updateByExampleSelective(@Param("record") NginxConfSlb record, @Param("example") NginxConfSlbExample example);

    int updateByExampleWithBLOBs(@Param("record") NginxConfSlb record, @Param("example") NginxConfSlbExample example);

    int updateByExample(@Param("record") NginxConfSlb record, @Param("example") NginxConfSlbExample example);

    int updateByPrimaryKeySelective(NginxConfSlb record);

    int updateByPrimaryKeyWithBLOBs(NginxConfSlb record);

    int updateByPrimaryKey(NginxConfSlb record);

    int upsert(NginxConfSlb record);

    int upsertSelective(NginxConfSlb record);

    int upsertWithBLOBs(NginxConfSlb record);
}


text:
const babel = require('babel-core');
const debug = require('debug')('fain:frctl-react-adapter');
const Adapter = require('@frctl/fractal').Adapter;
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const vm = require('vm');

const processSass = require('./processSass');
const { cleanFilepath } = require('./utils');

let componentStyle = '';
const babelOptions = {
  babelrc: false,
  plugins: [
    [require.resolve('babel-plugin-css-modules-transform'), {
      camelCase: true,
      devMode: true,
      extensions: ['.scss'],
      preprocessCss: processSass,
      processCss(css, filepath) {
        debug(`BABEL CSS ${cleanFilepath(filepath)}`);
        componentStyle = `${componentStyle}\n${css}`;
      }
    }]
  ],
  presets: [
    require.resolve('babel-preset-env'),
    require.resolve('babel-preset-react')
  ]
};

function compile(code) {
  // after first compilation, require will be hooked to use babel
  // because it is shared with the vm
  const result = babel.transform(code, babelOptions);
  return result.code;
}

function getSandbox() {
  return {
    exports: {},
    process: { env: { BABEL_DISABLE_CACHE: 1, NODE_ENV: 'production' } },
    require,
    window: { navigator: { userAgent: 'Node' } }
  };
}

function clearRequireCache() {
  debug(Object.keys(require.cache).filter(id => !/node_modules/.test(id)));
  Object.keys(require.cache)
    .filter(id => /packages\/fain\/(?!node_modules)/.test(id))
    .forEach(id => delete require.cache[id]);
}

function compileComponent(tplPath, tplCode) {
  clearRequireCache();
  debug(`COMPILE: ${cleanFilepath(tplPath)}`);
  componentStyle = '';
  const sandbox = getSandbox();
  vm.runInNewContext(`${compile(tplCode)}`, sandbox);
  const Component = sandbox.exports.default;
  Component.style = componentStyle;
  return Component;
}

class ReactAdapter extends Adapter {
  constructor(engineName, instance, source, app) {
    super(instance, source);
    this.fractal = app;
    this.engineName = engineName;
    this.instance = instance;
    this.source = source;
    this.cache = {};
  }

  render(tplPath, tplCode, tplContext, meta) {
    debug(`RENDERING: ${cleanFilepath(tplPath)}`);

    try {
      const Component = compileComponent(tplPath, tplCode);
      const { engineName, fractal, instance, source } = this;
      const props = Object.assign({},
        { engineName, fractal, instance, source, filePath: tplPath, meta },
        { style: Component.style },
        tplContext
      );

      const element = React.createElement(Component, props);
      const html = ReactDOMServer.renderToStaticMarkup(element);
      const output = `<style>${Component.style}</style>\n${html}`;
      return Promise.resolve(output);
    } catch (error) {
      debug(error);
      return Promise.reject(error.message);
    }
  }
}

module.exports = ReactAdapter;


text:
/**
 * Do not modify this class. It was generated.
 * Instead modify LeafRegionEntry.cpp and then run
 * bin/generateRegionEntryClasses.sh from the directory
 * that contains your build.xml.
 */
package com.gemstone.gemfire.internal.cache;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import com.gemstone.gemfire.internal.cache.Token;
import com.gemstone.gemfire.internal.concurrent.AtomicUpdaterFactory;
import com.gemstone.gemfire.internal.offheap.OffHeapRegionEntryHelper;
import com.gemstone.gemfire.internal.offheap.annotations.Released;
import com.gemstone.gemfire.internal.offheap.annotations.Retained;
import com.gemstone.gemfire.internal.offheap.annotations.Unretained;
import com.gemstone.gemfire.internal.cache.lru.EnableLRU;
import com.gemstone.gemfire.internal.cache.persistence.DiskRecoveryStore;
import com.gemstone.gemfire.internal.InternalStatisticsDisabledException;
import com.gemstone.gemfire.internal.cache.lru.LRUClockNode;
import com.gemstone.gemfire.internal.cache.lru.NewLRUClockHand;
import com.gemstone.gemfire.internal.concurrent.CustomEntryConcurrentHashMap.HashEntry;
import com.gemstone.gemfire.internal.size.ReflectionSingleObjectSizer;
@SuppressWarnings("serial")
public class VMStatsDiskLRURegionEntryOffHeap extends VMStatsDiskLRURegionEntry
    implements OffHeapRegionEntry
{
  public VMStatsDiskLRURegionEntryOffHeap (RegionEntryContext context, Object key,
    @Retained
    Object value
      ) {
    super(context,
          (value instanceof RecoveredEntry ? null : value)
        );
    initialize(context, value);
    this.key = key;
  }
  protected int hash;
  private HashEntry<Object, Object> next;
  @SuppressWarnings("unused")
  private volatile long lastModified;
  private static final AtomicLongFieldUpdater<VMStatsDiskLRURegionEntryOffHeap> lastModifiedUpdater
    = AtomicUpdaterFactory.newLongFieldUpdater(VMStatsDiskLRURegionEntryOffHeap.class, "lastModified");
  protected long getlastModifiedField() {
    return lastModifiedUpdater.get(this);
  }
  protected final boolean compareAndSetLastModifiedField(long expectedValue,
      long newValue) {
    return lastModifiedUpdater.compareAndSet(this, expectedValue, newValue);
  }
  @Override
  public final int getEntryHash() {
    return this.hash;
  }
  @Override
  protected final void setEntryHash(int v) {
    this.hash = v;
  }
  @Override
  public final HashEntry<Object, Object> getNextEntry() {
    return this.next;
  }
  @Override
  public final void setNextEntry(final HashEntry<Object, Object> n) {
    this.next = n;
  }
  protected final void initialize(RegionEntryContext drs, Object value) {
    boolean isBackup;
    if (drs instanceof LocalRegion) {
      isBackup = ((LocalRegion)drs).getDiskRegion().isBackup();
    } else if (drs instanceof PlaceHolderDiskRegion) {
      isBackup = true;
    } else {
      throw new IllegalArgumentException("expected a LocalRegion or PlaceHolderDiskRegion");
    }
    if (isBackup) {
      diskInitialize(drs, value);
    }
  }
  @Override
  public final synchronized int updateAsyncEntrySize(EnableLRU capacityController) {
    int oldSize = getEntrySize();
    int newSize = getKeySize(getRawKey(), capacityController);
    setEntrySize(newSize);
    int delta = newSize - oldSize;
    return delta;
  }
  private final int getKeySize(Object key, EnableLRU capacityController) {
    final GemFireCacheImpl.StaticSystemCallbacks sysCb =
        GemFireCacheImpl.getInternalProductCallbacks();
    if (sysCb == null || capacityController.getEvictionAlgorithm().isLRUEntry()) {
      return capacityController.entrySize(key, null);
    }
    else {
      int tries = 1;
      do {
        final int size = sysCb.entryKeySizeInBytes(key, this);
        if (size >= 0) {
          return size - ReflectionSingleObjectSizer.REFERENCE_SIZE;
        }
        if ((tries % MAX_READ_TRIES_YIELD) == 0) {
          Thread.yield();
        }
      } while (tries++ <= MAX_READ_TRIES);
      throw sysCb.checkCacheForNullKeyValue("DiskLRU RegionEntry#getKeySize");
    }
  }
  private void diskInitialize(RegionEntryContext context, Object value) {
    DiskRecoveryStore drs = (DiskRecoveryStore)context;
    DiskStoreImpl ds = drs.getDiskStore();
    long maxOplogSize = ds.getMaxOplogSize();
    this.id = DiskId.createDiskId(maxOplogSize, true , ds.needsLinkedList());
    Helper.initialize(this, drs, value);
  }
  protected DiskId id;
  public final DiskId getDiskId() {
    return this.id;
  }
  @Override
  public final void setDiskId(RegionEntry old) {
    this.id = ((AbstractDiskRegionEntry)old).getDiskId();
  }
  @Override
  public final void setDelayedDiskId(LocalRegion r) {
    DiskStoreImpl ds = r.getDiskStore();
    long maxOplogSize = ds.getMaxOplogSize();
    this.id = DiskId.createDiskId(maxOplogSize, false , ds.needsLinkedList());
  }
  public final synchronized int updateEntrySize(EnableLRU capacityController) {
    return updateEntrySize(capacityController, _getValue());
  }
  public final synchronized int updateEntrySize(EnableLRU capacityController,
                                                Object value) {
    int oldSize = getEntrySize();
    int newSize = capacityController.entrySize(getRawKey(), value);
    setEntrySize(newSize);
    int delta = newSize - oldSize;
    return delta;
  }
  private LRUClockNode nextLRU;
  private LRUClockNode prevLRU;
  private int size;
  public final void setNextLRUNode( LRUClockNode next ) {
    this.nextLRU = next;
  }
  public final LRUClockNode nextLRUNode() {
    return this.nextLRU;
  }
  public final void setPrevLRUNode( LRUClockNode prev ) {
    this.prevLRU = prev;
  }
  public final LRUClockNode prevLRUNode() {
    return this.prevLRU;
  }
  public final int getEntrySize() {
    return this.size;
  }
  protected final void setEntrySize(int size) {
    this.size = size;
  }
  @Override
  public final void updateStatsForGet(boolean hit, long time)
  {
    setLastAccessed(time);
    if (hit) {
      incrementHitCount();
    } else {
      incrementMissCount();
    }
  }
  @Override
  public final void setLastModified(long lastModified) {
    _setLastModified(lastModified);
    if (!DISABLE_ACCESS_TIME_UPDATE_ON_PUT) {
      setLastAccessed(lastModified);
    }
  }
  private volatile long lastAccessed;
  private volatile int hitCount;
  private volatile int missCount;
  private static final AtomicIntegerFieldUpdater<VMStatsDiskLRURegionEntryOffHeap> hitCountUpdater
    = AtomicUpdaterFactory.newIntegerFieldUpdater(VMStatsDiskLRURegionEntryOffHeap.class, "hitCount");
  private static final AtomicIntegerFieldUpdater<VMStatsDiskLRURegionEntryOffHeap> missCountUpdater
    = AtomicUpdaterFactory.newIntegerFieldUpdater(VMStatsDiskLRURegionEntryOffHeap.class, "missCount");
  @Override
  public final long getLastAccessed() throws InternalStatisticsDisabledException {
    return this.lastAccessed;
  }
  private void setLastAccessed(long lastAccessed) {
    this.lastAccessed = lastAccessed;
  }
  @Override
  public final long getHitCount() throws InternalStatisticsDisabledException {
    return this.hitCount & 0xFFFFFFFFL;
  }
  @Override
  public final long getMissCount() throws InternalStatisticsDisabledException {
    return this.missCount & 0xFFFFFFFFL;
  }
  private void incrementHitCount() {
    hitCountUpdater.incrementAndGet(this);
  }
  private void incrementMissCount() {
    missCountUpdater.incrementAndGet(this);
  }
  @Override
  public final void resetCounts() throws InternalStatisticsDisabledException {
    hitCountUpdater.set(this,0);
    missCountUpdater.set(this,0);
  }
  @Override
  public final void txDidDestroy(long currTime) {
    setLastModified(currTime);
    setLastAccessed(currTime);
    this.hitCount = 0;
    this.missCount = 0;
  }
  @Override
  public final boolean hasStats() {
    return true;
  }
  private Object key;
  @Override
  public final Object getRawKey() {
    return this.key;
  }
  @Override
  protected final void _setRawKey(Object key) {
    this.key = key;
  }
  @Retained @Released private volatile long ohAddress;
  private final static AtomicLongFieldUpdater<VMStatsDiskLRURegionEntryOffHeap> ohAddrUpdater =
      AtomicUpdaterFactory.newLongFieldUpdater(VMStatsDiskLRURegionEntryOffHeap.class, "ohAddress");
  @Override
  public final boolean isOffHeap() {
    return true;
  }
  @Override
  public final Token getValueAsToken() {
    return OffHeapRegionEntryHelper.getValueAsToken(this);
  }
  @Override
  @Unretained
  protected final Object getValueField() {
    return OffHeapRegionEntryHelper._getValue(this);
  }
  @Override
  protected final void setValueField(@Unretained Object v) {
    OffHeapRegionEntryHelper.setValue(this, v);
  }
  @Override
  @Retained
  public final Object _getValueRetain(RegionEntryContext context,
      boolean decompress) {
    return OffHeapRegionEntryHelper._getValueRetain(this, decompress);
  }
  @Override
  public final long getAddress() {
    return ohAddrUpdater.get(this);
  }
  @Override
  public final boolean setAddress(long expectedAddr, long newAddr) {
    return ohAddrUpdater.compareAndSet(this, expectedAddr, newAddr);
  }
  @Override
  @Released
  public final void release() {
    OffHeapRegionEntryHelper.releaseEntry(this);
  }
  private static RegionEntryFactory factory = new RegionEntryFactory() {
    public final RegionEntry createEntry(RegionEntryContext context, Object key, Object value) {
      return new VMStatsDiskLRURegionEntryOffHeap(context, key, value);
    }
    public final Class<?> getEntryClass() {
      return VMStatsDiskLRURegionEntryOffHeap.class;
    }
    public RegionEntryFactory makeVersioned() {
      return VMStatsDiskLRURegionEntryOffHeap.getEntryFactory();
    }
    @Override
    public RegionEntryFactory makeOnHeap() {
      return VMStatsDiskLRURegionEntryHeap.getEntryFactory();
    }
  };
  public static RegionEntryFactory getEntryFactory() {
    return factory;
  }
}


text:
const express = require("express")
const router = express()
const { createWebAPIRequest } = require("../util/util")

router.get("/", (req, res) => {
  const cookie = req.get('Cookie') ? req.get('Cookie') : ''
  const data = {
    "csrf_token": "",
    s: req.query.keywords || req.query.keywords || ''
  }

  createWebAPIRequest(
    'music.163.com',
    '/weapi/search/suggest/web',
    'POST',
    data,
    cookie,
    music_req => {
      res.send(music_req)
    },
    err => res.status(502).send('fetch error')
  )
})

module.exports = router


text:
package com.nms.vnm.eip.service.entity;

import com.nms.vnm.eip.entity.Picture;
import com.nms.vnm.eip.entity.PictureCategory;

public interface PictureService extends ProductService<Picture, PictureCategory> {

}


text:
Most class components start off with a constructor which does some
initialization of the component including setting the components initial
state. It might look something like the following:

```javascript
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true
    };
  }

  render() {
    if (this.state.loading) {
      return (
        <p>Loading...</p>
      );
    } else {
      // ...
    }
  }
}
```

If setting state is the only thing you need to do in the constructor,
then you can skip the constructor all together.

```javascript
class MyComponent extends React.Component {
  state = {
    loading: true
  };

  render() {
    if (this.state.loading) {
      return (
        <p>Loading...</p>
      );
    } else {
      // ...
    }
  }
}
```

This second example will work the same as the first, and it is a bit more
concise.


text:
@interface BTUICardCvvField ()<UITextFieldDelegate>
@property (nonatomic, readonly) NSUInteger validLength;
@property (nonatomic, strong) BTUICardHint *hint;
@end

@implementation BTUICardCvvField

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setThemedPlaceholder:BTUILocalizedString(CVV_FIELD_PLACEHOLDER)];
        self.textField.keyboardType = UIKeyboardTypeNumberPad;
        self.textField.delegate = self;

        self.hint = [BTUICardHint new];
        self.hint.displayMode = BTCardHintDisplayModeCVVHint;
        self.accessoryView = self.hint;
        self.accessoryView.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:self.accessoryView];
    }
    return self;
}

- (void)setCardType:(BTUICardType *)cardType {
    _cardType = cardType;
    self.displayAsValid = [self.textField isFirstResponder] || self.textField.text.length == 0 || self.valid;
    [self.hint setCardType:[BTUIViewUtil paymentMethodTypeForCardType:cardType] animated:YES];
    [self updateAppearance];
}

- (BOOL)valid {
    BOOL noCardTypeOKLength = (self.cardType == nil && self.cvv.length <= kMaximumCvvLength && self.cvv.length >= kMinimumCvvLength);
    BOOL validLengthForCardType = (self.cardType != nil && self.cvv.length == self.cardType.validCvvLength);
    return noCardTypeOKLength || validLengthForCardType;
}

- (BOOL)entryComplete {
    NSUInteger index = [self.textField offsetFromPosition:self.textField.beginningOfDocument toPosition:self.textField.selectedTextRange.start];
    BOOL cursorAtEnd = (index == self.textField.text.length);

    if (self.cardType == nil) {
        return cursorAtEnd && self.cvv.length == kMaximumCvvLength;
    } else {
        return self.valid;
    }
}

- (BOOL)textField:(__unused UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return string.length + range.location <= self.validLength;
}

- (NSUInteger)validLength {
    return self.cardType == nil ? kMaximumCvvLength : self.cardType.validCvvLength;
}

#pragma mark - Handlers

- (void)fieldContentDidChange {
    self.displayAsValid = YES;
    _cvv = [BTUIUtil stripNonDigits:self.textField.text];
    [self.delegate formFieldDidChange:self];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [super textFieldDidBeginEditing:textField];
    self.displayAsValid = YES;
    [self.hint setHighlighted:YES animated:YES];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [super textFieldDidEndEditing:textField];
    self.displayAsValid = self.textField.text.length == 0 || self.valid;
    [self.hint setHighlighted:NO animated:YES];
}

@end


text:
local gameConfig = require("gameConfig")
local composer = require( "composer" )
local LevelSelectionScene = require("scenes.templates.LevelSelectionScene")
local Sprite = require("Sprite")
local GlassPanel = require("ui.GlassPanel")
local MetalPanel = require("ui.MetalPanel")
local dbHelper = require("dbHelper")
local Bar = require("ui.BlueTopBar")
local MetalPanelPlate = require("ui.MetalPanelPlate")
local logger = require("logger")
local TAG = "ChapterSelection"
local Number = require("ui.Number")
local CHAPTER_RANDOM_MODE_INDEX = 1
local CHAPTER_INFINITE_MODE_INDEX = 2
local CHAPTER_LEVEL_MODE_INDEX = 3
local navigator = require("navigator")
local ScaleText = require("ui.ScaleText")
local scene = LevelSelectionScene.new({
    row = 1,
    col = 1,
    numOfLevels = 3,
    title = "Select Chapter"
  })

function scene:onLevelConfirm(index)
    logger:debug(TAG, "Select chapter %d", index)
    if self.blocks[index].locked then
      self:alert("Comming soon, check it later.")
      return
    end
    if index == CHAPTER_LEVEL_MODE_INDEX then
        navigator:push("scenes.chapterSelection")
        composer.showOverlay( "scenes.levelSelection", {
            isModal = true,
            effect = "fromRight",
            time = 400,
        })
    elseif index == CHAPTER_INFINITE_MODE_INDEX then
        --go to game
        composer.gotoScene("scenes.game")
    elseif index == CHAPTER_RANDOM_MODE_INDEX then
        print("Random chapter selected")
        math.randomseed(os.time())
        local levelIdx = math.random(1, #gameConfig.seperateLevels)
        composer.gotoScene("scenes.game", {
            params = {
              mode = gameConfig.MODE_SINGLE_LEVEL,
              _isRandom = true,
              levels = gameConfig.seperateLevels,
              levelIdx = levelIdx
            }
        })
    end
end

function scene:createChapter(options)
    local score = Number.new((options and options.score) or 1234)
    local chapter = display.newGroup()
    local bar = Bar.new(self.blockWidth, self.blockHeight * 0.16)
    local base = MetalPanel.new(self.blockWidth, self.blockHeight)
    local info = MetalPanelPlate.new(self.blockWidth * 0.92, self.blockHeight/4)
    local chapterName = ScaleText.new({
      text = (options and options.title) or "INFINITE",
      x = 0,
      y = 0,
      font = gameConfig.defaultFont,
      fontSize = 17
    })
    local scoreLabel = ScaleText.new({
      text = "Score",
      x = 0,
      y = 0,
      font = gameConfig.defaultFont,
      fontSize = 30
    })
    local preview = (options and options.preview) or Sprite["expansion-2"].new("Planet/5")
    preview.y = -self.blockHeight*0.08
    scoreLabel.fill = {139/255, 147/255, 158/255}
    base.y = (self.blockHeight - base.height)/2
    bar.y = (bar.height - base.height)/2
    info.y = self.blockHeight * 0.3
    chapterName.y = bar.y
    scoreLabel.y = self.blockHeight * 0.25
    scoreLabel.x = 0
    score.y = self.blockHeight * 0.35
    score.x = -score.width * 0.05

    chapter:insert(base)
    chapter:insert(info)
    chapter:insert(bar)
    chapter:insert(chapterName)
    chapter:insert(scoreLabel)
    chapter:insert(score)
    chapter:insert(preview)
    if options and options.locked then
      local lockIcon = Sprite["expansion-9"].new("UI/Icons/Lock")
      lockIcon.x = 0
      lockIcon.y = 0
      chapter.locked = options.locked
      chapter:insert(lockIcon)
    end
    return chapter
end

function scene:createLevelBlock(index)
    local block = nil
    if index == CHAPTER_INFINITE_MODE_INDEX then
        local highScore = dbHelper:getHighScore(gameConfig.ID_LEVEL_INFINITE, "local")
        block = self:createChapter({score = highScore, preview = Sprite["expansion-2"].new("Planet/7")})
    elseif index == CHAPTER_LEVEL_MODE_INDEX then
        local highScore = 0
        for i = 1, #gameConfig.seperateLevels do
            highScore = highScore + dbHelper:getHighScore(require("levels."..gameConfig.seperateLevels[i]).id, "local")
        end
        local locked = false
        if gameConfig.hiddenSingleLevelChapter then
          locked = true
        end
        block = self:createChapter({title = "SINGLE", score = highScore, preview = Sprite["expansion-2"].new("Planet/4"), locked = locked})
    elseif index == CHAPTER_RANDOM_MODE_INDEX then
        local highScore = 0
        for i = 1, #gameConfig.seperateLevels do
            highScore = highScore + dbHelper:getHighScore(require("levels."..gameConfig.seperateLevels[i]).id, "local")
        end
        block = self:createChapter({title = "RANDOM", score = highScore, preview = Sprite["expansion-2"].new("Planet/3"), locked = false})
    end
    return block
end

return scene


text:
WpApiProvider

service in module wp-api-angularjs

Description

wp-api-angularjs provider

Methods

setBaseUrl(newBaseUrl)

Set the webserver base url

Parameters

Param	Type	Details

newBaseUrl	string

the url to the webservice


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DeadManSwitch.Service.WebApi
{
    public class UserLoginModel
    {
        [Required]
        public string UserName { get; set; }
        [Required]
        public string Password { get; set; }
    }
}