Writes grade_items
435355
protected function write_grade_items() {

        $this->xmlwriter->begin_tag('grade_items');
        foreach ($this->converter->get_stash_itemids('gradebook_nonmodgradeitem') as $gradeitemid) {
            $gradeitem = $this->converter->get_stash('gradebook_nonmodgradeitem', $gradeitemid);
            $this->write_xml('grade_item', $gradeitem, array('/grade_item/id'));
        }
        $this->xmlwriter->end_tag('grade_items');
    }
1208863
protected function gradebook_item_update($submission=null, $grade=null) {
        global $CFG;

        require_once($CFG->dirroot.'/mod/assign/lib.php');
        // Do not push grade to gradebook if blind marking is active as
        // the gradebook would reveal the students.
        if ($this->is_blind_marking()) {
            return false;
        }

        // If marking workflow is enabled and grade is not released then remove any grade that may exist in the gradebook.
        if ($this->get_instance()->markingworkflow && !empty($grade) &&
                $this->get_grading_status($grade->userid) != ASSIGN_MARKING_WORKFLOW_STATE_RELEASED) {
            // Remove the grade (if it exists) from the gradebook as it is not 'final'.
            $grade->grade = -1;
            $grade->feedbacktext = '';
            $grade->feebackfiles = [];
        }

        if ($submission != null) {
            if ($submission->userid == 0) {
                // This is a group submission update.
                $team = groups_get_members($submission->groupid, 'u.id');

                foreach ($team as $member) {
                    $membersubmission = clone $submission;
                    $membersubmission->groupid = 0;
                    $membersubmission->userid = $member->id;
                    $this->gradebook_item_update($membersubmission, null);
                }
                return;
            }

            $gradebookgrade = $this->convert_submission_for_gradebook($submission);

        } else {
            $gradebookgrade = $this->convert_grade_for_gradebook($grade);
        }
        // Grading is disabled, return.
        if ($this->grading_disabled($gradebookgrade['userid'])) {
            return false;
        }
        $assign = clone $this->get_instance();
        $assign->cmidnumber = $this->get_course_module()->idnumber;
        // Set assign gradebook feedback plugin status (enabled and visible).
        $assign->gradefeedbackenabled = $this->is_gradebook_feedback_enabled();
        return assign_grade_item_update($assign, $gradebookgrade) == GRADE_UPDATE_OK;
    }
140373
private static void writeProfileForTree(final PrintWriter writer,
			final Map<WComponent, UicStats.Stat> treeStats) {
		// Copy all the stats into a list so we can sort and cull.
		List<UicStats.Stat> statList = new ArrayList<>(treeStats.values());

		Comparator<UicStats.Stat> comparator = new Comparator<UicStats.Stat>() {
			@Override
			public int compare(final UicStats.Stat stat1, final UicStats.Stat stat2) {
				if (stat1.getModelState() > stat2.getModelState()) {
					return -1;
				} else if (stat1.getModelState() < stat2.getModelState()) {
					return 1;
				} else {
					int diff = stat1.getClassName().compareTo(stat2.getClassName());

					if (diff == 0) {
						diff = stat1.getName().compareTo(stat2.getName());
					}

					return diff;
				}
			}
		};

		Collections.sort(statList, comparator);

		for (int i = 0; i < statList.size(); i++) {
			UicStats.Stat stat = statList.get(i);
			writeRow(writer, stat);
		}
	}
588369
def simple_write(filename, group, times, features,
                 properties=None, item='item', mode='a'):
    """"""
    write(filename, group, [item], [times], [features], mode=mode,
          properties=[properties] if properties is not None else None)
1039812
private static function grading_instance() {
        global $CFG;
        $instance = array();
        $instance['id']                = new external_value(PARAM_INT, 'instance id');
        $instance['raterid']           = new external_value(PARAM_INT, 'rater id');
        $instance['itemid']            = new external_value(PARAM_INT, 'item id');
        $instance['rawgrade']          = new external_value(PARAM_TEXT, 'raw grade', VALUE_OPTIONAL);
        $instance['status']            = new external_value(PARAM_INT, 'status');
        $instance['feedback']          = new external_value(PARAM_RAW, 'feedback', VALUE_OPTIONAL);
        $instance['feedbackformat']    = new external_format_value('feedback', VALUE_OPTIONAL);
        $instance['timemodified']      = new external_value(PARAM_INT, 'modified time');
        foreach (self::get_grading_methods() as $method) {
            require_once($CFG->dirroot.'/grade/grading/form/'.$method.'/lib.php');
            $details  = call_user_func('gradingform_'.$method.'_controller::get_external_instance_filling_details');
            if ($details != null) {
                $items = array();
                foreach ($details as $key => $value) {
                    $details[$key]->required = VALUE_OPTIONAL;
                    $items[$key] = $value;
                }
                $instance[$method] = new external_single_structure($items, 'items', VALUE_OPTIONAL);
            }
        }
        return new external_single_structure($instance);
    }
