Median mark.

http://docs.moodle.org/dev/Quiz_statistics_calculations#Median_Score

@param $s integer count of attempts
@param $fromqa string
@param $whereqa string
@param $qaparams string
@return float
487460
protected function median($s, $fromqa, $whereqa, $qaparams) {
        global $DB;

        if ($s % 2 == 0) {
            // An even number of attempts.
            $limitoffset = $s / 2 - 1;
            $limit = 2;
        } else {
            $limitoffset = floor($s / 2);
            $limit = 1;
        }
        $sql = "SELECT quiza.id, quiza.sumgrades
                  FROM $fromqa
                 WHERE $whereqa
              ORDER BY sumgrades";

        $medianmarks = $DB->get_records_sql_menu($sql, $qaparams, $limitoffset, $limit);

        return array_sum($medianmarks) / count($medianmarks);
    }
1206626
public function format($seconds, $params = null, $locale = null) {
		if ($seconds == 0) {
			return 0;
		}
			
		if ($seconds < 0.01) {
			return round($seconds * 1000, 2) . 'ms';
		}

		if ($seconds < 0.1) {
			return round($seconds * 1000, 1) . 'ms';
		}

		if ($seconds < 1) {
			return round($seconds * 1000) . 'ms';
		}

		if ($seconds < 10) {
			return round($seconds, 2) . 's';
		}	
			
		return round($seconds, 1) . 's';
	}
887472
protected function col_number($questionstat) {
        if ($this->is_calculated_question_summary($questionstat)) {
            return '';
        }
        if (!isset($questionstat->question->number)) {
            return '';
        }
        $number = $questionstat->question->number;

        if (isset($questionstat->subqdisplayorder)) {
            $number = $number . '.'.$questionstat->subqdisplayorder;
        }

        if ($questionstat->question->qtype != 'random' && !is_null($questionstat->variant)) {
            $number = $number . '.'.$questionstat->variant;
        }

        return $number;
    }
699715
private function fourBytesToInt($s)
	{
		return (ord($s[0]) << 24) + (ord($s[1]) << 16) + (ord($s[2]) << 8) + ord($s[3]);
	}
1155649
public function standard_mark_summary(question_attempt $qa, qbehaviour_renderer $behaviouroutput, question_display_options $options) {
        if (!$options->marks) {
            return '';

        } else if ($qa->get_max_mark() == 0) {
            return get_string('notgraded', 'question');

        } else if ($options->marks == question_display_options::MAX_ONLY ||
                is_null($qa->get_fraction())) {
            return $behaviouroutput->marked_out_of_max($qa, $this, $options);

        } else {
            return $behaviouroutput->mark_out_of_max($qa, $this, $options);
        }
    }
715931
public static function convertMetric( $value, $from, $to, $precision = null ) {
        switch ($from . $to) {
            case 'incm':
                $value *= 2.54;
                break;
            case 'inmm':
                $value *= 25.4;
                break;
            case 'inpt':
                $value *= 72;
                break;
            case 'cmin':
                $value /= 2.54;
                break;
            case 'cmmm':
                $value *= 10;
                break;
            case 'cmpt':
                $value *= 72 / 2.54;
                break;
            case 'mmin':
                $value /= 25.4;
                break;
            case 'mmcm':
                $value /= 10;
                break;
            case 'mmpt':
                $value *= 72 / 25.4;
                break;
            case 'ptin':
                $value /= 72;
                break;
            case 'ptcm':
                $value *= 2.54 / 72;
                break;
            case 'ptmm':
                $value *= 25.4 / 72;
                break;
        }

        if ( !is_null($precision) ) {
            $value = round($value, $precision);
        }

        return $value;
    }
274693
def medianscore(inlist):
    

    newlist = copy.deepcopy(inlist)
    newlist.sort()
    if len(newlist) % 2 == 0:   # if even number of scores, average middle 2
        index = len(newlist) / 2  # integer division correct
        median = float(newlist[index] + newlist[index - 1]) / 2
    else:
        index = len(newlist) / 2  # int divsion gives mid value when count from 0
        median = newlist[index]
    return median
425046
public static int cusolverSpXcsrsymmdqHost(
        cusolverSpHandle handle, 
        int n, 
        int nnzA, 
        cusparseMatDescr descrA, 
        Pointer csrRowPtrA, 
        Pointer csrColIndA, 
        Pointer p)
    {
        return checkResult(cusolverSpXcsrsymmdqHostNative(handle, n, nnzA, descrA, csrRowPtrA, csrColIndA, p));
    }
