<commit_before>'use strict';

function compareNumbers(a, b) {
    return a - b;
}

/**
 * Computes the sum of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.sum = function sum(values) {
    var sum = 0;
    for (var i = 0; i < values.length; i++) {
        sum += values[i];
    }
    return sum;
};

/**
 * Computes the maximum of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.max = function max(values) {
    var max = values[0];
    var l = values.length;
    for (var i = 1; i < l; i++) {
        if (values[i] > max) max = values[i];
    }
    return max;
};

/**
 * Computes the minimum of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.min = function min(values) {
    var min = values[0];
    var l = values.length;
    for (var i = 1; i < l; i++) {
        if (values[i] < min) min = values[i];
    }
    return min;
};

/**
 * Computes the min and max of the given values
 * @param {Array} values
 * @returns {{min: number, max: number}}
 */
exports.minMax = function minMax(values) {
    var min = values[0];
    var max = values[0];
    var l = values.length;
    for (var i = 1; i < l; i++) {
        if (values[i] < min) min = values[i];
        if (values[i] > max) max = values[i];
    }
    return {
        min: min,
        max: max
    };
};

/**
 * Computes the arithmetic mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.arithmeticMean = function arithmeticMean(values) {
    var sum = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        sum += values[i];
    }
    return sum / l;
};

/**
 * {@link arithmeticMean}
 */
exports.mean = exports.arithmeticMean;

/**
 * Computes the geometric mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.geometricMean = function geometricMean(values) {
    var mul = 1;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        mul *= values[i];
    }
    return Math.pow(mul, 1 / l);
};

/**
 * Computes the mean of the log of the given values
 * If the return value is exponentiated, it gives the same result as the
 * geometric mean.
 * @param {Array} values
 * @returns {number}
 */
exports.logMean = function logMean(values) {
    var lnsum = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        lnsum += Math.log(values[i]);
    }
    return lnsum / l;
};

/**
 * Computes the weighted grand mean for a list of means and sample sizes
 * @param {Array} means - Mean values for each set of samples
 * @param {Array} samples - Number of original values for each set of samples
 * @returns {number}
 */
exports.grandMean = function grandMean(means, samples) {
    var sum = 0;
    var n = 0;
    var l = means.length;
    for (var i = 0; i < l; i++) {
        sum += samples[i] * means[i];
        n += samples[i];
    }
    return sum / n;
};

/**
 * Computes the truncated mean of the given values using a given percentage
 * @param {Array} values
 * @param {number} percent - The percentage of values to keep (range: [0,1])
 * @param {boolean} [alreadySorted=false]
 * @returns {number}
 */
exports.truncatedMean = function truncatedMean(values, percent, alreadySorted) {
    if (alreadySorted === undefined) alreadySorted = false;
    if (!alreadySorted) {
        values = [].concat(values).sort(compareNumbers);
    }
    var l = values.length;
    var k = Math.floor(l * percent);
    var sum = 0;
    for (var i = k; i < (l - k); i++) {
        sum += values[i];
    }
    return sum / (l - 2 * k);
};

/**
 * Computes the harmonic mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.harmonicMean = function harmonicMean(values) {
    var sum = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        if (values[i] === 0) {
            throw new RangeError('value at index ' + i + 'is zero');
        }
        sum += 1 / values[i];
    }
    return l / sum;
};

/**
 * Computes the contraharmonic mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.contraHarmonicMean = function contraHarmonicMean(values) {
    var r1 = 0;
    var r2 = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        r1 += values[i] * values[i];
        r2 += values[i];
    }
    if (r2 < 0) {
        throw new RangeError('sum of values is negative');
    }
    return r1 / r2;
};

/**
 * Computes the median of the given values
 * @param {Array} values
 * @param {boolean} [alreadySorted=false]
 * @returns {number}
 */
exports.median = function median(values, alreadySorted) {
    if (alreadySorted === undefined) alreadySorted = false;
    if (!alreadySorted) {
        values = [].concat(values).sort(compareNumbers);
    }
    var l = values.length;
    var half = Math.floor(l / 2);
    if (l % 2 === 0) {
        return (values[half - 1] + values[half]) * 0.5;
    } else {
        return values[half];
    }
};

/**
 * Computes the variance of the given values
 * @param {Array} values
 * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.
 * @returns {number}
 */
exports.variance = function variance(values, unbiased) {
    if (unbiased === undefined) unbiased = true;
    var theMean = exports.mean(values);
    var theVariance = 0;
    var l = values.length;

    for (var i = 0; i < l; i++) {
        var x = values[i] - theMean;
        theVariance += x * x;
    }

    if (unbiased) {
        return theVariance / (l - 1);
    } else {
        return theVariance / l;
    }
};

/**
 * Computes the standard deviation of the given values
 * @param {Array} values
 * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.
 * @returns {number}
 */
exports.standardDeviation = function standardDeviation(values, unbiased) {
    return Math.sqrt(exports.variance(values, unbiased));
};

exports.standardError = function standardError(values) {
    return exports.standardDeviation(values) / Math.sqrt(values.length);
};

/**
 * @function robustMeanAndStddev()
 * IEEE Transactions on biomedical engineering, vol. 52, no. 1, january 2005, p. 76-
 * Calculate the standard deviation via the Median of the absolute deviation
 *  The formula for the standard deviation only holds for Gaussian random variables.
 * @returns {number}
 */
function robustMeanAndStddev(y){
    var mean = 0,stddev=0;
    var length = y.length,i=0;
    for(i = 0; i < length; i++){
        mean+=y[i];
    }
    mean/=length;
    var averageDeviations = new Array(length);
    for (i = 0; i < length; i++)
        averageDeviations[i] = Math.abs(y[i] - mean);
    averageDeviations.sort();
    if (length % 2 == 1) {
        stddev = averageDeviations[(length-1)/2] / 0.6745;
    } else {
        stddev = 0.5*(averageDeviations[length/2]+averageDeviations[length/2-1]) / 0.6745;
    }

    return [mean, stddev];
}

exports.quartiles = function quartiles(values, alreadySorted) {
    if (typeof(alreadySorted) === 'undefined') alreadySorted = false;
    if (!alreadySorted) {
        values = [].concat(values).sort(compareNumbers);
    }

    var quart = values.length / 4;
    var q1 = values[Math.ceil(quart) - 1];
    var q2 = exports.median(values, true);
    var q3 = values[Math.ceil(quart * 3) - 1];

    return {q1: q1, q2: q2, q3: q3};
};

exports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) {
    return Math.sqrt(exports.pooledVariance(samples, unbiased));
};

exports.pooledVariance = function pooledVariance(samples, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var sum = 0;
    var length = 0, l = samples.length;
    for (var i = 0; i < l; i++) {
        var values = samples[i];
        var vari = exports.variance(values);

        sum += (values.length - 1) * vari;

        if (unbiased)
            length += values.length - 1;
        else
            length += values.length;
    }
    return sum / length;
};

exports.mode = function mode(values) {
    var l = values.length,
        itemCount = new Array(l),
        i;
    for (i = 0; i < l; i++) {
        itemCount[i] = 0;
    }
    var itemArray = new Array(l);
    var count = 0;

    for (i = 0; i < l; i++) {
        var index = itemArray.indexOf(values[i]);
        if (index >= 0)
            itemCount[index]++;
        else {
            itemArray[count] = values[i];
            itemCount[count] = 1;
            count++;
        }
    }

    var maxValue = 0, maxIndex = 0;
    for (i = 0; i < count; i++) {
        if (itemCount[i] > maxValue) {
            maxValue = itemCount[i];
            maxIndex = i;
        }
    }

    return itemArray[maxIndex];
};

exports.covariance = function covariance(vector1, vector2, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var mean1 = exports.mean(vector1);
    var mean2 = exports.mean(vector2);

    if (vector1.length !== vector2.length)
        throw "Vectors do not have the same dimensions";

    var cov = 0, l = vector1.length;
    for (var i = 0; i < l; i++) {
        var x = vector1[i] - mean1;
        var y = vector2[i] - mean2;
        cov += x * y;
    }

    if (unbiased)
        return cov / (l - 1);
    else
        return cov / l;
};

exports.skewness = function skewness(values, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var theMean = exports.mean(values);

    var s2 = 0, s3 = 0, l = values.length;
    for (var i = 0; i < l; i++) {
        var dev = values[i] - theMean;
        s2 += dev * dev;
        s3 += dev * dev * dev;
    }
    var m2 = s2 / l;
    var m3 = s3 / l;

    var g = m3 / (Math.pow(m2, 3 / 2.0));
    if (unbiased) {
        var a = Math.sqrt(l * (l - 1));
        var b = l - 2;
        return (a / b) * g;
    }
    else {
        return g;
    }
};

exports.kurtosis = function kurtosis(values, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var theMean = exports.mean(values);
    var n = values.length, s2 = 0, s4 = 0;

    for (var i = 0; i < n; i++) {
        var dev = values[i] - theMean;
        s2 += dev * dev;
        s4 += dev * dev * dev * dev;
    }
    var m2 = s2 / n;
    var m4 = s4 / n;

    if (unbiased) {
        var v = s2 / (n - 1);
        var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));
        var b = s4 / (v * v);
        var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));

        return a * b - 3 * c;
    }
    else {
        return m4 / (m2 * m2) - 3;
    }
};

exports.entropy = function entropy(values, eps) {
    if (typeof(eps) === 'undefined') eps = 0;
    var sum = 0, l = values.length;
    for (var i = 0; i < l; i++)
        sum += values[i] * Math.log(values[i] + eps);
    return -sum;
};

exports.weightedMean = function weightedMean(values, weights) {
    var sum = 0, l = values.length;
    for (var i = 0; i < l; i++)
        sum += values[i] * weights[i];
    return sum;
};

exports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) {
    return Math.sqrt(exports.weightedVariance(values, weights));
};

exports.weightedVariance = function weightedVariance(values, weights) {
    var theMean = exports.weightedMean(values, weights);
    var vari = 0, l = values.length;
    var a = 0, b = 0;

    for (var i = 0; i < l; i++) {
        var z = values[i] - theMean;
        var w = weights[i];

        vari += w * (z * z);
        b += w;
        a += w * w;
    }

    return vari * (b / (b * b - a));
};

