Check the user's drop to see if he has corrected enought copy and if his copy is fully corrected
in order to notify him that his grade is available.
352734
private function checkUserGradeAvailable(Dropzone $dropzone, Drop $drop, $user)
    {
        // notification only in the PeerReview mode.
        $em = $this->getDoctrine()->getManager();
        $event = new LogDropGradeAvailableEvent($dropzone, $drop);
        if (1 === $dropzone->getPeerReview()) {
            // copy corrected by user

            // corrections on the user's copy
            $nbCorrectionByOthersOnUsersCopy = $em->getRepository('IcapDropzoneBundle:Correction')->getCorrectionsIds($dropzone, $drop);

            //Expected corrections
            $expectedCorrections = $dropzone->getExpectedTotalCorrection();

            /**
             * $nbCorrectionByUser = $em->getRepository('IcapDropzoneBundle:Correction')->getAlreadyCorrectedDropIds($dropzone, $user);
             * if(count($nbCorrectionByUser) >=  $expectedCorrections && count($nbCorrectionByOthersOnUsersCopy) >= $expectedCorrections  ).
             **/
            // corrected copy only instead of corrected copy AND given corrections.
            if (count($nbCorrectionByOthersOnUsersCopy) >= $expectedCorrections) {
                //dispatchEvent.
                $this->get('event_dispatcher')->dispatch('log', $event);
            }
        } else {
            $nbCorrectionByOthersOnUsersCopy = $em->getRepository('IcapDropzoneBundle:Correction')
                ->getCorrectionsIds($dropzone, $drop);

            if ($nbCorrectionByOthersOnUsersCopy > 0) {
                $this->get('event_dispatcher')->dispatch('log', $event);
            }
        }
    }
542587
public function has_submissions_or_grades() {
        $allgrades = $this->count_grades();
        $allsubmissions = $this->count_submissions();
        if (($allgrades == 0) && ($allsubmissions == 0)) {
            return false;
        }
        return true;
    }
956477
def is_feedback_available(self, question_id):
        """"""
        response = self.get_response(question_id)
        item = self._get_item(question_id)
        if response.is_answered():
            return item.is_feedback_available_for_response(response)
        return item.is_feedback_available()
904069
function checkThreshold(item, ctx) {
		if (item.count >= item.opts.minRequestCount) {
			const rate = item.failures / item.count;
			if (rate >= item.opts.threshold)
				trip(item, ctx);
		}
	}
1291740
public function checkCompletion(Dropzone $dropzone, array $users, Drop $drop = null)
    {
        $fixedStatusList = [
            AbstractResourceEvaluation::STATUS_COMPLETED,
            AbstractResourceEvaluation::STATUS_PASSED,
            AbstractResourceEvaluation::STATUS_FAILED,
        ];
        $teamId = !empty($drop) ? $drop->getTeamUuid() : null;

        $this->om->startFlushSuite();

        /* By default drop is complete if teacher review is enabled or drop is unlocked for user */
        $isComplete = !empty($drop) ? $drop->isFinished() && (!$dropzone->isPeerReview() || $drop->isUnlockedUser()) : false;

        /* If drop is not complete by default, checks for the number of finished corrections done by user */
        if (!$isComplete) {
            $expectedCorrectionTotal = $dropzone->getExpectedCorrectionTotal();
            $finishedPeerDrops = $this->getFinishedPeerDrops($dropzone, $users[0], $teamId);
            $isComplete = count($finishedPeerDrops) >= $expectedCorrectionTotal;
        }
        if ($isComplete) {
            foreach ($users as $user) {
                $userEval = $this->resourceEvalManager->getResourceUserEvaluation($dropzone->getResourceNode(), $user, false);

                if (!empty($userEval) && !in_array($userEval->getStatus(), $fixedStatusList)) {
                    $this->resourceEvalManager->createResourceEvaluation(
                        $dropzone->getResourceNode(),
                        $user,
                        null,
                        ['status' => AbstractResourceEvaluation::STATUS_COMPLETED, 'progression' => 100]
                    );
                } elseif (!empty($drop)) {
                    $this->updateDropProgression($dropzone, $drop, 100);
                }
                //TODO user whose score is available must be notified by LogDropGradeAvailableEvent, when he has done his corrections AND his drop has been corrected
            }
        }

        $this->om->endFlushSuite();
    }