922249
protected function median($values) {
        $count = count($values);

        if ($count === 1) {
            return reset($values);
        }

        $middlevalue = (int)floor(($count - 1) / 2);

        if ($count % 2) {
            // Odd number, middle is the median.
            $median = $values[$middlevalue];
        } else {
            // Even number, calculate avg of 2 medians.
            $low = $values[$middlevalue];
            $high = $values[$middlevalue + 1];
            $median = (($low + $high) / 2);
        }
        return intval($median);
    }
320950
def qqgraph(h1, h2, quantiles=None):
    
    if quantiles is None:
        quantiles = max(min(len(h1), len(h2)) / 2, 1)
    nq = quantiles
    # position where to compute the quantiles in [0, 1]
    xq = array('d', [0.] * nq)
    # array to contain the quantiles
    yq1 = array('d', [0.] * nq)
    # array to contain the quantiles
    yq2 = array('d', [0.] * nq)

    for i in range(nq):
        xq[i] = float(i + 1) / nq

    h1.GetQuantiles(nq, yq1, xq)
    h2.GetQuantiles(nq, yq2, xq)

    xq_plus = array('d', [0.] * nq)
    xq_minus = array('d', [0.] * nq)
    yq2_plus = array('d', [0.] * nq)
    yq2_minus = array('d', [0.] * nq)

    """
    KS_cv: KS critical value

               1.36
    KS_cv = -----------
             sqrt( N )

    Where 1.36 is for alpha = 0.05 (confidence level 1-5%=95%, about 2 sigma)

    For 1 sigma (alpha=0.32, CL=68%), the value in the nominator is 0.9561,
    it is gotten by GetCriticalValue(1, 1 - 0.68).

    Notes
    -----

    * For 1-sample KS test (data and theoretic), N should be n

    * For 2-sample KS test (2 data set), N should be sqrt(m*n/(m+n))!
      Here is the case m or n (size of samples) should be effective size
      for a histogram

    * Critical value here is valid for only for sample size >= 80 (some
      references say 35) which means, for example, for a unweighted histogram,
      it must have more than 80 (or 35) entries filled and then confidence
      band is reliable.

    """

    esum1 = effective_sample_size(h1)
    esum2 = effective_sample_size(h2)

    # one sigma band
    KS_cv = (critical_value(1, 1 - 0.68) /
             sqrt((esum1 * esum2) / (esum1 + esum2)))

    for i in range(nq):
        # upper limit
        xq_plus[i] = float(xq[i] + KS_cv)
        # lower limit
        xq_minus[i] = float(xq[i] - KS_cv)

    h2.GetQuantiles(nq, yq2_plus, xq_plus)
    h2.GetQuantiles(nq, yq2_minus, xq_minus)

    yq2_err_plus = array('d', [0.] * nq)
    yq2_err_minus = array('d', [0.] * nq)
    for i in range(nq):
        yq2_err_plus[i] = yq2_plus[i] - yq2[i]
        yq2_err_minus[i] = yq2[i] - yq2_minus[i]

    # forget the last point, so number of points: (nq - 1)
    gr = Graph(nq - 1)
    for i in range(nq - 1):
        gr[i] = (yq1[i], yq2[i])
        # confidence level band
        gr.SetPointEYlow(i, yq2_err_minus[i])
        gr.SetPointEYhigh(i, yq2_err_plus[i])

    return gr
1283087
function count($table, $where, $where_params = null)
    {
        $sql = "SELECT COUNT(*) FROM " . $table . $this->buildWhere($where);
        $stmt = $this->executeQuery($sql, $where_params);

        return $stmt->fetchColumn();
    }
808411
function tscore() {
    var args = slice.call(arguments);
    return (args.length === 4) ?
      ((args[0] - args[1]) / (args[2] / Math.sqrt(args[3]))) :
      ((args[0] - jStat.mean(args[1])) /
       (jStat.stdev(args[1], true) / Math.sqrt(args[1].length)));
  }
454060
@Override protected double score1(Chunk[] chks, double weight, double offset, double[/*nclass*/] fs, int row) {
    return score1static(chks, idx_tree(0), offset, fs, row, new Distribution(_parms), _nclass);
  }