exports.center = function center(values, inPlace) {
    if (typeof(inPlace) === 'undefined') inPlace = false;

    var result = values;
    if (!inPlace)
        result = [].concat(values);

    var theMean = exports.mean(result), l = result.length;
    for (var i = 0; i < l; i++)
        result[i] -= theMean;
};

exports.standardize = function standardize(values, standardDev, inPlace) {
    if (typeof(standardDev) === 'undefined') standardDev = exports.standardDeviation(values);
    if (typeof(inPlace) === 'undefined') inPlace = false;
    var l = values.length;
    var result = inPlace ? values : new Array(l);
    for (var i = 0; i < l; i++)
        result[i] = values[i] / standardDev;
    return result;
};

exports.cumulativeSum = function cumulativeSum(array) {
    var l = array.length;
    var result = new Array(l);
    result[0] = array[0];
    for (var i = 1; i < l; i++)
        result[i] = result[i - 1] + array[i];
    return result;
};
<commit_msg>Fix function format<commit_after>'use strict';

function compareNumbers(a, b) {
    return a - b;
}

/**
 * Computes the sum of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.sum = function sum(values) {
    var sum = 0;
    for (var i = 0; i < values.length; i++) {
        sum += values[i];
    }
    return sum;
};

/**
 * Computes the maximum of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.max = function max(values) {
    var max = values[0];
    var l = values.length;
    for (var i = 1; i < l; i++) {
        if (values[i] > max) max = values[i];
    }
    return max;
};

/**
 * Computes the minimum of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.min = function min(values) {
    var min = values[0];
    var l = values.length;
    for (var i = 1; i < l; i++) {
        if (values[i] < min) min = values[i];
    }
    return min;
};

/**
 * Computes the min and max of the given values
 * @param {Array} values
 * @returns {{min: number, max: number}}
 */
exports.minMax = function minMax(values) {
    var min = values[0];
    var max = values[0];
    var l = values.length;
    for (var i = 1; i < l; i++) {
        if (values[i] < min) min = values[i];
        if (values[i] > max) max = values[i];
    }
    return {
        min: min,
        max: max
    };
};

/**
 * Computes the arithmetic mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.arithmeticMean = function arithmeticMean(values) {
    var sum = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        sum += values[i];
    }
    return sum / l;
};

/**
 * {@link arithmeticMean}
 */
exports.mean = exports.arithmeticMean;

/**
 * Computes the geometric mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.geometricMean = function geometricMean(values) {
    var mul = 1;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        mul *= values[i];
    }
    return Math.pow(mul, 1 / l);
};

/**
 * Computes the mean of the log of the given values
 * If the return value is exponentiated, it gives the same result as the
 * geometric mean.
 * @param {Array} values
 * @returns {number}
 */
exports.logMean = function logMean(values) {
    var lnsum = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        lnsum += Math.log(values[i]);
    }
    return lnsum / l;
};

/**
 * Computes the weighted grand mean for a list of means and sample sizes
 * @param {Array} means - Mean values for each set of samples
 * @param {Array} samples - Number of original values for each set of samples
 * @returns {number}
 */
exports.grandMean = function grandMean(means, samples) {
    var sum = 0;
    var n = 0;
    var l = means.length;
    for (var i = 0; i < l; i++) {
        sum += samples[i] * means[i];
        n += samples[i];
    }
    return sum / n;
};

/**
 * Computes the truncated mean of the given values using a given percentage
 * @param {Array} values
 * @param {number} percent - The percentage of values to keep (range: [0,1])
 * @param {boolean} [alreadySorted=false]
 * @returns {number}
 */
exports.truncatedMean = function truncatedMean(values, percent, alreadySorted) {
    if (alreadySorted === undefined) alreadySorted = false;
    if (!alreadySorted) {
        values = [].concat(values).sort(compareNumbers);
    }
    var l = values.length;
    var k = Math.floor(l * percent);
    var sum = 0;
    for (var i = k; i < (l - k); i++) {
        sum += values[i];
    }
    return sum / (l - 2 * k);
};

/**
 * Computes the harmonic mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.harmonicMean = function harmonicMean(values) {
    var sum = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        if (values[i] === 0) {
            throw new RangeError('value at index ' + i + 'is zero');
        }
        sum += 1 / values[i];
    }
    return l / sum;
};

/**
 * Computes the contraharmonic mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.contraHarmonicMean = function contraHarmonicMean(values) {
    var r1 = 0;
    var r2 = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        r1 += values[i] * values[i];
        r2 += values[i];
    }
    if (r2 < 0) {
        throw new RangeError('sum of values is negative');
    }
    return r1 / r2;
};

/**
 * Computes the median of the given values
 * @param {Array} values
 * @param {boolean} [alreadySorted=false]
 * @returns {number}
 */
exports.median = function median(values, alreadySorted) {
    if (alreadySorted === undefined) alreadySorted = false;
    if (!alreadySorted) {
        values = [].concat(values).sort(compareNumbers);
    }
    var l = values.length;
    var half = Math.floor(l / 2);
    if (l % 2 === 0) {
        return (values[half - 1] + values[half]) * 0.5;
    } else {
        return values[half];
    }
};

/**
 * Computes the variance of the given values
 * @param {Array} values
 * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.
 * @returns {number}
 */
exports.variance = function variance(values, unbiased) {
    if (unbiased === undefined) unbiased = true;
    var theMean = exports.mean(values);
    var theVariance = 0;
    var l = values.length;

    for (var i = 0; i < l; i++) {
        var x = values[i] - theMean;
        theVariance += x * x;
    }

    if (unbiased) {
        return theVariance / (l - 1);
    } else {
        return theVariance / l;
    }
};

/**
 * Computes the standard deviation of the given values
 * @param {Array} values
 * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.
 * @returns {number}
 */
exports.standardDeviation = function standardDeviation(values, unbiased) {
    return Math.sqrt(exports.variance(values, unbiased));
};

exports.standardError = function standardError(values) {
    return exports.standardDeviation(values) / Math.sqrt(values.length);
};

/**
 * @function robustMeanAndStddev()
 * IEEE Transactions on biomedical engineering, vol. 52, no. 1, january 2005, p. 76-
 * Calculate the standard deviation via the Median of the absolute deviation
 *  The formula for the standard deviation only holds for Gaussian random variables.
 * @returns {number}
 */
exports.robustMeanAndStddev = function robustMeanAndStddev(y){
    var mean = 0,stddev=0;
    var length = y.length,i=0;
    for(i = 0; i < length; i++){
        mean+=y[i];
    }
    mean/=length;
    var averageDeviations = new Array(length);
    for (i = 0; i < length; i++)
        averageDeviations[i] = Math.abs(y[i] - mean);
    averageDeviations.sort();
    if (length % 2 == 1) {
        stddev = averageDeviations[(length-1)/2] / 0.6745;
    } else {
        stddev = 0.5*(averageDeviations[length/2]+averageDeviations[length/2-1]) / 0.6745;
    }

    return [mean, stddev];
}

exports.quartiles = function quartiles(values, alreadySorted) {
    if (typeof(alreadySorted) === 'undefined') alreadySorted = false;
    if (!alreadySorted) {
        values = [].concat(values).sort(compareNumbers);
    }

    var quart = values.length / 4;
    var q1 = values[Math.ceil(quart) - 1];
    var q2 = exports.median(values, true);
    var q3 = values[Math.ceil(quart * 3) - 1];

    return {q1: q1, q2: q2, q3: q3};
};

exports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) {
    return Math.sqrt(exports.pooledVariance(samples, unbiased));
};

exports.pooledVariance = function pooledVariance(samples, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var sum = 0;
    var length = 0, l = samples.length;
    for (var i = 0; i < l; i++) {
        var values = samples[i];
        var vari = exports.variance(values);

        sum += (values.length - 1) * vari;

        if (unbiased)
            length += values.length - 1;
        else
            length += values.length;
    }
    return sum / length;
};

exports.mode = function mode(values) {
    var l = values.length,
        itemCount = new Array(l),
        i;
    for (i = 0; i < l; i++) {
        itemCount[i] = 0;
    }
    var itemArray = new Array(l);
    var count = 0;

    for (i = 0; i < l; i++) {
        var index = itemArray.indexOf(values[i]);
        if (index >= 0)
            itemCount[index]++;
        else {
            itemArray[count] = values[i];
            itemCount[count] = 1;
            count++;
        }
    }

    var maxValue = 0, maxIndex = 0;
    for (i = 0; i < count; i++) {
        if (itemCount[i] > maxValue) {
            maxValue = itemCount[i];
            maxIndex = i;
        }
    }

    return itemArray[maxIndex];
};

exports.covariance = function covariance(vector1, vector2, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var mean1 = exports.mean(vector1);
    var mean2 = exports.mean(vector2);

    if (vector1.length !== vector2.length)
        throw "Vectors do not have the same dimensions";

    var cov = 0, l = vector1.length;
    for (var i = 0; i < l; i++) {
        var x = vector1[i] - mean1;
        var y = vector2[i] - mean2;
        cov += x * y;
    }

    if (unbiased)
        return cov / (l - 1);
    else
        return cov / l;
};

exports.skewness = function skewness(values, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var theMean = exports.mean(values);

    var s2 = 0, s3 = 0, l = values.length;
    for (var i = 0; i < l; i++) {
        var dev = values[i] - theMean;
        s2 += dev * dev;
        s3 += dev * dev * dev;
    }
    var m2 = s2 / l;
    var m3 = s3 / l;

    var g = m3 / (Math.pow(m2, 3 / 2.0));
    if (unbiased) {
        var a = Math.sqrt(l * (l - 1));
        var b = l - 2;
        return (a / b) * g;
    }
    else {
        return g;
    }
};

exports.kurtosis = function kurtosis(values, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var theMean = exports.mean(values);
    var n = values.length, s2 = 0, s4 = 0;

    for (var i = 0; i < n; i++) {
        var dev = values[i] - theMean;
        s2 += dev * dev;
        s4 += dev * dev * dev * dev;
    }
    var m2 = s2 / n;
    var m4 = s4 / n;

    if (unbiased) {
        var v = s2 / (n - 1);
        var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));
        var b = s4 / (v * v);
        var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));

        return a * b - 3 * c;
    }
    else {
        return m4 / (m2 * m2) - 3;
    }
};