1069797
public function format_line($item) {
        global $OUTPUT;

        $grade = $this->fetch_grade_or_default($this->item, $item->id);

        $lockicon = '';

        $lockedgrade = $lockedgradeitem = 0;
        if (!empty($grade->locked)) {
            $lockedgrade = 1;
        }
        if (!empty($grade->grade_item->locked)) {
            $lockedgradeitem = 1;
        }
        // Check both grade and grade item.
        if ( $lockedgrade || $lockedgradeitem ) {
            $lockicon = $OUTPUT->pix_icon('t/locked', 'grade is locked') . ' ';
        }

        if (!empty($item->alternatename)) {
            $fullname = $lockicon . $item->alternatename . ' (' . $item->firstname . ') ' . $item->lastname;
        } else {
            $fullname = $lockicon . fullname($item);
        }

        $item->imagealt = $fullname;
        $url = new moodle_url("/user/view.php", array('id' => $item->id, 'course' => $this->courseid));
        $iconstring = get_string('filtergrades', 'gradereport_singleview', $fullname);
        $grade->label = $fullname;

        $line = array(
            $OUTPUT->action_icon($this->format_link('user', $item->id), new pix_icon('t/editstring', $iconstring)),
            $OUTPUT->user_picture($item, array('visibletoscreenreaders' => false)) .
            html_writer::link($url, $fullname),
            $this->item_range()
        );
        $lineclasses = array(
            "action",
            "user",
            "range"
        );
        $outputline = array();
        $i = 0;
        foreach ($line as $key => $value) {
            $cell = new \html_table_cell($value);
            if ($isheader = $i == 1) {
                $cell->header = $isheader;
                $cell->scope = "row";
            }
            if (array_key_exists($key, $lineclasses)) {
                $cell->attributes['class'] = $lineclasses[$key];
            }
            $outputline[] = $cell;
            $i++;
        }

        return $this->format_definition($outputline, $grade);
    }
344593
private void writeElements(SerIterator itemIterator) throws IOException {
        if (itemIterator.metaTypeRequired()) {
            output.writeObjectStart();
            output.writeObjectKeyValue(META, itemIterator.metaTypeName());
            output.writeObjectKey(VALUE);
        }
        if (itemIterator.category() == SerCategory.MAP) {
            writeMap(itemIterator);
        } else if (itemIterator.category() == SerCategory.COUNTED) {
            writeCounted(itemIterator);
        } else if (itemIterator.category() == SerCategory.TABLE) {
            writeTable(itemIterator);
        } else if (itemIterator.category() == SerCategory.GRID) {
            writeGrid(itemIterator);
        } else {
            writeArray(itemIterator);
        }
        if (itemIterator.metaTypeRequired()) {
            output.writeObjectEnd();
        }
    }
1359277
def _write_section(self, fp, section_name, section_items, delimiter):
        """"""
        fp.write("[{0}]\n".format(section_name))
        for key, value in section_items:
            value = self._interpolation.before_write(self, section_name, key,
                                                     value)
            if value is not None or not self._allow_no_value:
                value = delimiter + str(value).replace('\n', '\n\t')
            else:
                value = ""
            fp.write("{0}{1}\n".format(key, value))
        fp.write("\n")