399943
private void checkStability() {
    if ((_watermarksInserted.getCount() - _watermarksSwept.getCount()) > _watermarkLagThreshold) {
      log.error("Setting abort flag for Watermark tracking because the lag between the "
          + "watermarksInserted: {} and watermarksSwept: {} is greater than the threshold: {}",
          _watermarksInserted.getCount(), _watermarksSwept.getCount(), _watermarkLagThreshold);
      _abort.set(true);
    }
  }
508628
def update_user_stats(self, username, task, submission, result_str, grade, state, newsub):
        
        self.user_saw_task(username, submission["courseid"], submission["taskid"])

        if newsub:
            old_submission = self._database.user_tasks.find_one_and_update(
                {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]}, {"$inc": {"tried": 1, "tokens.amount": 1}})

            # Check if the submission is the default download
            set_default = task.get_evaluate() == 'last' or \
                          (task.get_evaluate() == 'student' and old_submission is None) or \
                          (task.get_evaluate() == 'best' and old_submission.get('grade', 0.0) <= grade)

            if set_default:
                self._database.user_tasks.find_one_and_update(
                    {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]},
                    {"$set": {"succeeded": result_str == "success", "grade": grade, "state": state, "submissionid": submission['_id']}})
        else:
            old_submission = self._database.user_tasks.find_one(
                {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]})

            if task.get_evaluate() == 'best':  # if best, update cache consequently (with best submission)
                def_sub = list(self._database.submissions.find({
                    "username": username, "courseid": task.get_course_id(),
                    "taskid": task.get_id(), "status": "done"}
                ).sort([("grade", pymongo.DESCENDING), ("submitted_on", pymongo.DESCENDING)]).limit(1))

                if len(def_sub) > 0:
                    self._database.user_tasks.find_one_and_update(
                        {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]},
                        {"$set": {
                            "succeeded": def_sub[0]["result"] == "success",
                            "grade": def_sub[0]["grade"],
                            "state": def_sub[0]["state"],
                            "submissionid": def_sub[0]['_id']
                        }})
            elif old_submission["submissionid"] == submission["_id"]:  # otherwise, update cache if needed
                self._database.user_tasks.find_one_and_update(
                    {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]},
                    {"$set": {
                        "succeeded": submission["result"] == "success",
                        "grade": submission["grade"],
                        "state": submission["state"]
                    }})
1012923
def is_pending(self):
        
        self.get_info()

        if 'status' not in self.info:
            return False
        if 'isPending' not in self.info['status']:
            return False

        return self.info['status']['isPending']
37579
public function wasAccepted()
    {
        if ( $this->hasErrors() ) {
            return false;
        }

        $aResponse = $this->getResponse();

        if ( !empty( $aResponse['pm_order_status'] ) && $aResponse['pm_order_status'] === 'ACCEPTED' ) {
            return true;
        }

        return false;
    }
1255379
def success(self):
        """"""
        self._check_valid()
        return self._problem._p.get_status() == qsoptex.SolutionStatus.OPTIMAL