exports.entropy = function entropy(values, eps) {
    if (typeof(eps) === 'undefined') eps = 0;
    var sum = 0, l = values.length;
    for (var i = 0; i < l; i++)
        sum += values[i] * Math.log(values[i] + eps);
    return -sum;
};

exports.weightedMean = function weightedMean(values, weights) {
    var sum = 0, l = values.length;
    for (var i = 0; i < l; i++)
        sum += values[i] * weights[i];
    return sum;
};

exports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) {
    return Math.sqrt(exports.weightedVariance(values, weights));
};

exports.weightedVariance = function weightedVariance(values, weights) {
    var theMean = exports.weightedMean(values, weights);
    var vari = 0, l = values.length;
    var a = 0, b = 0;

    for (var i = 0; i < l; i++) {
        var z = values[i] - theMean;
        var w = weights[i];

        vari += w * (z * z);
        b += w;
        a += w * w;
    }

    return vari * (b / (b * b - a));
};

exports.center = function center(values, inPlace) {
    if (typeof(inPlace) === 'undefined') inPlace = false;

    var result = values;
    if (!inPlace)
        result = [].concat(values);

    var theMean = exports.mean(result), l = result.length;
    for (var i = 0; i < l; i++)
        result[i] -= theMean;
};

exports.standardize = function standardize(values, standardDev, inPlace) {
    if (typeof(standardDev) === 'undefined') standardDev = exports.standardDeviation(values);
    if (typeof(inPlace) === 'undefined') inPlace = false;
    var l = values.length;
    var result = inPlace ? values : new Array(l);
    for (var i = 0; i < l; i++)
        result[i] = values[i] / standardDev;
    return result;
};

exports.cumulativeSum = function cumulativeSum(array) {
    var l = array.length;
    var result = new Array(l);
    result[0] = array[0];
    for (var i = 1; i < l; i++)
        result[i] = result[i - 1] + array[i];
    return result;
};
<|endoftext|>


<commit_before>var config = {
    "name": "Harry John",
    "taglines": [
        "Ninja Software Engineer",
        "Chasing dreams since 1993",
        "SDE II @ Amazon",
        "The odd one"
    ],
    "links": [
        {
            "label": "blog",
            "url": "/blog"
        },
        {
            "label": "github",
            "url": "https://github.com/harry671003"
        },
        {
            "label": "linkedIn",
            "url": "https://www.linkedin.com/in/harry671003"
        }
    ],
    "sections": [
        {
            "title": "Work",
            "items": [
                {
                    "label": "Software Development Engineer II",
                    "desc": "Amazon (June 2018 - Present)"
                },
                {
                    "label": "Software Engineer",
                    "desc": "Microsoft (June 2015 - May 2018)"
                }
            ]
        },
        {
            "title": "Side Projects",
            "items": [
                {
                    "label": "S.Y.L (Sylphrena)",
                    "url": "https://github.com/harry671003/syl-core",
                    "desc": "Building a bot with better context management. (2018)"
                },
                {
                    "label": "ng2-appinsights",
                    "url": "https://www.npmjs.com/package/ng2-appinsights",
                    "desc": "App insights logging for Angular 2+ apps. (2017)"
                }
            ]
        },
        {
            "title": "Education",
            "items": [
                {
                    "label": "B-Tech",
                    "desc": "Amrita Amrita Vishwa Vidyapeetham (2011 - 15)"
                }
            ]
        },
        {
            "title": "Stats",
            "items": [
                {
                    "label": "Hitting the gym",
                    "desc": "257 days"
                }
            ]
        }
    ]
}
<commit_msg>Update config.js<commit_after>var config = {
    "name": "Harry John",
    "taglines": [
        "Ninja Software Engineer",
        "Chasing dreams since 1993",
        "SDE II @ Amazon",
        "The odd one",
        "AKA @harry671003"
    ],
    "links": [
        {
            "label": "blog",
            "url": "/blog"
        },
        {
            "label": "github",
            "url": "https://github.com/harry671003"
        },
        {
            "label": "linkedIn",
            "url": "https://www.linkedin.com/in/harry671003"
        }
    ],
    "sections": [
        {
            "title": "Work",
            "items": [
                {
                    "label": "Software Development Engineer II",
                    "desc": "Amazon (June 2018 - Present)"
                },
                {
                    "label": "Software Engineer",
                    "desc": "Microsoft (June 2015 - May 2018)"
                }
            ]
        },
        {
            "title": "Side Projects",
            "items": [
                {
                    "label": "S.Y.L (Sylphrena)",
                    "url": "https://github.com/harry671003/syl-core",
                    "desc": "Building a bot with better context management. (2018)"
                },
                {
                    "label": "ng2-appinsights",
                    "url": "https://www.npmjs.com/package/ng2-appinsights",
                    "desc": "App insights logging for Angular 2+ apps. (2017)"
                }
            ]
        },
        {
            "title": "Education",
            "items": [
                {
                    "label": "B-Tech",
                    "desc": "Amrita Amrita Vishwa Vidyapeetham (2011 - 15)"
                }
            ]
        },
        {
            "title": "Stats",
            "items": [
                {
                    "label": "Hitting the gym",
                    "desc": "257 days"
                }
            ]
        }
    ]
}
<|endoftext|>


<commit_before>(function () {
    var Ext;

    Ext = window.Ext4 || window.Ext;

    Ext.define('Rally.apps.roadmapplanningboard.PlanningBoardColumn', {
        extend: 'Rally.ui.cardboard.Column',
        alias: 'widget.planningboardcolumn',
        mixins: {
            maskable: 'Rally.ui.mask.Maskable'
        },
        requires: ['Rally.apps.roadmapplanningboard.plugin.OrcaColumnDropController', 'Rally.apps.roadmapplanningboard.OrcaColumnDropTarget'],
        config: {
            stores: [],
            lowestPIType: undefined,
            dropControllerConfig: {
                ptype: 'orcacolumndropcontroller'
            }
        },

        initComponent: function () {
            this.callParent(arguments);
            return this.on('beforerender', function () {
                var cls;

                cls = 'planning-column';
                this.getContentCell().addCls(cls);
                return this.getColumnHeaderCell().addCls(cls);
            }, this, {
                single: true
            });
        },

        getStores: function () {

            if (!this.planRecord || !this.planRecord.data.features.length) {
                return [];
            }

            var filters = [];

            _.each(this.planRecord.data.features, function(feature) {
                filters.push({
                    property: 'ObjectID',
                    operator: '=',
                    value: feature.id
                });
            });

            return [
                Ext.create('Rally.data.WsapiDataStore', {
                    model: this.lowestPIType,
                    autoLoad: true,
                    fetch: ['Value','FormattedID', 'Owner','Name', 'PreliminaryEstimate'],
                    mergeFetch: true,
                    filters: Rally.data.QueryFilter.or(filters)
                })
            ];
        },

        isMatchingRecord: function () {
            return true;
        },

        _getProgressBarHtml: function () {
            return '

';
        },

        findCardInfo: function (searchCriteria, includeHiddenCards) {
            var card, index, _i, _len, _ref;

            searchCriteria = searchCriteria.get && searchCriteria.get('ObjectID') ? searchCriteria.get('ObjectID') : searchCriteria;
            _ref = this.getCards(includeHiddenCards);
            for (index = _i = 0, _len = _ref.length; _i < _len; index = ++_i) {
                card = _ref[index];
                if (card.getRecord().get('ObjectID') === searchCriteria || card.getEl() === searchCriteria || card.getEl() === Ext.get(searchCriteria)) {
                    return {
                        record: card.getRecord(),
                        index: index,
                        card: card
                    };
                }
            }
            return null;
        },

        destroy: function () {
            var plugin, _i, _len, _ref;

            _ref = this.plugins;
            for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                plugin = _ref[_i];
                if (plugin !== null) {
                    plugin.destroy();
                }
            }
            return this.callParent(arguments);
        }
    });

}).call(this);
<commit_msg>S52969: Show card info: Hiding card icons.<commit_after>(function () {
    var Ext;

    Ext = window.Ext4 || window.Ext;

    Ext.define('Rally.apps.roadmapplanningboard.PlanningBoardColumn', {
        extend: 'Rally.ui.cardboard.Column',
        alias: 'widget.planningboardcolumn',
        mixins: {
            maskable: 'Rally.ui.mask.Maskable'
        },
        requires: ['Rally.apps.roadmapplanningboard.plugin.OrcaColumnDropController', 'Rally.apps.roadmapplanningboard.OrcaColumnDropTarget'],
        config: {
            stores: [],
            lowestPIType: undefined,
            dropControllerConfig: {
                ptype: 'orcacolumndropcontroller'
            },
            cardConfig: {
                showIconsAndHighlightBorder: false
            }
        },

        initComponent: function () {
            this.callParent(arguments);
            return this.on('beforerender', function () {
                var cls;

                cls = 'planning-column';
                this.getContentCell().addCls(cls);
                return this.getColumnHeaderCell().addCls(cls);
            }, this, {
                single: true
            });
        },

        getStores: function () {

            if (!this.planRecord || !this.planRecord.data.features.length) {
                return [];
            }

            var filters = [];

            _.each(this.planRecord.data.features, function(feature) {
                filters.push({
                    property: 'ObjectID',
                    operator: '=',
                    value: feature.id
                });
            });

            return [
                Ext.create('Rally.data.WsapiDataStore', {
                    model: this.lowestPIType,
                    autoLoad: true,
                    fetch: ['Value','FormattedID', 'Owner','Name', 'PreliminaryEstimate'],
                    mergeFetch: true,
                    filters: Rally.data.QueryFilter.or(filters)
                })
            ];
        },

        isMatchingRecord: function () {
            return true;
        },

        _getProgressBarHtml: function () {
            return '

';
        },

        findCardInfo: function (searchCriteria, includeHiddenCards) {
            var card, index, _i, _len, _ref;

            searchCriteria = searchCriteria.get && searchCriteria.get('ObjectID') ? searchCriteria.get('ObjectID') : searchCriteria;
            _ref = this.getCards(includeHiddenCards);
            for (index = _i = 0, _len = _ref.length; _i < _len; index = ++_i) {
                card = _ref[index];
                if (card.getRecord().get('ObjectID') === searchCriteria || card.getEl() === searchCriteria || card.getEl() === Ext.get(searchCriteria)) {
                    return {
                        record: card.getRecord(),
                        index: index,
                        card: card
                    };
                }
            }
            return null;
        },

        destroy: function () {
            var plugin, _i, _len, _ref;

            _ref = this.plugins;
            for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                plugin = _ref[_i];
                if (plugin !== null) {
                    plugin.destroy();
                }
            }
            return this.callParent(arguments);
        }
    });

}).call(this);
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Bruce Schubert.
 * The MIT License
 * http://www.opensource.org/licenses/mit-license
 */