1263293
def summarize_grading(samples, vkey="validate"):
    
    samples = list(utils.flatten(samples))
    if not _has_grading_info(samples, vkey):
        return [[d] for d in samples]
    validate_dir = utils.safe_makedir(os.path.join(samples[0]["dirs"]["work"], vkey))
    header = ["sample", "caller", "variant.type", "category", "value"]
    _summarize_combined(samples, vkey)
    validated, out = _group_validate_samples(samples, vkey,
                                             (["metadata", "validate_batch"], ["metadata", "batch"], ["description"]))
    for vname, vitems in validated.items():
        out_csv = os.path.join(validate_dir, "grading-summary-%s.csv" % vname)
        with open(out_csv, "w") as out_handle:
            writer = csv.writer(out_handle)
            writer.writerow(header)
            plot_data = []
            plot_files = []
            for data in sorted(vitems, key=lambda x: x.get("lane", dd.get_sample_name(x)) or ""):
                validations = [variant.get(vkey) for variant in data.get("variants", [])
                               if isinstance(variant, dict)]
                validations = [v for v in validations if v]
                if len(validations) == 0 and vkey in data:
                    validations = [data.get(vkey)]
                for validate in validations:
                    if validate:
                        validate["grading_summary"] = out_csv
                        if validate.get("grading"):
                            for row in _get_validate_plotdata_yaml(validate["grading"], data):
                                writer.writerow(row)
                                plot_data.append(row)
                        elif validate.get("summary") and not validate.get("summary") == "None":
                            if isinstance(validate["summary"], (list, tuple)):
                                plot_files.extend(list(set(validate["summary"])))
                            else:
                                plot_files.append(validate["summary"])
        if plot_files:
            plots = validateplot.classifyplot_from_plotfiles(plot_files, out_csv)
        elif plot_data:
            plots = validateplot.create(plot_data, header, 0, data["config"],
                                        os.path.splitext(out_csv)[0])
        else:
            plots = []
        for data in vitems:
            if data.get(vkey):
                data[vkey]["grading_plots"] = plots
            for variant in data.get("variants", []):
                if isinstance(variant, dict) and variant.get(vkey):
                    variant[vkey]["grading_plots"] = plots
            out.append([data])
    return out
823707
def write(self, fp):
        """"""
        if self._defaults:
            fp.write("[%s]\n" % DEFAULTSECT)
            for (key, value) in self._defaults.items():
                fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
            fp.write("\n")
        for section in self._sections:
            fp.write("[%s]\n" % section)
            for (key, value) in self._sections[section].items():
                if key == "__name__":
                    continue
                if (value is not None) or (self._optcre == self.OPTCRE):
                    key = " = ".join((key, str(value).replace('\n', '\n\t')))
                fp.write("%s\n" % (key))
            fp.write("\n")
803252
public function format_line($item) {
        global $OUTPUT;

        $grade = $this->fetch_grade_or_default($item, $this->item->id);
        $lockicon = '';

        $lockeditem = $lockeditemgrade = 0;
        if (!empty($grade->locked)) {
            $lockeditem = 1;
        }
        if (!empty($grade->grade_item->locked)) {
            $lockeditemgrade = 1;
        }
        // Check both grade and grade item.
        if ($lockeditem || $lockeditemgrade) {
             $lockicon = $OUTPUT->pix_icon('t/locked', 'grade is locked');
        }

        $iconstring = get_string('filtergrades', 'gradereport_singleview', $item->get_name());

        // Create a fake gradetreeitem so we can call get_element_header().
        // The type logic below is from grade_category->_get_children_recursion().
        $gradetreeitem = array();
        if (in_array($item->itemtype, array('course', 'category'))) {
            $gradetreeitem['type'] = $item->itemtype.'item';
        } else {
            $gradetreeitem['type'] = 'item';
        }
        $gradetreeitem['object'] = $item;
        $gradetreeitem['userid'] = $this->item->id;

        $itemlabel = $this->structure->get_element_header($gradetreeitem, true, false, false, false, true);
        $grade->label = $item->get_name();

        $line = array(
            $OUTPUT->action_icon($this->format_link('grade', $item->id), new pix_icon('t/editstring', $iconstring)),
            $this->format_icon($item) . $lockicon . $itemlabel,
            $this->category($item),
            new range($item)
        );
        $lineclasses = array(
            "action",
            "gradeitem",
            "category",
            "range"
        );

        $outputline = array();
        $i = 0;
        foreach ($line as $key => $value) {
            $cell = new \html_table_cell($value);
            if ($isheader = $i == 1) {
                $cell->header = $isheader;
                $cell->scope = "row";
            }
            if (array_key_exists($key, $lineclasses)) {
                $cell->attributes['class'] = $lineclasses[$key];
            }
            $outputline[] = $cell;
            $i++;
        }

        return $this->format_definition($outputline, $grade);
    }
109676
private void writeElements(String currentIndent, String tagName, StringBuilder attrs, SerIterator itemIterator) throws IOException {
        if (itemIterator.metaTypeRequired()) {
            appendAttribute(attrs, METATYPE, itemIterator.metaTypeName());
        }
        if (itemIterator.category() == SerCategory.GRID) {
            appendAttribute(attrs, ROWS, Integer.toString(itemIterator.dimensionSize(0)));
            appendAttribute(attrs, COLS, Integer.toString(itemIterator.dimensionSize(1)));
        }
        if (itemIterator.size() == 0) {
            output.append(currentIndent).append('<').append(tagName).append(attrs).append('/').append('>').append(settings.getNewLine());
        } else {
            output.append(currentIndent).append('<').append(tagName).append(attrs).append('>').append(settings.getNewLine());
            writeElements(currentIndent + settings.getIndent(), itemIterator);
            output.append(currentIndent).append('<').append('/').append(tagName).append('>').append(settings.getNewLine());
        }
    }