541518
public function is_feedback_modified(stdClass $grade, stdClass $data) {
        global $USER;

        $filekey = null;
        $draftareainfo = null;
        foreach ($data as $key => $value) {
            if (strpos($key, 'files_') === 0 && strpos($key, '_filemanager')) {
                $filekey = $key;
            }
        }
        if (isset($filekey)) {
            $draftareainfo = file_get_draft_area_info($data->$filekey);
            $filecount = $this->count_files($grade->id, ASSIGNFEEDBACK_FILE_FILEAREA);
            if ($filecount != $draftareainfo['filecount']) {
                return true;
            } else {
                // We need to check that the files in the draft area are the same as in the file area.
                $usercontext = context_user::instance($USER->id);
                $fs = get_file_storage();
                $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $data->$filekey, 'id', true);
                $files = $fs->get_area_files($this->assignment->get_context()->id,
                                     'assignfeedback_file',
                                     ASSIGNFEEDBACK_FILE_FILEAREA,
                                     $grade->id,
                                     'id',
                                     false);
                foreach ($files as $key => $file) {
                    // Flag for recording if we have a matching file.
                    $matchflag = false;
                    foreach ($draftfiles as $draftkey => $draftfile) {
                        if (!$file->is_directory()) {
                            // File name is the same, but it could be a different file with the same name.
                            if ($draftfile->get_filename() == $file->get_filename()) {
                                // If the file name is the same but the content hash is different, or
                                // The file path for the file has changed, then we have a modification.
                                if ($draftfile->get_contenthash() != $file->get_contenthash() ||
                                        $draftfile->get_filepath() != $file->get_filepath()) {
                                    return true;
                                }
                                // These files match. Check the next file.
                                $matchflag = true;
                                // We have a match on the file name so we can move to the next file and not
                                // proceed through the other draftfiles.
                                break;
                            }
                        }
                    }
                    // If the file does not match then there has been a modification.
                    if (!$matchflag) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
986397
def check(self):
        """"""
        if not self.date:
            raise XnDataError("Missing date")
        if not self.desc:
            raise XnDataError("Missing description")
        if not self.dst:
            raise XnDataError("No destination accounts")
        if not self.src:
            raise XnDataError("No source accounts")
        if not self.amount:
            raise XnDataError("No transaction amount")
331647
def check(sentence):
    """"""

    # How we decide what to put as the human readable feedback
    #
    # Our order of prefence is,
    #
    # 1. Spelling errors.
    #   - A spelling error can change the sentence meaning
    # 2. Subject-verb agreement errors
    # 3. Subordinate conjunction starting a sentence
    # 4. Participle phrase fragment
    # 5. Other errors

    result = Feedback()
    is_missing_verb = detect_missing_verb(sentence)
    is_infinitive = detect_infinitive_phrase(sentence)
    is_participle = is_participle_clause_fragment(sentence)
    lang_tool_feedback = get_language_tool_feedback(sentence)
    subject_and_verb_agree = get_subject_verb_agreement_feedback(sentence)
    ####
    if is_missing_verb: # Lowest priority
        result.matches['missing_verb'] = True 
        result.human_readable = MISSING_VERB_ADVICE.replace('\n', '') 
        result.primary_error = 'MISSING_VERB_ERROR'
        result.specific_error = 'MISSING_VERB'
    if is_participle > .5: 
        result.matches['participle_phrase'] = is_participle
        result.human_readable = PARTICIPLE_FRAGMENT_ADVICE.replace('\n', '')
        result.primary_error = 'FRAGMENT_ERROR'
        result.specific_error = 'PARTICIPLE_PHRASE'
    if lang_tool_feedback:
        result.matches['lang_tool'] = lang_tool_feedback
        for ltf in lang_tool_feedback:
            if ltf['rule']['id'] == 'SENTENCE_FRAGMENT':
                result.human_readable = lang_tool_feedback[0]['message']
                result.primary_error = 'FRAGMENT_ERROR'
                result.specific_error = 'SUBORDINATE_CLAUSE'
    if is_infinitive:
        result.matches['infinitive_phrase'] = True 
        result.human_readable = INFINITIVE_PHRASE_ADVICE.replace('\n', '') 
        result.primary_error = 'INFINITIVE_PHRASE_ERROR'
        result.specific_error = 'INFINITIVE_PHRASE'
    if not subject_and_verb_agree:
        result.matches['subject_verb_agreement'] = subject_and_verb_agree
        result.human_readable = SUBJECT_VERB_AGREEMENT_ADVICE.replace('\n', '') 
        result.primary_error = 'SUBJECT_VERB_AGREEMENT_ERROR'
        result.specific_error = 'SUBJECT_VERB_AGREEMENT'
    if lang_tool_feedback: # Highest priority (spelling, other lang tool errors)
        result.matches['lang_tool'] = lang_tool_feedback
        for ltf in lang_tool_feedback:
            if ltf['rule']['id'] == 'MORFOLOGIK_RULE_EN_US':
                result.human_readable = ltf['message']
                result.primary_error = 'SPELLING_ERROR'
                result.specific_error = 'SPELLING_ERROR'
        if not result.primary_error:
            result.human_readable = ltf['message']
            result.primary_error = 'OTHER_ERROR'
            result.specific_error = ltf['rule']['id']

         
    ####
    if not result.matches:
        result.human_readable = STRONG_SENTENCE_ADVICE.replace('\n', '')

    return result
232910
def post_grade(self, grade):
        
        message_identifier_id = self.message_identifier_id()
        operation = 'replaceResult'
        lis_result_sourcedid = self.lis_result_sourcedid
        # # edX devbox fix
        score = float(grade)
        if 0 <= score <= 1.0:
            xml = generate_request_xml(
                message_identifier_id, operation, lis_result_sourcedid,
                score)
            ret = post_message(self._consumers(), self.key,
                               self.response_url, xml)
            if not ret:
                raise LTIPostMessageException("Post Message Failed")
            return True

        return False
484187
def check_status(self, delay=0):
        
        if not self.item_id:
            while not self._request_status():
                # wait until _request_status returns True
                yield self.status, self.completion_percentage
                if self.item_id is None:
                    sleep(delay)
        else:
            yield self.status, self.completion_percentage
24487
async function getUsersIdsToNotify(thing, checkValueAccess) {
	
	if (!thing)
		throw new utils.ErrorCustom(httpStatusCodes.INTERNAL_SERVER_ERROR, "Thing can't be null", 26);
	
	let UsersIdsToNotify = new Set();
	
	for(let r of thing.usersRights) {
	
		if (!(
			((r.userStatus & (thConstants.ThingUserStates.Ok | thConstants.ThingUserStates.WaitForAuth)) != 0) &&
				((r.userVisibility & thConstants.ThingUserVisibility.Visible) != 0))
		)
			continue;

		let userId = r.userId;
		let username = r.username;
	
		if (!userId && !username)
			throw new utils.ErrorCustom(httpStatusCodes.INTERNAL_SERVER_ERROR, "Both userId and username can't be empty", 27);
		
		let user = userId ? await usersManager.findUserById(userId) : await	usersManager.findUserByUsername(username);
		if (!user)
			continue;

		if (checkValueAccess) {
			let thingUserClaims = getThingUserClaims(user, thing, user.isSuperAdministrator);
			if ((thingUserClaims.change & thConstants.ThingUserChangeClaims.CanChangeValue) == 0)
				continue;
		}
			
		UsersIdsToNotify.add(userId);
	}
	
	return UsersIdsToNotify;
}
461020
public function display_grade($grade, $editable, $userid, $modified) {
        if ($this->is_downloading()) {
            if ($this->assignment->get_instance()->grade >= 0) {
                if ($grade == -1 || $grade === null) {
                    return '';
                }
                $gradeitem = $this->assignment->get_grade_item();
                return format_float($grade, $gradeitem->get_decimals());
            } else {
                // This is a custom scale.
                $scale = $this->assignment->display_grade($grade, false);
                if ($scale == '-') {
                    $scale = '';
                }
                return $scale;
            }
        }
        return $this->assignment->display_grade($grade, $editable, $userid, $modified);
    }