/* global define, WorldWind */

/**
 * The TimeZoneLayer, derived from Open Natural Earth 10m time zones.
 *
 * See: http://www.naturalearthdata.com/downloads/10m-cultural-vectors/timezones/
 *
 * @exports TimeZoneLayer
 * @author Bruce Schubert
 */
define(['model/globe/layers/ShapefileLayer',
        'worldwind'],
    function (ShapefileLayer,
              ww) {
        "use strict";
        /**
         * Constructs a time zone layer.
         * @constructor
         */
        var TimeZoneLayer = function () {
            // Open Natural Earth 10m time zones have been simplified to .05deg resolution
            // See: http://www.naturalearthdata.com/downloads/10m-cultural-vectors/timezones/
            ShapefileLayer.call(this,
                ww.WWUtil.currentUrlSansFilePart() + "/data/timezones/ne_05deg_time_zones.shp",
                "Time Zones");
        };

        // Inherit the ShapefileLayer methods
        TimeZoneLayer.prototype = Object.create(ShapefileLayer.prototype);

        return TimeZoneLayer;
    }
);<commit_msg>Made TimeZoneLayer colors transparent.<commit_after>/*
 * Copyright (c) 2016 Bruce Schubert.
 * The MIT License
 * http://www.opensource.org/licenses/mit-license
 */

/* global define, WorldWind */

/**
 * The TimeZoneLayer, derived from Open Natural Earth 10m time zones.
 *
 * See: http://www.naturalearthdata.com/downloads/10m-cultural-vectors/timezones/
 *
 * @exports TimeZoneLayer
 * @author Bruce Schubert
 */
define(['model/globe/layers/ShapefileLayer',
        'worldwind'],
    function (ShapefileLayer,
              ww) {
        "use strict";
        /**
         * Constructs a time zone layer.
         * @constructor
         */
        var TimeZoneLayer = function () {
            var shapeConfigurationCallback = function (attributes, record) {
                var configuration = {};
                configuration.name = attributes.values.name || attributes.values.Name || attributes.values.NAME;
                configuration.attributes = new WorldWind.ShapeAttributes(null);
                // Fill the polygon with a random pastel color.
                configuration.attributes.interiorColor = new WorldWind.Color(
                    0.375 + 0.5 * Math.random(),
                    0.375 + 0.5 * Math.random(),
                    0.375 + 0.5 * Math.random(),
                    0.0);   // We must draw the interior to enable picking, but make it transparent

                // Paint the outline in a darker variant of the interior color.
                configuration.attributes.outlineColor = new WorldWind.Color(
                    0.5 * configuration.attributes.interiorColor.red,
                    0.5 * configuration.attributes.interiorColor.green,
                    0.5 * configuration.attributes.interiorColor.blue,
                    0.5);

                // Make the DBaseRecord and Layer available to picked objects
                configuration.userProperties = {record: attributes, layer: record.shapefile.layer};

                return configuration;
            };

            this._enabled = true;

            // Open Natural Earth 10m time zones have been simplified to .05deg resolution
            // See: http://www.naturalearthdata.com/downloads/10m-cultural-vectors/timezones/
            ShapefileLayer.call(this,
                ww.WWUtil.currentUrlSansFilePart() + "/data/timezones/ne_05deg_time_zones.shp",
                "Time Zones", shapeConfigurationCallback);
        };

        // Inherit the ShapefileLayer methods
        TimeZoneLayer.prototype = Object.create(ShapefileLayer.prototype);

        return TimeZoneLayer;
    }
);<|endoftext|>


<commit_before>//
//  [The "BSD license"]
//   Copyright (c) 2012 Terence Parr
//   Copyright (c) 2012 Sam Harwell
//   Copyright (c) 2014 Eric Vergnaud
//   All rights reserved.
//
//   Redistribution and use in source and binary forms, with or without
//   modification, are permitted provided that the following conditions
//   are met:
//
//   1. Redistributions of source code must retain the above copyright
//      notice, this list of conditions and the following disclaimer.
//   2. Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//   3. The name of the author may not be used to endorse or promote products
//      derived from this software without specific prior written permission.
//
//   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
//   IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//   IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
//   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//   NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
//   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
//   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

//
//  This is an InputStream that is loaded from a file all at once
//  when you construct the object.
//
var InputStream = require('./InputStream').InputStream;
var isNodeJs = typeof window === 'undefined' && importScripts === 'undefined';
var fs = isNodeJs ? require("fs") : null;

function FileStream(fileName) {
	var data = fs.readFileSync(fileName, "utf8");
	InputStream.call(this, data);
	this.fileName = fileName;
	return this;
}

FileStream.prototype = Object.create(InputStream.prototype);
FileStream.prototype.constructor = FileStream;

exports.FileStream = FileStream;
<commit_msg>was failing when ran in NodeJS<commit_after>//
//  [The "BSD license"]
//   Copyright (c) 2012 Terence Parr
//   Copyright (c) 2012 Sam Harwell
//   Copyright (c) 2014 Eric Vergnaud
//   All rights reserved.
//
//   Redistribution and use in source and binary forms, with or without
//   modification, are permitted provided that the following conditions
//   are met:
//
//   1. Redistributions of source code must retain the above copyright
//      notice, this list of conditions and the following disclaimer.
//   2. Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//   3. The name of the author may not be used to endorse or promote products
//      derived from this software without specific prior written permission.
//
//   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
//   IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//   IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
//   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//   NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
//   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
//   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

//
//  This is an InputStream that is loaded from a file all at once
//  when you construct the object.
//
var InputStream = require('./InputStream').InputStream;
var isNodeJs = typeof window === 'undefined' && typeof importScripts === 'undefined';
var fs = isNodeJs ? require("fs") : null;

function FileStream(fileName) {
	var data = fs.readFileSync(fileName, "utf8");
	InputStream.call(this, data);
	this.fileName = fileName;
	return this;
}

FileStream.prototype = Object.create(InputStream.prototype);
FileStream.prototype.constructor = FileStream;

exports.FileStream = FileStream;
<|endoftext|>


<commit_before>/**
 * Returns a function that turns a table into a datatable for displaying experiment runs
 */
define("runs/runTable", ["bootstrap", "datatables", "datatables-bootstrap", "runs/detailView"],
    function (bootstrap, datatables, dtboostrap, generateDetailView) {
        /**
         * Scrolls down in the element
         * @param obj
         */
        function scrollDown(obj) {
            $(obj).scrollTop(obj.scrollHeight);
        }

        /**
         * Turn tableElement into dataTable displaying runs.
         *
         * Returns the created table.
         * @param tableElement
         */
        var createRunTable = {};
        createRunTable.table = null;
        createRunTable.reload = function () {
            createRunTable.table.ajax.reload();
        };
        createRunTable.queryFilter = {type: "and", filters: []};

        createRunTable.initTable = function (tableElement) {
            var jqRuns = $(tableElement);
            var config = {
                colReorder: true,
                responsive: false,
                bFilter: false,

                // Scroller:
                //scrollY: window.innerHeight / 1.4,
                deferRender: true,
                //scroller: false,
                serverSide: true,
                ajax: {
                    url: "/api/run",
                    data: function (request) {
                        request.queryFilter = JSON.stringify(createRunTable.queryFilter);

                    }
                },
                "columns": [
                    {
                        "className": 'details-control',
                        "orderable": false,
                        "data": null,
                        "defaultContent": ''
                    },
                    {
                        "data": "experiment_name",
                        "name": "experiment.name",
                        "render": function (data, type, row) {
                            return '█  ' + data;
                        }
                    },
                    {"data": "start_time", "name": "start_time"},
                    {"data": "heartbeat", "name": "heartbeat"},
                    {"data": "hostname", "name": "hostname"},
                    {"data": "result", "name": "result"},
                    {"data": "id", "visible": false}
                ],
                order: [["5", "desc"]]
            };
            var table = jqRuns.DataTable(config);
            createRunTable.table = table;
            // Add event listener for opening and closing details
            jqRuns.find('tbody').on('click', 'tr', function () {
                var tr = $(this);
                var row = table.row(tr);
                if (row.child.isShown()) {
                    // This row is already open - close it
                    row.child.hide();
                    tr.removeClass('shown');
                }
                else {
                    if (row.data() == undefined) {
                        // Nothing to do here
                        return;
                    }
                    var id = row.data().id;
                    var f = function () {
                        $.ajax({
                            url: "/api/run/" + id
                        }).done(function (data) {
                            if (data.data[0].id != row.data().id) {
                                /* Before this ajax function was called,
                                 our parent row has changed (belongs to some other experiment)
                                 there is nothing to do here. */
                                return;
                            }
                            var detail_view = null;
                            //Show detailed view if not shown yet
                            if (!row.child.isShown()) {
                                row.child(generateDetailView(data.data[0])).show();
                                detail_view = tr[0].nextSibling;
                            } else {
                                //udpdate content
                                detail_view = tr[0].nextSibling;
                                $(detail_view).find('[sacred-content="captured_out"]').each(function (i, obj) {
                                    obj.innerText = data.data[0].object.captured_out;
                                });
                            }
                            //scroll to the end of captured out
                            $(detail_view).find(".scrollDown").each(function (i, obj) {
                                scrollDown(obj);
                            });
                            //update parent row with current data:
                            row.data(data.data[0]);
                            //set timeOut
                            setTimeout(function () {
                                if (row.child.isShown()) {
                                    f();
                                }
                            }, 5000);
                        });
                        tr.addClass('shown');
                    };
                    f();
                }
            });
            return table;
        };
        return createRunTable;
    });