474301
def write(self, more):
        """"""
        if more:
            self.output += str(more).upper()
            self.output += '\n'
1025788
public function write()
    {
        $stats = array('hits' => $this->hits, 'misses' => $this->misses);

        file_put_contents($this->getFilename(), serialize($stats));
    }
1108328
function definition_after_data() {
        global $CFG, $COURSE;

        $mform =& $this->_form;

        if ($id = $mform->getElementValue('id')) {
            $gradeitem = grade_item::fetch(array('id' => $id));
            $parentcategory = $gradeitem->get_parent_category();
        } else {
            // If we do not have an id, we are creating a new grade item.
            $gradeitem = new grade_item(array('courseid' => $COURSE->id, 'itemtype' => 'manual'), false);

            // Assign the course category to this grade item.
            $parentcategory = grade_category::fetch_course_category($COURSE->id);
            $gradeitem->parent_category = $parentcategory;
        }

        if (!$gradeitem->is_raw_used()) {
            $mform->removeElement('plusfactor');
            $mform->removeElement('multfactor');
        }

        if ($gradeitem->is_outcome_item()) {
            // We have to prevent incompatible modifications of outcomes if outcomes disabled.
            $mform->removeElement('grademax');
            if ($mform->elementExists('grademin')) {
                $mform->removeElement('grademin');
            }
            $mform->removeElement('gradetype');
            $mform->removeElement('display');
            $mform->removeElement('decimals');
            $mform->hardFreeze('scaleid');

        } else {
            if ($gradeitem->is_external_item()) {
                // Following items are set up from modules and should not be overrided by user.
                if ($mform->elementExists('grademin')) {
                    // The site setting grade_report_showmin may have prevented grademin being added to the form.
                    $mform->hardFreeze('grademin');
                }
                $mform->hardFreeze('itemname,gradetype,grademax,scaleid');
                if ($gradeitem->itemnumber == 0) {
                    // The idnumber of grade itemnumber 0 is synced with course_modules.
                    $mform->hardFreeze('idnumber');
                }

                // For external items we can not change the grade type, even if no grades exist, so if it is set to
                // scale, then remove the grademax and grademin fields from the form - no point displaying them.
                if ($gradeitem->gradetype == GRADE_TYPE_SCALE) {
                    $mform->removeElement('grademax');
                    if ($mform->elementExists('grademin')) {
                        $mform->removeElement('grademin');
                    }
                } else { // Not using scale, so remove it.
                    $mform->removeElement('scaleid');
                }

                // Always remove the rescale grades element if it's an external item.
                $mform->removeElement('rescalegrades');
            } else if ($gradeitem->has_grades()) {
                // Can't change the grade type or the scale if there are grades.
                $mform->hardFreeze('gradetype, scaleid');

                // If we are using scales then remove the unnecessary rescale and grade fields.
                if ($gradeitem->gradetype == GRADE_TYPE_SCALE) {
                    $mform->removeElement('rescalegrades');
                    $mform->removeElement('grademax');
                    if ($mform->elementExists('grademin')) {
                        $mform->removeElement('grademin');
                    }
                } else { // Remove the scale field.
                    $mform->removeElement('scaleid');
                    // Set the maximum grade to disabled unless a grade is chosen.
                    $mform->disabledIf('grademax', 'rescalegrades', 'eq', '');
                }
            } else {
                // Remove the rescale element if there are no grades.
                $mform->removeElement('rescalegrades');
            }
        }

        // If we wanted to change parent of existing item - we would have to verify there are no circular references in parents!!!
        if ($id && $mform->elementExists('parentcategory')) {
            $mform->hardFreeze('parentcategory');
        }

        $parentcategory->apply_forced_settings();

        if (!$parentcategory->is_aggregationcoef_used()) {
            if ($mform->elementExists('aggregationcoef')) {
                $mform->removeElement('aggregationcoef');
            }

        } else {
            $coefstring = $gradeitem->get_coefstring();

            if ($coefstring !== '') {
                if ($coefstring == 'aggregationcoefextrasum' || $coefstring == 'aggregationcoefextraweightsum') {
                    // The advcheckbox is not compatible with disabledIf!
                    $coefstring = 'aggregationcoefextrasum';
                    $element =& $mform->createElement('checkbox', 'aggregationcoef', get_string($coefstring, 'grades'));
                } else {
                    $element =& $mform->createElement('text', 'aggregationcoef', get_string($coefstring, 'grades'));
                }
                if ($mform->elementExists('parentcategory')) {
                    $mform->insertElementBefore($element, 'parentcategory');
                } else {
                    $mform->insertElementBefore($element, 'id');
                }
                $mform->addHelpButton('aggregationcoef', $coefstring, 'grades');
            }
            $mform->disabledIf('aggregationcoef', 'gradetype', 'eq', GRADE_TYPE_NONE);
            $mform->disabledIf('aggregationcoef', 'gradetype', 'eq', GRADE_TYPE_TEXT);
            $mform->disabledIf('aggregationcoef', 'parentcategory', 'eq', $parentcategory->id);
        }

        // Remove fields used by natural weighting if the parent category is not using natural weighting.
        // Or if the item is a scale and scales are not used in aggregation.
        if ($parentcategory->aggregation != GRADE_AGGREGATE_SUM
                || (empty($CFG->grade_includescalesinaggregation) && $gradeitem->gradetype == GRADE_TYPE_SCALE)) {
            if ($mform->elementExists('weightoverride')) {
                $mform->removeElement('weightoverride');
            }
            if ($mform->elementExists('aggregationcoef2')) {
                $mform->removeElement('aggregationcoef2');
            }
        }

        if ($category = $gradeitem->get_item_category()) {
            if ($category->aggregation == GRADE_AGGREGATE_SUM) {
                if ($mform->elementExists('gradetype')) {
                    $mform->hardFreeze('gradetype');
                }
                if ($mform->elementExists('grademin')) {
                    $mform->hardFreeze('grademin');
                }
                if ($mform->elementExists('grademax')) {
                    $mform->hardFreeze('grademax');
                }
                if ($mform->elementExists('scaleid')) {
                    $mform->removeElement('scaleid');
                }
            }
        }

        // no parent header for course category
        if (!$mform->elementExists('aggregationcoef') and !$mform->elementExists('parentcategory')) {
            $mform->removeElement('headerparent');
        }
    }