44595
public static function iqr(array $values) : float
    {
        $n = count($values);

        if ($n < 1) {
            throw new InvalidArgumentException('Interquartile range is not'
                . ' defined for empty set.');
        }

        $mid = intdiv($n, 2);

        sort($values);

        if ($n % 2 === 0) {
            $lower = array_slice($values, 0, $mid);
            $upper = array_slice($values, $mid);
        } else {
            $lower = array_slice($values, 0, $mid);
            $upper = array_slice($values, $mid + 1);
        }

        return self::median($upper) - self::median($lower);
    }
5653
function descStats(sample) {
    var S = [].concat(sample);
    S.sort(function sortOrder(a, b) {
        return a - b;
    });
    var N = S.length;
    var q1 = S[Math.floor(0.25 * N)];
    var q2 = S[Math.floor(0.50 * N)];
    var q3 = S[Math.floor(0.70 * N)];
    var iqr = q3 - q1;
    var tol = 3 * iqr / 2;
    var hi = q3 + tol;
    var whiIndex = N;
    while (--whiIndex > 0) {
        if (S[whiIndex] <= hi) {
            break;
        }
    }
    var whiPct = (whiIndex + 1) / N;
    var whi = S[whiIndex];
    return {
        min: S[0],
        max: S[N - 1],
        q1: q1,
        q2: q2,
        q3: q3,
        hi: hi,
        whi: whi,
        whiPct: whiPct
    };
}
1292308
def get_phi_ss_at_quantile(phi_model, quantile):
    
    # Setup SA coeffs - the backward compatible Python 2.7 way
    coeffs = deepcopy(phi_model.sa_coeffs)
    coeffs.update(phi_model.non_sa_coeffs)
    for imt in coeffs:
        if quantile is None:
            coeffs[imt] = {"a": phi_model[imt]["mean_a"],
                           "b": phi_model[imt]["mean_b"]}
        else:
            coeffs[imt] = {
                "a": _at_percentile(phi_model[imt]["mean_a"],
                                    phi_model[imt]["var_a"],
                                    quantile),
                "b": _at_percentile(phi_model[imt]["mean_b"],
                                    phi_model[imt]["var_b"],
                                    quantile)
                }
    return CoeffsTable(sa_damping=5., table=coeffs)
434350
public static void updateScore(FatCatParameters params, AFPChain afpChain)
	{
		int     i, j, bknow, bkold, g1, g2;


		afpChain.setConn(0d);
		afpChain.setDVar(0d);

		int blockNum = afpChain.getBlockNum();
		int alignScoreUpdate = 0;
		double[] blockScore = afpChain.getBlockScore();
		int[] blockGap = afpChain.getBlockGap();
		int[] blockSize =afpChain.getBlockSize();
		int[] afpChainList = afpChain.getAfpChainList();
		List<AFP>afpSet = afpChain.getAfpSet();
		int[] block2Afp = afpChain.getBlock2Afp();

		double torsionPenalty = params.getTorsionPenalty();


		bkold = 0;
		for(i = 0; i < blockNum; i ++)  {
			blockScore[i] = 0;
			blockGap[i] = 0;
			for(j = 0; j < blockSize[i]; j ++)      {
				bknow = afpChainList[block2Afp[i] + j];
				if(j == 0)      {
					blockScore[i] = afpSet.get(bknow).getScore();
				}
				else    {
					AFPChainer.afpPairConn(bkold, bknow, params, afpChain); //note: j, i
					Double conn = afpChain.getConn();
					blockScore[i] += afpSet.get(bknow).getScore() + conn;
					g1 = afpSet.get(bknow).getP1() - afpSet.get(bkold).getP1() - afpSet.get(bkold).getFragLen();
					g2 = afpSet.get(bknow).getP2() - afpSet.get(bkold).getP2() - afpSet.get(bkold).getFragLen();
					blockGap[i] += (g1 > g2)?g1:g2;
				}
				bkold = bknow;
			}
			alignScoreUpdate += blockScore[i];
		}
		if(blockNum >= 2)       {
			alignScoreUpdate += (blockNum - 1) * torsionPenalty;
		}

		afpChain.setBlockGap(blockGap);
		afpChain.setAlignScoreUpdate(alignScoreUpdate);
		afpChain.setBlockScore(blockScore);
		afpChain.setBlockSize(blockSize);
		afpChain.setAfpChainList(afpChainList);
		afpChain.setBlock2Afp(block2Afp);
	}