<commit_msg>By default, order runs in the table by their last activity<commit_after>/**
 * Returns a function that turns a table into a datatable for displaying experiment runs
 */
define("runs/runTable", ["bootstrap", "datatables", "datatables-bootstrap", "runs/detailView"],
    function (bootstrap, datatables, dtboostrap, generateDetailView) {
        /**
         * Scrolls down in the element
         * @param obj
         */
        function scrollDown(obj) {
            $(obj).scrollTop(obj.scrollHeight);
        }

        /**
         * Turn tableElement into dataTable displaying runs.
         *
         * Returns the created table.
         * @param tableElement
         */
        var createRunTable = {};
        createRunTable.table = null;
        createRunTable.reload = function () {
            createRunTable.table.ajax.reload();
        };
        createRunTable.queryFilter = {type: "and", filters: []};

        createRunTable.initTable = function (tableElement) {
            var jqRuns = $(tableElement);
            var config = {
                colReorder: true,
                responsive: false,
                bFilter: false,

                // Scroller:
                //scrollY: window.innerHeight / 1.4,
                deferRender: true,
                //scroller: false,
                serverSide: true,
                ajax: {
                    url: "/api/run",
                    data: function (request) {
                        request.queryFilter = JSON.stringify(createRunTable.queryFilter);

                    }
                },
                "columns": [
                    {
                        "className": 'details-control',
                        "orderable": false,
                        "data": null,
                        "defaultContent": ''
                    },
                    {
                        "data": "experiment_name",
                        "name": "experiment.name",
                        "render": function (data, type, row) {
                            return '█  ' + data;
                        }
                    },
                    {"data": "start_time", "name": "start_time"},
                    {"data": "heartbeat", "name": "heartbeat"},
                    {"data": "hostname", "name": "hostname"},
                    {"data": "result", "name": "result"},
                    {"data": "id", "visible": false}
                ],
                order: [["3", "desc"]]
            };
            var table = jqRuns.DataTable(config);
            createRunTable.table = table;
            // Add event listener for opening and closing details
            jqRuns.find('tbody').on('click', 'tr', function () {
                var tr = $(this);
                var row = table.row(tr);
                if (row.child.isShown()) {
                    // This row is already open - close it
                    row.child.hide();
                    tr.removeClass('shown');
                }
                else {
                    if (row.data() == undefined) {
                        // Nothing to do here
                        return;
                    }
                    var id = row.data().id;
                    var f = function () {
                        $.ajax({
                            url: "/api/run/" + id
                        }).done(function (data) {
                            if (data.data[0].id != row.data().id) {
                                /* Before this ajax function was called,
                                 our parent row has changed (belongs to some other experiment)
                                 there is nothing to do here. */
                                return;
                            }
                            var detail_view = null;
                            //Show detailed view if not shown yet
                            if (!row.child.isShown()) {
                                row.child(generateDetailView(data.data[0])).show();
                                detail_view = tr[0].nextSibling;
                            } else {
                                //udpdate content
                                detail_view = tr[0].nextSibling;
                                $(detail_view).find('[sacred-content="captured_out"]').each(function (i, obj) {
                                    obj.innerText = data.data[0].object.captured_out;
                                });
                            }
                            //scroll to the end of captured out
                            $(detail_view).find(".scrollDown").each(function (i, obj) {
                                scrollDown(obj);
                            });
                            //update parent row with current data:
                            row.data(data.data[0]);
                            //set timeOut
                            setTimeout(function () {
                                if (row.child.isShown()) {
                                    f();
                                }
                            }, 5000);
                        });
                        tr.addClass('shown');
                    };
                    f();
                }
            });
            return table;
        };
        return createRunTable;
    });
<|endoftext|>


<commit_before>Multi-Threaded Application vs. Single Threaded Application

// What is a Multi-Threaded application?
//     Multithreading is a feature of an operating system that allows programs to run subcomponents or threads in parallel.
//     Typically most applications only need to use one thread because they do not perform time consuming tasks.
//     The use of multiple threads allows an application to distribute long running tasks so that they can be executed in parallel.
//     This gives the user the perceived appearance that the application is working faster due to the fact that
//     while one thread is waiting on an IO process the remaining tasks can make use of the available CPU.
//     The allows working threads to execute in tandem so that they can be competed sooner.

// Why would we use a multi threaded application vs. a single threaded application?

//   - Multithreading Benefits

//       Improved responsiveness — Users usually report improved responsiveness compared to single thread applications.
//       Faster applications — Multiple threads can lead to improved application performance.
//       Prioritization — Threads can be assigned a priority which would allow higher priority tasks to take
//                         precedence over lower priority tasks.

//   - Single Threading Benefits

//       Programming and debugging — These activities are easier compared to multithreaded applications due to
//                                   the reduced complexity
//       Less Overhead — Threads add overhead to an application

// When developing multi-threaded applications, the following must be considered..

//       Deadlocks occur when two threads hold a monitor that the other one requires.
//       In essence each task is blocking the other and both tasks are waiting for the other monitor to be released.
//       This forces an application to hang or deadlock.
//       Resource allocation is used to prevent deadlocks because the system determines if
//       approving the resource request will render the system in an unsafe state.
//       An unsafe state could result in a deadlock. The system only approves requests that will lead to safe states.
//       Thread Synchronization is used when multiple threads use the same instance of an object.
//       The threads accessing the object can then be locked and then synchronized so that each task can
//       interact with the static object on at a time.

//
<commit_msg>add resource<commit_after>Multi-Threaded Application vs. Single Threaded Application

// What is a Multi-Threaded application?
//     Multithreading is a feature of an operating system that allows programs to run subcomponents or threads in parallel.
//     Typically most applications only need to use one thread because they do not perform time consuming tasks.
//     The use of multiple threads allows an application to distribute long running tasks so that they can be executed in parallel.
//     This gives the user the perceived appearance that the application is working faster due to the fact that
//     while one thread is waiting on an IO process the remaining tasks can make use of the available CPU.
//     The allows working threads to execute in tandem so that they can be competed sooner.

// Why would we use a multi threaded application vs. a single threaded application?

//   - Multithreading Benefits

//       Improved responsiveness — Users usually report improved responsiveness compared to single thread applications.
//       Faster applications — Multiple threads can lead to improved application performance.
//       Prioritization — Threads can be assigned a priority which would allow higher priority tasks to take
//                         precedence over lower priority tasks.

//   - Single Threading Benefits

//       Programming and debugging — These activities are easier compared to multithreaded applications due to
//                                   the reduced complexity
//       Less Overhead — Threads add overhead to an application

// When developing multi-threaded applications, the following must be considered..

//       Deadlocks occur when two threads hold a monitor that the other one requires.
//       In essence each task is blocking the other and both tasks are waiting for the other monitor to be released.
//       This forces an application to hang or deadlock.
//       Resource allocation is used to prevent deadlocks because the system determines if
//       approving the resource request will render the system in an unsafe state.
//       An unsafe state could result in a deadlock. The system only approves requests that will lead to safe states.
//       Thread Synchronization is used when multiple threads use the same instance of an object.
//       The threads accessing the object can then be locked and then synchronized so that each task can
//       interact with the static object on at a time.

// -------------------------------------------------------------------------------------------

 // - Resources
 //   This blog provided info and examples:
 //    http://benalman.com/news/2010/11/immediately-invoked-function-expression/
<|endoftext|>


<commit_before>class DysonEnvironmentState {

    updateState(newState) {

        this._lastUpdated = new Date(newState.time);

        // Gets all possible values from the data (depending on the model)
        this._pm2_5Density = this.getNumericValue(newState.data.p25r);
        this._pm10Density = this.getNumericValue(newState.data.p10r);
        this._vocDensity = this.getNumericValue(newState.data.va10);
        this._nitrogenDioxideDensity = this.getNumericValue(newState.data.noxl);
        let p = this.getCharacteristicValue(newState.data.pact);
        let v = this.getCharacteristicValue(newState.data.vact);

        // Gets the highest value, which means the one with the baddest results
        this._airQuality = Math.max(
            this.getCharacteristicValue(newState.data.pm25),
            this.getCharacteristicValue(newState.data.pm10),
            this.getCharacteristicValue(newState.data.va10),
            this.getCharacteristicValue(newState.data.noxl),
            p, v);

        this._humidity = Number.parseInt(newState.data.hact);
        // Reference: http://aakira.hatenablog.com/entry/2016/08/12/012654
        this._temperature = Number.parseFloat(newState.data.tact) / 10 - 273;
    }

    getNumericValue(rawValue) {

        // Converts the raw value into an integer
        if (!rawValue) {
            return 0;
        }
        return Number.parseInt(rawValue);
    }

    getCharacteristicValue(rawValue) {

        // Converts the raw value into an integer (if no value is provided, 0 is returned, so that the overall result is not changed)
        if (!rawValue) {
            return 0;
        }
        let integerValue = Number.parseInt(rawValue);

        // Reduces the scale from 0-100 to 0-10 as used in the Dyson app
        integerValue = Math.floor(integerValue / 10);

        // Returns the characteristic value based on the bucket in which the value should go (as seen in the Dyson app)
        if (integerValue <= 3) {
            return 2; // Characteristic.AirQuality.GOOD
        }
        if (integerValue <= 6) {
            return 3; // Characteristic.AirQuality.FAIR
        }
        if (integerValue <= 8) {
            return 4; // Characteristic.AirQuality.INFERIOR
        }
        return 5; // Characteristic.AirQuality.POOR
    }

    get lastUpdated() {return this._lastUpdated;}
    get airQuality() {return this._airQuality;}
    get pm2_5Density() {return this._pm2_5Density;}
    get pm10Density() {return this._pm10Density;}
    get vocDensity() {return this._vocDensity;}
    get nitrogenDioxideDensity() {return this._nitrogenDioxideDensity;}
    get humidity() {return this._humidity;}
    get temperature() {return this._temperature;}

}