827411
def write(self, fout_xlsx=None, fout_txt=None, verbose=False):
        """"""
        sortby = self._get_fncsortnt(self.objgrpd.grprobj.gosubdag.prt_attr['flds'])
        kws_sort = {'sortby' if verbose else 'section_sortby': sortby}
        sortobj = Sorter(self.objgrpd.grprobj, **kws_sort)
        # KWS: hdrgo_prt=True section_prt=None top_n=None use_sections=True
        # RET: {sortobj, sections, hdrgo_prt} or {sortobj flat hdrgo_prt}
        desc2nts = sortobj.get_desc2nts_fnc(
            hdrgo_prt=verbose,
            section_prt=True,
            top_n=None,
            use_sections=True)
        # print('FFFF', desc2nts['flds'])
        # Write user GO IDs in sections
        objgowr = WrXlsxSortedGos("init", sortobj, self.objgrpd.ver_list)
        if fout_xlsx is not None:
            kws_xlsx = {'shade_hdrgos':verbose}
            if not verbose:
                kws_xlsx['prt_flds'] = [f for f in desc2nts['flds'] if f not in self.excl_flds]
            objgowr.wr_xlsx_nts(fout_xlsx, desc2nts, **kws_xlsx)
            fout_desc = '{BASE}_desc.txt'.format(BASE=os.path.splitext(fout_xlsx)[0])
            self._wr_ver_n_key(fout_desc, verbose)
        if fout_txt is not None:
            self._wr_txt_nts(fout_txt, desc2nts, objgowr, verbose)
        if fout_xlsx is None and fout_txt is None:
            self._prt_ver_n_key(sys.stdout, verbose)
            prtfmt = self._get_prtfmt(objgowr, verbose)
            summary_dct = objgowr.prt_txt_desc2nts(sys.stdout, desc2nts, prtfmt)
            self._prt_ver_n_key(sys.stdout, verbose)
            if summary_dct:
                print("\n{N} GO IDs in {S} sections".format(
                    N=desc2nts['num_items'], S=desc2nts['num_sections']))
1187818
function write_setting($data) {
        global $CFG;

        $previous = $this->get_setting();
        $result = parent::write_setting($data);

        // If saved and the value has changed.
        if (empty($result) && $previous != $data) {
            require_once($CFG->libdir . '/gradelib.php');
            grade_force_site_regrading();
        }

        return $result;
    }