module.exports = { DysonEnvironmentState };<commit_msg>Handle case where sensor is OFF<commit_after>class DysonEnvironmentState {

    updateState(newState) {

        this._lastUpdated = new Date(newState.time);

        // Gets all possible values from the data (depending on the model)
        this._pm2_5Density = this.getNumericValue(newState.data.p25r);
        this._pm10Density = this.getNumericValue(newState.data.p10r);
        this._vocDensity = this.getNumericValue(newState.data.va10);
        this._nitrogenDioxideDensity = this.getNumericValue(newState.data.noxl);
        let p = this.getCharacteristicValue(newState.data.pact);
        let v = this.getCharacteristicValue(newState.data.vact);

        // Gets the highest value, which means the one with the baddest results
        this._airQuality = Math.max(
            this.getCharacteristicValue(newState.data.pm25),
            this.getCharacteristicValue(newState.data.pm10),
            this.getCharacteristicValue(newState.data.va10),
            this.getCharacteristicValue(newState.data.noxl),
            p, v);

        this._humidity = Number.parseInt(newState.data.hact);
        // Reference: http://aakira.hatenablog.com/entry/2016/08/12/012654
        this._temperature = Number.parseFloat(newState.data.tact) / 10 - 273;
    }

    getNumericValue(rawValue) {

        // Converts the raw value into an integer
        if (!rawValue) {
            return 0;
        }
        return Number.parseInt(rawValue);
    }

    getCharacteristicValue(rawValue) {

        // Converts the raw value into an integer (if no value is provided, 0 is returned, so that the overall result is not changed)
        if (!rawValue) {
            return 0;
        }

       // If the sensor is OFF, 0 is returned.
        if (rawValue == "OFF") {
            return 0;
        }

        let integerValue = Number.parseInt(rawValue);

        // Reduces the scale from 0-100 to 0-10 as used in the Dyson app
        integerValue = Math.floor(integerValue / 10);

        // Returns the characteristic value based on the bucket in which the value should go (as seen in the Dyson app)
        if (integerValue <= 3) {
            return 2; // Characteristic.AirQuality.GOOD
        }
        if (integerValue <= 6) {
            return 3; // Characteristic.AirQuality.FAIR
        }
        if (integerValue <= 8) {
            return 4; // Characteristic.AirQuality.INFERIOR
        }
        return 5; // Characteristic.AirQuality.POOR
    }

    get lastUpdated() {return this._lastUpdated;}
    get airQuality() {return this._airQuality;}
    get pm2_5Density() {return this._pm2_5Density;}
    get pm10Density() {return this._pm10Density;}
    get vocDensity() {return this._vocDensity;}
    get nitrogenDioxideDensity() {return this._nitrogenDioxideDensity;}
    get humidity() {return this._humidity;}
    get temperature() {return this._temperature;}

}

module.exports = { DysonEnvironmentState };<|endoftext|>


<commit_before>// Note to self: This is a "presentation" type component.
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { CLIENT_ID } from '../../constants/auth';

class Stream extends Component {

    componentDidUpdate() {
        const audioElement = ReactDOM.findDOMNode(this.refs.audio);

        if (!audioElement) { return; }

        const { activeTrack } = this.props;

        if (activeTrack) {
            // Temp hax until i get an API CLIENT_ID and can use the real function audio tag below.
            console.log('Stream - audioElement.play() - ' + activeTrack.origin.title);
            // audioElement.play();
        } else {
            // Temp hax until i get an API CLIENT_ID and can use the real function audio tag below.
            console.log('Stream - audioElement.play() - ' + activeTrack.origin.title);
            // audioElement.pause();
        }
    }

    render() {
        const {  user, tracks = [], activeTrack, onAuth, onPlay } = this.props;

        return (

                    {
                        user
                        ?

{user.username}

                        :
                            <button onClick={onAuth} type="button">Login</button>
                    }

                    {
                        tracks.map((track, key) => {
                            return (

                                    {track.origin.title}

                                    <button type="button" onClick={() => onPlay(track)}>Play</button>

                            );
                        })
                    }

                {
                    activeTrack
                    ?
                        // Temp hax until i get an API CLIENT_ID and can use the real function audio tag below.
                        [audio-placholder: {activeTrack.origin.stream_url}]
                        // <audio id="audio" ref="audio" src={`${activeTrack.origin.stream_url}?client_id=${CLIENT_ID}`}></audio>
                    :
                        null
                }

        );
    }

}

export default Stream;
<commit_msg>SoundCloud Player. Stop the playing music<commit_after>// Note to self: This is a "presentation" type component.
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { CLIENT_ID } from '../../constants/auth';

class Stream extends Component {

    componentDidUpdate() {
        const audioElement = ReactDOM.findDOMNode(this.refs.audio);

        if (!audioElement) { return; }

        const { activeTrack } = this.props;

        if (activeTrack) {
            // Temp hax until i get an API CLIENT_ID and can use the real function audio tag below.
            console.log('Stream - audioElement.play() - ' + activeTrack.origin.title);
            // audioElement.play();
        } else {
            // Temp hax until i get an API CLIENT_ID and can use the real function audio tag below.
            console.log('Stream - audioElement.play() - ' + activeTrack.origin.title);
            // audioElement.pause();
        }
    }

    render() {
        const {  user, tracks = [], activeTrack, onAuth, onPlay } = this.props;

        return (

                    {
                        user
                        ?

{user.username}

                        :
                            <button onClick={onAuth} type="button">Login</button>
                    }

                    {
                        tracks.map((track, key) => {
                            if (activeTrack !== track) {
                                return(

                                        {track.origin.title}

                                        <button type="button" onClick={() => onPlay(track)}>Play</button>

                                );
                            } else {
                                return(

                                        {track.origin.title}

                                        <button type="button" onClick={() => onPlay(null)}>Stop</button>

                                );
                            }
                        })
                    }

                {
                    activeTrack
                    ?
                        // Temp hax until i get an API CLIENT_ID and can use the real function audio tag below.
                        [audio-placholder: {activeTrack.origin.stream_url}]
                        // <audio id="audio" ref="audio" src={`${activeTrack.origin.stream_url}?client_id=${CLIENT_ID}`}></audio>
                    :
                        null
                }

        );
    }

}

export default Stream;
<|endoftext|>


<commit_before>/**
 * React Static Boilerplate
 * https://github.com/kriasoft/react-static-boilerplate
 *
 * Copyright © 2015-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React, { PropTypes } from 'react';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import Layout from '../../../components/Layout';
import Link from '../../../components/Link';
import Logo from '../../../components/Logo';
import s from './styles.css';
import g from '../../styles/grid.css';
import v from '../../styles/aesthetics.css';
import { title, html } from './index.md';

class HomePage extends React.Component {

  static propTypes = {
  };

  componentDidMount() {
    document.title = title;
  }

  render() {
    return (
      <Layout>

        <div className={`${s.hero} ${g.gFlexContainer} ${g.gFlexCenter}`}>

                <ReactCSSTransitionGroup
      component="div"
      className={`container ${g.maxWidth}`}
      transitionName={{
        enter: s.enter,
        leave: s.leave
      }}
      transitionEnterTimeout={9000}
      transitionLeaveTimeout={9000}
      >

hello@zaneriley.com

            <h1 key="2" className={`${g.gMarginTopSmaller} ${g.g8l} `}>Digital product designer that codes

            <p key="3" className={` ${g.g6l} ${g.gMarginTop}`}>I’m Zane, based in San Francisco, California, making products easier to use and help businesses communicate more effectively.

          </ReactCSSTransitionGroup>

          <Logo className={`${s.theBigZ}`}/>

        <div className={`${g.maxWidth}`}>
          <h2 className={`${g.g9m} ${g.g6l} `}>Case Studies

          <p className={`${g.g9m} ${g.g6l} `}><Link className="mdl-navigation__link" to="/case-study/improving-purchase-process">Improving the purchase process of Classes and Kits</Link>

          <p className={`${g.g9m} ${g.g6l} `}><Link className="mdl-navigation__link" to="/case-study/building-a-design-system">Building a Design system.</Link>

      </Layout>
    );
  }

}

export default HomePage;
<commit_msg>Write better.<commit_after>/**
 * React Static Boilerplate
 * https://github.com/kriasoft/react-static-boilerplate
 *
 * Copyright © 2015-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React, { PropTypes } from 'react';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import Layout from '../../../components/Layout';
import Link from '../../../components/Link';
import Logo from '../../../components/Logo';
import s from './styles.css';
import g from '../../styles/grid.css';
import v from '../../styles/aesthetics.css';
import { title, html } from './index.md';

class HomePage extends React.Component {

  static propTypes = {
  };

  componentDidMount() {
    document.title = title;
  }

  render() {
    return (
      <Layout>

        <div className={`${s.hero} ${g.gFlexContainer} ${g.gFlexCenter}`}>

                <ReactCSSTransitionGroup
      component="div"
      className={`container ${g.maxWidth}`}
      transitionName={{
        enter: s.enter,
        leave: s.leave
      }}
      transitionEnterTimeout={9000}
      transitionLeaveTimeout={9000}
      >

hello@zaneriley.com

            <h1 key="2" className={`${g.gMarginTopSmaller} ${g.g8l} `}>Digital product designer that codes

            <p key="3" className={` ${g.g6l} ${g.gMarginTop}`}>I’m Zane, a designer based in San Francisco, California. I make products easier to use and help businesses communicate more effectively.

          </ReactCSSTransitionGroup>

          <Logo className={`${s.theBigZ}`}/>

        <div className={`${g.maxWidth}`}>
          <h2 className={`${g.g9m} ${g.g6l} `}>Case Studies

          <p className={`${g.g9m} ${g.g6l} `}><Link className="mdl-navigation__link" to="/case-study/improving-purchase-process">Improving the purchase process of Classes and Kits</Link>

          <p className={`${g.g9m} ${g.g6l} `}><Link className="mdl-navigation__link" to="/case-study/building-a-design-system">Building a Design system.</Link>

      </Layout>
    );
  }

}

export default HomePage;
<|endoftext|>


<commit_before>import Head from './mixins/head'
import Body from './mixins/body'
import Foot from './mixins/foot'

export default {
  name: 'datatable',

  mixins: [Head, Body, Foot],

  data () {
    return {
      desc: null,
      page: 1,
      sorting: null,
      all: false
    }
  },

  props: {
    headers: {
      type: Array,
      default: () => []
    },
    headerText: {
      type: String,
      default: 'text'
    },
    hideActions: Boolean,
    items: {
      type: Array,
      default: () => []
    },
    itemValue: {
      default: 'value'
    },
    noDataText: {
      type: String,
      default: 'No data available in table'
    },
    noResultsText: {
      type: String,
      default: 'No matching records found'
    },
    rowsPerPage: {
      type: [Number, String],
      default: 5
    },
    rowsPerPageItems: {
      type: Array,
      default () {
        return [
          5,
          10,
          25,
          { text: 'All', value: -1 }
        ]
      }
    },
    rowsPerPageText: {
      type: String,
      default: 'Rows per page:'
    },
    selectAll: Boolean,
    search: {
      required: false
    },
    filter: {
      type: Function,
      default: (val, search) => {
        return val !== null &&
          ['undefined', 'boolean'].indexOf(typeof val) === -1 &&
          val.toString().toLowerCase().indexOf(search) !== -1
      }
    },
    value: {
      type: Array,
      default: () => []
    }
  },

  computed: {
    indeterminate () {
      return this.selectAll && this.someItems && !this.everyItem
    },
    everyItem () {
      return this.value.every(i => i[this.itemValue])
    },
    someItems () {
      return this.value.some(i => i[this.itemValue])
    },
    pageStart () {
      const page = this.rowsPerPage === Object(this.rowsPerPage)
        ? this.rowsPerPage.value
        : this.rowsPerPage
      return page === -1 ? 0 : (this.page - 1) * page
    },
    pageStop () {
      const page = this.rowsPerPage === Object(this.rowsPerPage)
        ? this.rowsPerPage.value
        : this.rowsPerPage
      return page === -1 ? this.value.length : this.page * page
    },
    filteredItems () {
      let items = this.value.slice()
      const hasSearch = typeof this.search !== 'undefined' && this.search !== null

      if (hasSearch) {
        const search = this.search.toString().toLowerCase()

        items = items.filter(i => Object.keys(i).some(j => this.filter(i[j], search)))
      }

      items = items.sort((a, b) => {
        this.sorting = !this.sorting ? this.headers.find(h => !('sortable' in h) || h.sortable).value : this.sorting
        const sortA = a[this.sorting]
        const sortB = b[this.sorting]

        if (this.desc) {
          if (sortA < sortB) return 1
          if (sortA > sortB) return -1
          return 0
        } else {
          if (sortA < sortB) return -1
          if (sortA > sortB) return 1
          return 0
        }
      })

      return this.hideActions ? items : items.slice(this.pageStart, this.pageStop)
    }
  },

  watch: {
    rowsPerPage () {
      this.page = 1
    },
    indeterminate (val) {
      if (val) this.all = true
    },
    someItems (val) {
      if (!val) this.all = false
    },
    search () {
      this.page = 1
    }
  },

  methods: {
    sort (index) {
      if (this.sorting === null) {
        this.sorting = index
        this.desc = true
      } else if (this.sorting === index && this.desc) {
        this.desc = false
      } else if (this.sorting !== index) {
        this.sorting = index
        this.desc = true
      } else {
        this.sorting = null
        this.desc = null
      }
    },
    genTR (children, data = {}) {
      return this.$createElement('tr', data, children)
    },
    toggle (val) {
      this.all = val

      this.$emit('input', this.value.map(i => {
        i[this.itemValue] = this.filteredItems.includes(i) ? val : false

        return i
      }))
    }
  },

  render (h) {
    return h('v-table-overflow', {}, [
      h('table', {
        'class': {
          'datatable table': true,
          'datatable--select-all': this.selectAll
        }
      }, [
        this.genTHead(),
        this.genTBody(),
        this.hideActions ? null : this.genTFoot()
      ])
    ])
  }
}
<commit_msg>fixed auto sort bug (#434)<commit_after>import Head from './mixins/head'
import Body from './mixins/body'
import Foot from './mixins/foot'

export default {
  name: 'datatable',

  mixins: [Head, Body, Foot],

  data () {
    return {
      desc: null,
      page: 1,
      sorting: null,
      all: false
    }
  },

  props: {
    headers: {
      type: Array,
      default: () => []
    },
    headerText: {
      type: String,
      default: 'text'
    },
    hideActions: Boolean,
    items: {
      type: Array,
      default: () => []
    },
    itemValue: {
      default: 'value'
    },
    noDataText: {
      type: String,
      default: 'No data available in table'
    },
    noResultsText: {
      type: String,
      default: 'No matching records found'
    },
    rowsPerPage: {
      type: [Number, String],
      default: 5
    },
    rowsPerPageItems: {
      type: Array,
      default () {
        return [
          5,
          10,
          25,
          { text: 'All', value: -1 }
        ]
      }
    },
    rowsPerPageText: {
      type: String,
      default: 'Rows per page:'
    },
    selectAll: Boolean,
    search: {
      required: false
    },
    filter: {
      type: Function,
      default: (val, search) => {
        return val !== null &&
          ['undefined', 'boolean'].indexOf(typeof val) === -1 &&
          val.toString().toLowerCase().indexOf(search) !== -1
      }
    },
    value: {
      type: Array,
      default: () => []
    }
  },

  computed: {
    indeterminate () {
      return this.selectAll && this.someItems && !this.everyItem
    },
    everyItem () {
      return this.value.every(i => i[this.itemValue])
    },
    someItems () {
      return this.value.some(i => i[this.itemValue])
    },
    pageStart () {
      const page = this.rowsPerPage === Object(this.rowsPerPage)
        ? this.rowsPerPage.value
        : this.rowsPerPage
      return page === -1 ? 0 : (this.page - 1) * page
    },
    pageStop () {
      const page = this.rowsPerPage === Object(this.rowsPerPage)
        ? this.rowsPerPage.value
        : this.rowsPerPage
      return page === -1 ? this.value.length : this.page * page
    },
    filteredItems () {
      let items = this.value.slice()
      const hasSearch = typeof this.search !== 'undefined' && this.search !== null

      if (hasSearch) {
        const search = this.search.toString().toLowerCase()

        items = items.filter(i => Object.keys(i).some(j => this.filter(i[j], search)))
      }

      items = items.sort((a, b) => {
        const sortA = a[this.sorting]
        const sortB = b[this.sorting]

        if (this.desc) {
          if (sortA < sortB) return 1
          if (sortA > sortB) return -1
          return 0
        } else {
          if (sortA < sortB) return -1
          if (sortA > sortB) return 1
          return 0
        }
      })

      return this.hideActions ? items : items.slice(this.pageStart, this.pageStop)
    }
  },

  watch: {
    rowsPerPage () {
      this.page = 1
    },
    indeterminate (val) {
      if (val) this.all = true
    },
    someItems (val) {
      if (!val) this.all = false
    },
    search () {
      this.page = 1
    }
  },

  methods: {
    sort (index) {
      if (this.sorting === null) {
        this.sorting = index
        this.desc = true
      } else if (this.sorting === index && this.desc) {
        this.desc = false
      } else if (this.sorting !== index) {
        this.sorting = index
        this.desc = true
      } else {
        this.sorting = null
        this.desc = null
      }
    },
    genTR (children, data = {}) {
      return this.$createElement('tr', data, children)
    },
    toggle (val) {
      this.all = val

      this.$emit('input', this.value.map(i => {
        i[this.itemValue] = this.filteredItems.includes(i) ? val : false

        return i
      }))
    }
  },

  mounted () {
    this.sorting = !this.sorting ? this.headers.find(h => !('sortable' in h) || h.sortable).value : this.sorting
  },

  render (h) {
    return h('v-table-overflow', {}, [
      h('table', {
        'class': {
          'datatable table': true,
          'datatable--select-all': this.selectAll
        }
      }, [
        this.genTHead(),
        this.genTBody(),
        this.hideActions ? null : this.genTFoot()
      ])
    ])
  }
}
<|endoftext|>


<commit_before>/**
 * Patterns notification - Display (self-healing) notifications.
 *
 * Copyright 2013 Marko Durkovic
 */
define([
    "jquery",
    "../registry",
    "../core/logger",
    "../core/parser"
], function($, patterns, logger, Parser) {
    var log = logger.getLogger("notification"),
        parser = new Parser("notification");

    parser.add_argument("type", "static", ["static", "banner"]);
    parser.add_argument("healing", "5s");
    parser.add_argument("controls", "icons", ["icons", "buttons", "none"]);
    parser.add_argument("class");

    var _ = {
        name: "notification",
        trigger: ".pat-notification",

        // this is generic functionality and should be moved to lib
        parseUnit: function(value, unit) {
            var unitRe = new RegExp(unit+"$"),
                numericRe = new RegExp("^[0-9.]+");

            if (!(unitRe.test(value))) {
                throw "value " + value + "is not in unit " + unit;
            }

            var mod = value.replace(numericRe, "");
            mod = mod.replace(unitRe, "");

            value = parseFloat(value);
            if (!mod.length) {
                return value;
            }

            var factors = {
                M: 1000000,
                k: 1000,
                m: 0.001,
                u: 0.000001
            };

            return value * factors[mod];
        },

        parseUnitOrOption: function(value, unit, options) {
            if (options.indexOf(value) >= 0) {
                return value;
            }

            return _.parseUnit(value, unit);
        },

        count: 0,

        init: function($el, opts) {
            return $el.each(function() {
                var $el = $(this);

                if ($el.is("a,form")) {
                    _._init_inject($el, opts);
                } else {
                    _._initNotification($el, opts);
                }
                return $el;
            });
        },

        _initNotification: function($el, opts) {
            _.count++;

            var options = parser.parse($el, opts);

            $el = $el.wrap("
").parent()
                .attr("id", "pat-notification-" + _.count)
                .addClass("pat-notification-panel")
                .on("mouseenter.pat-notification", _.onMouseEnter)
                .on("mouseleave.pat-notification", _.onMouseLeave);

            if (options["class"]) {
                $el.addClass(options["class"]);
            }

            if (!Array.isArray(options.controls)) {
                options.controls = [ options.controls ];
            }

            // add close icon if requsted
            if (options.controls.indexOf("icons") >= 0) {
                $el.append("<button type="button" class="close-panel">Close</button>");
            }

            // add close button if requested
            if (options.controls.indexOf("buttons") >= 0) {
                $el.append("
<button type='button' class='close-panel'>Close</button>
");
            }

            if ($el.find(".close-panel").length) {
                $el.on("click.pat-notification", ".close-panel", _.onClick);
            } else {
                $el.on("click.pat-notification", _.onClick);
            }

            if (options.type === "banner") {
                var $container = $("#pat-notification-banners");
                if (!$container.length) {
                    $container = $("
").attr("id", "pat-notification-banners").addClass("pat-notification-container").appendTo("body");
                }
                $container.append($el);
            }

            var healing = _.parseUnitOrOption(options.healing, "s", ["persistent"]);

            log.debug("Healing value is", healing);
            $el.data("healing", healing);

            $el.animate({"opacity": 1}, "fast", function() {
                _.initRemoveTimer($el);
            });
        },

        _init_inject: function($el) {
            var inject_opts = {
                target: "#pat-notification-temp"
            };
            $el.on("pat-inject-success.pat-notification", function() {
                var $trigger = $(this),
                    cfg = parser.parse($trigger, { type: "banner"});

                var $el = $("#pat-notification-temp").contents().wrapAll("
")
                    .parent()
                    .addClass("pat-notification");

                if ($trigger.is("a")) {
                    $trigger.after($el);
                } else {
                    $el.prependTo($trigger);
                }
                _._initNotification($el, cfg);

                // XXX: Do this later as inject tries to access its target afterwards.
                // This should be fixed in injection.
                setTimeout(function() {
                    $('#pat-notification-temp').remove();
                }, 0);
            });
            inject.init($el, inject_opts);
        },

        initRemoveTimer: function($el) {
            var healing = $el.data("healing");
            if (healing !== "persistent") {
                clearTimeout($el.data("timer"));
                $el.data("timer", setTimeout(function() {
                    _.remove($el);
                }, healing * 1000));
            }
        },

        onMouseEnter: function() {
            $(this).data("persistent", true);
        },

        onMouseLeave: function() {
            var $this = $(this);

            $this.data("persistent", false);
            _.initRemoveTimer($this);
        },

        onClick: function(event) {
            var $this = $(event.delegateTarget);

            $this.data("persistent", false);
            _.remove($this);
        },

        remove: function($el) {
            if ($el.data("persistent") || $el.data("removing")) {
                return;
            }

            $el.data("removing", true);

            $el.stop(true).animate({"opacity": 0}, {
                step: function() {
                    if ($el.data("persistent")) {
                        // remove the timer and show notification
                        clearTimeout($el.data("timer"));
                        $el.stop(true).animate({"opacity": 1});
                        $el.data("removing", false);
                        return false;
                    }
                },

                complete: function() {
                    var $this = $(this);
                    $this.off(".pat-notification");
                    $this.slideUp("slow", function() {
                        $this.remove();
                    });
                }
            });
        }
    };

    patterns.register(_);
    return _;
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<commit_msg>Various notification fixes.<commit_after>/**
 * Patterns notification - Display (self-healing) notifications.
 *
 * Copyright 2013 Marko Durkovic
 */
define([
    "jquery",
    "pat-registry",
    "pat-logger",
    "pat-parser",
    "pat-inject"
], function($, patterns, logger, Parser, inject) {
    var log = logger.getLogger("notification"),
        parser = new Parser("notification");

    parser.add_argument("type", "static", ["static", "banner"]);
    parser.add_argument("healing", "5s");
    parser.add_argument("controls", "icons", ["icons", "buttons", "none"]);
    parser.add_argument("class");

    var _ = {
        name: "notification",
        trigger: ".pat-notification",

        // this is generic functionality and should be moved to lib
        parseUnit: function(value, unit) {
            var unitRe = new RegExp(unit+"$"),
                numericRe = new RegExp("^[0-9.]+");

            if (!(unitRe.test(value))) {
                throw "value " + value + "is not in unit " + unit;
            }

            var mod = value.replace(numericRe, "");
            mod = mod.replace(unitRe, "");

            value = parseFloat(value);
            if (!mod.length) {
                return value;
            }

            var factors = {
                M: 1000000,
                k: 1000,
                m: 0.001,
                u: 0.000001
            };

            return value * factors[mod];
        },

        parseUnitOrOption: function(value, unit, options) {
            if (options.indexOf(value) >= 0) {
                return value;
            }

            return _.parseUnit(value, unit);
        },

        count: 0,

        init: function($el, opts) {
            return $el.each(function() {
                var $el = $(this);

                if ($el.is("a,form")) {
                    _._init_inject($el, opts);
                } else {
                    _._initNotification($el, opts);
                }
                return $el;
            });
        },

        _initNotification: function($el, opts) {
            _.count++;

            var options = parser.parse($el, opts);

            $el = $el.wrap("
").parent()
                .attr("id", "pat-notification-" + _.count)
                .addClass("pat-notification-panel")
                .on("mouseenter.pat-notification", _.onMouseEnter)
                .on("mouseleave.pat-notification", _.onMouseLeave);

            if (options["class"]) {
                $el.addClass(options["class"]);
            }

            if (!Array.isArray(options.controls)) {
                options.controls = [ options.controls ];
            }

            // add close icon if requsted
            if (options.controls.indexOf("icons") >= 0) {
                $el.append("<button type='button' class=.close-panel'>Close</button>");
            }

            // add close button if requested
            if (options.controls.indexOf("buttons") >= 0) {
                $el.append("
<button type='button' class='close-panel'>Close</button>
");
            }

            if ($el.find(".close-panel").length) {
                $el.on("click.pat-notification", ".close-panel", _.onClick);
            } else {
                $el.on("click.pat-notification", _.onClick);
            }

            if (options.type === "banner") {
                var $container = $("#pat-notification-banners");
                if (!$container.length) {
                    $container = $("
").attr("id", "pat-notification-banners").addClass("pat-notification-container").appendTo("body");
                }
                $container.append($el);
            }

            var healing = _.parseUnitOrOption(options.healing, "s", ["persistent"]);

            log.debug("Healing value is", healing);
            $el.data("healing", healing);

            $el.animate({"opacity": 1}, "fast", function() {
                _.initRemoveTimer($el);
            });
        },

        _init_inject: function($el) {
            var inject_opts = {
                target: "#pat-notification-temp"
            };
            $el.on("pat-inject-success.pat-notification", function() {
                var $trigger = $(this),
                    cfg = parser.parse($trigger, { type: "banner"});

                var $el = $("#pat-notification-temp").contents().wrapAll("
")
                    .parent()
                    .addClass("pat-notification");

                if ($trigger.is("a")) {
                    $trigger.after($el);
                } else {
                    $el.prependTo($trigger);
                }
                _._initNotification($el, cfg);

                // XXX: Do this later as inject tries to access its target afterwards.
                // This should be fixed in injection.
                setTimeout(function() {
                    $("#pat-notification-temp").remove();
                }, 0);
            });
            inject.init($el, inject_opts);
        },

        initRemoveTimer: function($el) {
            var healing = $el.data("healing");
            if (healing !== "persistent") {
                clearTimeout($el.data("timer"));
                $el.data("timer", setTimeout(function() {
                    _.remove($el);
                }, healing * 1000));
            }
        },

        onMouseEnter: function() {
            $(this).data("persistent", true);
        },

        onMouseLeave: function() {
            var $this = $(this);

            $this.data("persistent", false);
            _.initRemoveTimer($this);
        },

        onClick: function(event) {
            var $this = $(event.delegateTarget);

            $this.data("persistent", false);
            _.remove($this);
        },

        remove: function($el) {
            if ($el.data("persistent") || $el.data("removing")) {
                return;
            }

            $el.data("removing", true);

            $el.stop(true).animate({"opacity": 0}, {
                step: function() {
                    if ($el.data("persistent")) {
                        // remove the timer and show notification
                        clearTimeout($el.data("timer"));
                        $el.stop(true).animate({"opacity": 1});
                        $el.data("removing", false);
                        return false;
                    }
                },

                complete: function() {
                    var $this = $(this);
                    $this.off(".pat-notification");
                    $this.slideUp("slow", function() {
                        $this.remove();
                    });
                }
            });
        }
    };

    patterns.register(_);
    return _;
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<|endoftext|>


<commit_before>// An infinite computer must be able to do the following things:
//  1. getTotalScrollableHeight()
//  2. getDisplayIndexStart()
//  3. getDisplayIndexEnd()

class InfiniteComputer {
  constructor(heightData, numberOfChildren) {
    this.heightData = heightData;
    this.numberOfChildren = numberOfChildren;
  }

  getTotalScrollableHeight() {
    throw new Error("getTotalScrollableHeight not implemented.");
  }

  getDisplayIndexStart() {
    throw new Error("getDisplayIndexStart not implemented.");
  }

  getDisplayIndexEnd() {
    throw new Error("getDisplayIndexEnd not implemented.");
  }

  // These are helper methods, and can be calculated from
  // the above details.
  getTopSpacerHeight() {
    throw new Error("getTopSpacerHeight not implemented.");
  }

  getBottomSpacerHeight() {
    throw new Error("getBottomSpacerHeight not implemented.");
  }
}

module.exports = InfiniteComputer;
<commit_msg>Add arguments to abstract functions.<commit_after>// An infinite computer must be able to do the following things:
//  1. getTotalScrollableHeight()
//  2. getDisplayIndexStart()
//  3. getDisplayIndexEnd()

class InfiniteComputer {
  constructor(heightData, numberOfChildren) {
    this.heightData = heightData;
    this.numberOfChildren = numberOfChildren;
  }

  getTotalScrollableHeight() {
    throw new Error("getTotalScrollableHeight not implemented.");
  }

  getDisplayIndexStart(windowTop) {
    throw new Error("getDisplayIndexStart not implemented.");
  }

  getDisplayIndexEnd(windowBottom) {
    throw new Error("getDisplayIndexEnd not implemented.");
  }

  // These are helper methods, and can be calculated from
  // the above details.
  getTopSpacerHeight(displayIndexStart) {
    throw new Error("getTopSpacerHeight not implemented.");
  }

  getBottomSpacerHeight(displayIndexEnd) {
    throw new Error("getBottomSpacerHeight not implemented.");
  }
}

module.exports = InfiniteComputer;
<|endoftext|>