<commit_before>// Represents a BAM index.
// Code is based heavily on bam.js, part of the Dalliance Genome Explorer,  (c) Thomas Down 2006-2001.

var igv = (function (igv) {

    const BAI_MAGIC = 21578050;
    const TABIX_MAGIC = 21578324;
    const MAX_HEADER_SIZE = 100000000;   // IF the header is larger than this we can't read it !
    const MAX_GZIP_BLOCK_SIZE = (1 << 16);

    /**
     * @param indexURL
     * @param config
     * @param tabix
     *
     * @returns a Promised for the bam or tabix index.  The fulfill function takes the index as an argument.
     */
    igv.loadBamIndex = function (indexURL, config, tabix) {

        return new Promise(function (fulfill, reject) {

            var genome = igv.browser ? igv.browser.genome : null;

            igvxhr.loadArrayBuffer(indexURL,
                {
                    headers: config.headers,
                    withCredentials: config.withCredentials
                }).then(function (arrayBuffer) {

                    var indices = [],
                        magic, nbin, nintv, nref, parser,
                        blockMin = Number.MAX_VALUE,
                        blockMax = 0,
                        binIndex, linearIndex, binNumber, cs, ce, b, i, ref, sequenceIndexMap;

                    if (!arrayBuffer) {
                        fulfill(null);
                        return;
                    }

                    if (tabix) {
                        var inflate = new Zlib.Gunzip(new Uint8Array(arrayBuffer));
                        arrayBuffer = inflate.decompress().buffer;
                    }

                    parser = new igv.BinaryParser(new DataView(arrayBuffer));

                    magic = parser.getInt();

                    if (magic === BAI_MAGIC || (tabix && magic === TABIX_MAGIC)) {

                        nref = parser.getInt();

                        if (tabix) {
                            // Tabix header parameters aren't used, but they must be read to advance the pointer
                            var format = parser.getInt();
                            var col_seq = parser.getInt();
                            var col_beg = parser.getInt();
                            var col_end = parser.getInt();
                            var meta = parser.getInt();
                            var skip = parser.getInt();
                            var l_nm = parser.getInt();

                            sequenceIndexMap = {};
                            for (i = 0; i < nref; i++) {
                                var seq_name = parser.getString();

                                // Translate to "official" chr name.
                                if (genome) seq_name = genome.getChromosomeName(seq_name);

                                sequenceIndexMap[seq_name] = i;
                            }
                        }

                        for (ref = 0; ref < nref; ++ref) {

                            binIndex = {};
                            linearIndex = [];

                            nbin = parser.getInt();

                            for (b = 0; b < nbin; ++b) {

                                binNumber = parser.getInt();
                                binIndex[binNumber] = [];

                                var nchnk = parser.getInt(); // # of chunks for this bin

                                for (i = 0; i < nchnk; i++) {
                                    cs = parser.getVPointer();
                                    ce = parser.getVPointer();
                                    if (cs && ce) {
                                        if (cs.block < blockMin) {
                                            blockMin = cs.block;    // Block containing first alignment
                                        }
                                        if (ce.block > blockMax) {
                                            blockMax = ce.block;
                                        }
                                        binIndex[binNumber].push([cs, ce]);
                                    }
                                }
                            }

                            nintv = parser.getInt();
                            for (i = 0; i < nintv; i++) {
                                cs = parser.getVPointer();
                                linearIndex.push(cs);   // Might be null
                            }

                            if (nbin > 0) {
                                indices[ref] = {
                                    binIndex: binIndex,
                                    linearIndex: linearIndex
                                }
                            }
                        }

                    } else {
                        throw new Error(indexURL + " is not a " + (tabix ? "tabix" : "bai") + " file");
                    }
                    fulfill(new igv.BamIndex(indices, blockMin, blockMax, sequenceIndexMap, tabix));
                });
        })
    }

    igv.BamIndex = function (indices, headerSize, blockMax, sequenceIndexMap, tabix) {
        this.headerSize = headerSize;
        this.indices = indices;
        this.sequenceIndexMap = sequenceIndexMap;
        this.tabix = tabix;
        this.blockMax = blockMax;

    }

    /**
     * Fetch blocks for a particular genomic range.  This method is public so it can be unit-tested.
     *
     * @param refId  the sequence dictionary index of the chromosome
     * @param min  genomic start position
     * @param max  genomic end position
     * @param return an array of {minv: {filePointer, offset}, {maxv: {filePointer, offset}}
     */
    igv.BamIndex.prototype.blocksForRange = function (refId, min, max) {

        var bam = this,
            ba = bam.indices[refId],
            overlappingBins,
            leafChunks,
            otherChunks,
            nintv,
            lowest,
            minLin,
            lb,
            prunedOtherChunks,
            i,
            chnk,
            dif,
            intChunks,
            mergedChunks;

        if (!ba) {
            return [];
        }
        else {

            overlappingBins = reg2bins(min, max);        // List of bin #s that might overlap min, max
            leafChunks = [];
            otherChunks = [];

            overlappingBins.forEach(function (bin) {

                if (ba.binIndex[bin]) {
                    var chunks = ba.binIndex[bin],
                        nchnk = chunks.length;

                    for (var c = 0; c < nchnk; ++c) {
                        var cs = chunks[c][0];
                        var ce = chunks[c][1];
                        (bin < 4681 ? otherChunks : leafChunks).push({minv: cs, maxv: ce, bin: bin});
                    }

                }
            });

            // Use the linear index to find the lowest block that could contain alignments in the region
            nintv = ba.linearIndex.length;
            lowest = null;
            minLin = Math.min(min >> 14, nintv - 1), maxLin = Math.min(max >> 14, nintv - 1);
            for (i = minLin; i <= maxLin; ++i) {
                lb = ba.linearIndex[i];
                if (!lb) {
                    continue;
                }
                if (!lowest || lb.block < lowest.block || lb.offset < lowest.offset) {
                    lowest = lb;
                }
            }

            // Prune chunks that end before the lowest block
            prunedOtherChunks = [];
            if (lowest != null) {
                for (i = 0; i < otherChunks.length; ++i) {
                    chnk = otherChunks[i];
                    if (chnk.maxv.block >= lowest.block && chnk.maxv.offset >= lowest.offset) {
                        prunedOtherChunks.push(chnk);
                    }
                }
            }

            intChunks = [];
            for (i = 0; i < prunedOtherChunks.length; ++i) {
                intChunks.push(prunedOtherChunks[i]);
            }
            for (i = 0; i < leafChunks.length; ++i) {
                intChunks.push(leafChunks[i]);
            }

            intChunks.sort(function (c0, c1) {
                dif = c0.minv.block - c1.minv.block;
                if (dif != 0) {
                    return dif;
                } else {
                    return c0.minv.offset - c1.minv.offset;
                }
            });

            mergedChunks = [];
            if (intChunks.length > 0) {
                var cur = intChunks[0];
                for (var i = 1; i < intChunks.length; ++i) {
                    var nc = intChunks[i];
                    if ((nc.minv.block - cur.maxv.block) < 65000) { // Merge blocks that are withing 65k of each other
                        cur = {minv: cur.minv, maxv: nc.maxv};
                    } else {
                        mergedChunks.push(cur);
                        cur = nc;
                    }
                }
                mergedChunks.push(cur);
            }
            return mergedChunks;
        }

    };

    /**
     * Calculate the list of bins that may overlap with region [beg, end]
     *
     */
    function reg2bins(beg, end) {
        var i = 0, k, list = [];
        if (end >= 1 << 29)   end = 1 << 29;
        --end;
        list.push(0);
        for (k = 1 + (beg >> 26); k <= 1 + (end >> 26); ++k) list.push(k);
        for (k = 9 + (beg >> 23); k <= 9 + (end >> 23); ++k) list.push(k);
        for (k = 73 + (beg >> 20); k <= 73 + (end >> 20); ++k) list.push(k);
        for (k = 585 + (beg >> 17); k <= 585 + (end >> 17); ++k) list.push(k);
        for (k = 4681 + (beg >> 14); k <= 4681 + (end >> 14); ++k) list.push(k);
        return list;
    }

    return igv;

})(igv || {});<commit_msg>Catch uncaught promise failure<commit_after>// Represents a BAM index.
// Code is based heavily on bam.js, part of the Dalliance Genome Explorer,  (c) Thomas Down 2006-2001.

var igv = (function (igv) {

    const BAI_MAGIC = 21578050;
    const TABIX_MAGIC = 21578324;
    const MAX_HEADER_SIZE = 100000000;   // IF the header is larger than this we can't read it !
    const MAX_GZIP_BLOCK_SIZE = (1 << 16);

    /**
     * @param indexURL
     * @param config
     * @param tabix
     *
     * @returns a Promised for the bam or tabix index.  The fulfill function takes the index as an argument.
     */
    igv.loadBamIndex = function (indexURL, config, tabix) {

        return new Promise(function (fulfill, reject) {

            var genome = igv.browser ? igv.browser.genome : null;

            igvxhr.loadArrayBuffer(indexURL,
                {
                    headers: config.headers,
                    withCredentials: config.withCredentials
                }).then(function (arrayBuffer) {

                    var indices = [],
                        magic, nbin, nintv, nref, parser,
                        blockMin = Number.MAX_VALUE,
                        blockMax = 0,
                        binIndex, linearIndex, binNumber, cs, ce, b, i, ref, sequenceIndexMap;

                    if (!arrayBuffer) {
                        fulfill(null);
                        return;
                    }

                    if (tabix) {
                        var inflate = new Zlib.Gunzip(new Uint8Array(arrayBuffer));
                        arrayBuffer = inflate.decompress().buffer;
                    }

                    parser = new igv.BinaryParser(new DataView(arrayBuffer));

                    magic = parser.getInt();

                    if (magic === BAI_MAGIC || (tabix && magic === TABIX_MAGIC)) {

                        nref = parser.getInt();

                        if (tabix) {
                            // Tabix header parameters aren't used, but they must be read to advance the pointer
                            var format = parser.getInt();
                            var col_seq = parser.getInt();
                            var col_beg = parser.getInt();
                            var col_end = parser.getInt();
                            var meta = parser.getInt();
                            var skip = parser.getInt();
                            var l_nm = parser.getInt();

                            sequenceIndexMap = {};
                            for (i = 0; i < nref; i++) {
                                var seq_name = parser.getString();

                                // Translate to "official" chr name.
                                if (genome) seq_name = genome.getChromosomeName(seq_name);

                                sequenceIndexMap[seq_name] = i;
                            }
                        }

                        for (ref = 0; ref < nref; ++ref) {

                            binIndex = {};
                            linearIndex = [];

                            nbin = parser.getInt();

                            for (b = 0; b < nbin; ++b) {

                                binNumber = parser.getInt();
                                binIndex[binNumber] = [];

                                var nchnk = parser.getInt(); // # of chunks for this bin

                                for (i = 0; i < nchnk; i++) {
                                    cs = parser.getVPointer();
                                    ce = parser.getVPointer();
                                    if (cs && ce) {
                                        if (cs.block < blockMin) {
                                            blockMin = cs.block;    // Block containing first alignment
                                        }
                                        if (ce.block > blockMax) {
                                            blockMax = ce.block;
                                        }
                                        binIndex[binNumber].push([cs, ce]);
                                    }
                                }
                            }

                            nintv = parser.getInt();
                            for (i = 0; i < nintv; i++) {
                                cs = parser.getVPointer();
                                linearIndex.push(cs);   // Might be null
                            }

                            if (nbin > 0) {
                                indices[ref] = {
                                    binIndex: binIndex,
                                    linearIndex: linearIndex
                                }
                            }
                        }

                    } else {
                        throw new Error(indexURL + " is not a " + (tabix ? "tabix" : "bai") + " file");
                    }
                    fulfill(new igv.BamIndex(indices, blockMin, blockMax, sequenceIndexMap, tabix));
                }).catch(reject);
        })
    }

    igv.BamIndex = function (indices, headerSize, blockMax, sequenceIndexMap, tabix) {
        this.headerSize = headerSize;
        this.indices = indices;
        this.sequenceIndexMap = sequenceIndexMap;
        this.tabix = tabix;
        this.blockMax = blockMax;

    }

    /**
     * Fetch blocks for a particular genomic range.  This method is public so it can be unit-tested.
     *
     * @param refId  the sequence dictionary index of the chromosome
     * @param min  genomic start position
     * @param max  genomic end position
     * @param return an array of {minv: {filePointer, offset}, {maxv: {filePointer, offset}}
     */
    igv.BamIndex.prototype.blocksForRange = function (refId, min, max) {

        var bam = this,
            ba = bam.indices[refId],
            overlappingBins,
            leafChunks,
            otherChunks,
            nintv,
            lowest,
            minLin,
            lb,
            prunedOtherChunks,
            i,
            chnk,
            dif,
            intChunks,
            mergedChunks;

        if (!ba) {
            return [];
        }
        else {

            overlappingBins = reg2bins(min, max);        // List of bin #s that might overlap min, max
            leafChunks = [];
            otherChunks = [];

            overlappingBins.forEach(function (bin) {

                if (ba.binIndex[bin]) {
                    var chunks = ba.binIndex[bin],
                        nchnk = chunks.length;

                    for (var c = 0; c < nchnk; ++c) {
                        var cs = chunks[c][0];
                        var ce = chunks[c][1];
                        (bin < 4681 ? otherChunks : leafChunks).push({minv: cs, maxv: ce, bin: bin});
                    }

                }
            });

            // Use the linear index to find the lowest block that could contain alignments in the region
            nintv = ba.linearIndex.length;
            lowest = null;
            minLin = Math.min(min >> 14, nintv - 1), maxLin = Math.min(max >> 14, nintv - 1);
            for (i = minLin; i <= maxLin; ++i) {
                lb = ba.linearIndex[i];
                if (!lb) {
                    continue;
                }
                if (!lowest || lb.block < lowest.block || lb.offset < lowest.offset) {
                    lowest = lb;
                }
            }

            // Prune chunks that end before the lowest block
            prunedOtherChunks = [];
            if (lowest != null) {
                for (i = 0; i < otherChunks.length; ++i) {
                    chnk = otherChunks[i];
                    if (chnk.maxv.block >= lowest.block && chnk.maxv.offset >= lowest.offset) {
                        prunedOtherChunks.push(chnk);
                    }
                }
            }

            intChunks = [];
            for (i = 0; i < prunedOtherChunks.length; ++i) {
                intChunks.push(prunedOtherChunks[i]);
            }
            for (i = 0; i < leafChunks.length; ++i) {
                intChunks.push(leafChunks[i]);
            }

            intChunks.sort(function (c0, c1) {
                dif = c0.minv.block - c1.minv.block;
                if (dif != 0) {
                    return dif;
                } else {
                    return c0.minv.offset - c1.minv.offset;
                }
            });

            mergedChunks = [];
            if (intChunks.length > 0) {
                var cur = intChunks[0];
                for (var i = 1; i < intChunks.length; ++i) {
                    var nc = intChunks[i];
                    if ((nc.minv.block - cur.maxv.block) < 65000) { // Merge blocks that are withing 65k of each other
                        cur = {minv: cur.minv, maxv: nc.maxv};
                    } else {
                        mergedChunks.push(cur);
                        cur = nc;
                    }
                }
                mergedChunks.push(cur);
            }
            return mergedChunks;
        }

    };

    /**
     * Calculate the list of bins that may overlap with region [beg, end]
     *
     */
    function reg2bins(beg, end) {
        var i = 0, k, list = [];
        if (end >= 1 << 29)   end = 1 << 29;
        --end;
        list.push(0);
        for (k = 1 + (beg >> 26); k <= 1 + (end >> 26); ++k) list.push(k);
        for (k = 9 + (beg >> 23); k <= 9 + (end >> 23); ++k) list.push(k);
        for (k = 73 + (beg >> 20); k <= 73 + (end >> 20); ++k) list.push(k);
        for (k = 585 + (beg >> 17); k <= 585 + (end >> 17); ++k) list.push(k);
        for (k = 4681 + (beg >> 14); k <= 4681 + (end >> 14); ++k) list.push(k);
        return list;
    }

    return igv;

})(igv || {});<|endoftext|>


<commit_before>/* Magic Mirror
 *
 * Check the configuration file for errors
 *
 * By Rodrigo Ramírez Norambuena https://rodrigoramirez.com
 * MIT Licensed.
 */
const Linter = require("eslint").Linter;
const linter = new Linter();

const path = require("path");
const fs = require("fs");

const rootPath = path.resolve(__dirname + "/../");
const Log = require(rootPath + "/js/logger.js");
const Utils = require(rootPath + "/js/utils.js");

/**
 * Returns a string with path of configuration file.
 * Check if set by environment variable MM_CONFIG_FILE
 *
 * @returns {string} path and filename of the config file
 */
function getConfigFile() {
	// FIXME: This function should be in core. Do you want refactor me ;) ?, be good!
	let configFileName = path.resolve(rootPath + "/config/config.js");
	if (process.env.MM_CONFIG_FILE) {
		configFileName = path.resolve(process.env.MM_CONFIG_FILE);
	}
	return configFileName;
}

/**
 * Checks the config file using eslint.
 */
function checkConfigFile() {
	const configFileName = getConfigFile();

	// Check if file is present
	if (fs.existsSync(configFileName) === false) {
		Log.error(Utils.colors.error("File not found: "), configFileName);
		throw new Error("No config file present!");
	}

	// Check permission
	try {
		fs.accessSync(configFileName, fs.F_OK);
	} catch (e) {
		Log.error(Utils.colors.error(e));
		throw new Error("No permission to access config file!");
	}

	// Validate syntax of the configuration file.
	Log.info(Utils.colors.info("Checking file... "), configFileName);

	// I'm not sure if all ever is utf-8
	fs.readFile(configFileName, "utf-8", function (err, data) {
		if (err) {
			throw err;
		}
		const messages = linter.verify(data);
		if (messages.length === 0) {
			Log.info(Utils.colors.pass("Your configuration file doesn't contain syntax errors :)"));
		} else {
			Log.error(Utils.colors.error("Your configuration file contains syntax errors :("));
			// In case the there errors show messages and return
			messages.forEach((error) => {
				Log.error("Line", error.line, "col", error.column, error.message);
			});
		}
	});
}

checkConfigFile();
<commit_msg>clean up config checker<commit_after>/* Magic Mirror
 *
 * Check the configuration file for errors
 *
 * By Rodrigo Ramírez Norambuena https://rodrigoramirez.com
 * MIT Licensed.
 */
const Linter = require("eslint").Linter;
const linter = new Linter();

const path = require("path");
const fs = require("fs");

const rootPath = path.resolve(`${__dirname}/../`);
const Log = require(`${rootPath}/js/logger.js`);
const Utils = require(`${rootPath}/js/utils.js`);

/**
 * Returns a string with path of configuration file.
 * Check if set by environment variable MM_CONFIG_FILE
 *
 * @returns {string} path and filename of the config file
 */
function getConfigFile() {
	// FIXME: This function should be in core. Do you want refactor me ;) ?, be good!
	return path.resolve(process.env.MM_CONFIG_FILE || `${rootPath}/config/config.js`);
}

/**
 * Checks the config file using eslint.
 */
function checkConfigFile() {
	const configFileName = getConfigFile();

	// Check if file is present
	if (fs.existsSync(configFileName) === false) {
		Log.error(Utils.colors.error("File not found: "), configFileName);
		throw new Error("No config file present!");
	}

	// Check permission
	try {
		fs.accessSync(configFileName, fs.F_OK);
	} catch (e) {
		Log.error(Utils.colors.error(e));
		throw new Error("No permission to access config file!");
	}

	// Validate syntax of the configuration file.
	Log.info(Utils.colors.info("Checking file... "), configFileName);

	// I'm not sure if all ever is utf-8
	const configFile = fs.readFileSync(configFileName, "utf-8");

	const errors = linter.verify(configFile);
	if (errors.length === 0) {
		Log.info(Utils.colors.pass("Your configuration file doesn't contain syntax errors :)"));
	} else {
		Log.error(Utils.colors.error("Your configuration file contains syntax errors :("));

		for (const error of errors) {
			Log.error(`Line ${error.line} column ${error.column}: ${error.message}`);
		}
	}
}

checkConfigFile();
<|endoftext|>


<commit_before>goog.provide('closurequery');

goog.require('require.goog');

/**
* @function
* @property {Node} jQuery-like wrapper around goog.dom API (http://closure-library.googlecode.com/svn/docs/closure_goog_dom_dom.js.html)
* @param {string} selector
* @example $('#parent').removeChildren()
* @example $('div.exists').append($('

'))
*/
var $	= function (selector) {
	var elements	= domHelper.query(selector);
	var isEmpty		= elements.length < 1;

	if (isEmpty && new DOMParser().parseFromString(selector, 'text/xml').getElementsByTagName('parsererror').length < 1) {
		var tempElem		= domHelper.createElement('div');
		tempElem.innerHTML	= selector;
		elements[0]			= tempElem.firstChild;
	}
	else if (isEmpty) {
		elements[0]	= {};
	}

	$_domHelpers.forEach(function (key) {
		for (var i = 0 ; i < elements.length ; ++i) {
			elements[i][key]	= elements[i][key] || domHelper[key].fill(elements[i]);
		}

		elements[key]	= elements[0] && elements[0][key];
	});

	return elements;
};

var domHelper		= goog.dom;

var $_domHelpers	= goog.object.getKeys(domHelper).filter(function (key) { return !key.has('_') && typeof domHelper[key] === 'function'; });

$_domHelpers.forEach(function (key) {
	$[key]	= domHelper[key];
});
<commit_msg>Possible Closurequery fix<commit_after>goog.provide('closurequery');

goog.require('require.goog');

/**
* @function
* @property {Node} jQuery-like wrapper around goog.dom API (http://closure-library.googlecode.com/svn/docs/closure_goog_dom_dom.js.html)
* @param {string} selector
* @example $('#parent').removeChildren()
* @example $('div.exists').append($('

'))
*/
var $	= function (selector) {
	var elements	= domHelper.query(selector);
	var isEmpty		= elements.length < 1;

	if (isEmpty && new DOMParser().parseFromString(selector, 'text/xml').getElementsByTagName('parsererror').length < 1) {
		var tempElem		= domHelper.createElement('div');
		tempElem.innerHTML	= selector;
		elements[0]			= tempElem.firstChild;
	}
	else if (isEmpty) {
		elements[0]	= {};
	}

	$_domHelpers.forEach(function (key) {
		for (var i = 0 ; i < elements.length ; ++i) {
			elements[i][key]	= elements[i][key] || domHelper[key].fill(elements[i]);
		}

		elements[key]	= elements[0] && elements[0][key];
	});

	return elements;
};

var domHelper		= {
	append: goog.dom.append,
	appendChild: goog.dom.appendChild,
	canHaveChildren: goog.dom.canHaveChildren,
	compareNodeOrder: goog.dom.compareNodeOrder,
	contains: goog.dom.contains,
	createDom: goog.dom.createDom,
	createElement: goog.dom.createElement,
	createTable: goog.dom.createTable,
	createTextNode: goog.dom.createTextNode,
	findCommonAncestor: goog.dom.findCommonAncestor,
	findNode: goog.dom.findNode,
	findNodes: goog.dom.findNodes,
	flattenElement: goog.dom.flattenElement,
	getActiveElement: goog.dom.getActiveElement,
	getAncestor: goog.dom.getAncestor,
	getAncestorByClass: goog.dom.getAncestorByClass,
	getAncestorByTagNameAndClass: goog.dom.getAncestorByTagNameAndClass,
	getChildren: goog.dom.getChildren,
	getCompatMode: goog.dom.getCompatMode,
	getDocument: goog.dom.getDocument,
	getDocumentHeight: goog.dom.getDocumentHeight,
	getDocumentScroll: goog.dom.getDocumentScroll,
	getDocumentScrollElement: goog.dom.getDocumentScrollElement,
	getDomHelper: goog.dom.getDomHelper,
	getElement: goog.dom.getElement,
	getElementByClass: goog.dom.getElementByClass,
	getElementsByClass: goog.dom.getElementsByClass,
	getElementsByTagNameAndClass: goog.dom.getElementsByTagNameAndClass,
	getFirstElementChild: goog.dom.getFirstElementChild,
	getFrameContentDocument: goog.dom.getFrameContentDocument,
	getFrameContentWindow: goog.dom.getFrameContentWindow,
	getLastElementChild: goog.dom.getLastElementChild,
	getNextElementSibling: goog.dom.getNextElementSibling,
	getNextNode: goog.dom.getNextNode,
	getNodeAtOffset: goog.dom.getNodeAtOffset,
	getNodeTextLength: goog.dom.getNodeTextLength,
	getNodeTextOffset: goog.dom.getNodeTextOffset,
	getOuterHtml: goog.dom.getOuterHtml,
	getOwnerDocument: goog.dom.getOwnerDocument,
	getPageScroll: goog.dom.getPageScroll,
	getParentElement: goog.dom.getParentElement,
	getPreviousElementSibling: goog.dom.getPreviousElementSibling,
	getPreviousNode: goog.dom.getPreviousNode,
	getRawTextContent: goog.dom.getRawTextContent,
	getTextContent: goog.dom.getTextContent,
	getViewportSize: goog.dom.getViewportSize,
	getWindow: goog.dom.getWindow,
	htmlToDocumentFragment: goog.dom.htmlToDocumentFragment,
	insertChildAt: goog.dom.insertChildAt,
	insertSiblingAfter: goog.dom.insertSiblingAfter,
	insertSiblingBefore: goog.dom.insertSiblingBefore,
	isCss1CompatMode: goog.dom.isCss1CompatMode,
	isElement: goog.dom.isElement,
	isFocusableTabIndex: goog.dom.isFocusableTabIndex,
	isNodeLike: goog.dom.isNodeLike,
	isNodeList: goog.dom.isNodeList,
	isWindow: goog.dom.isWindow,
	query: goog.dom.query,
	removeChildren: goog.dom.removeChildren,
	removeNode: goog.dom.removeNode,
	replaceNode: goog.dom.replaceNode,
	setFocusableTabIndex: goog.dom.setFocusableTabIndex,
	setProperties: goog.dom.setProperties,
	setTextContent: goog.dom.setTextContent
};

for (var key in domHelper) {
	$[key]	= domHelper[key];
};
<|endoftext|>


<commit_before>const fs = require('fs')
const h = require('../../h')
const pull = require('pull-stream')
const { unique, drain } = pull
const {
  Array: MutantArray,
  map, computed, when, dictToCollection
} = require('@mmckegg/mutant')

exports.needs = {
  avatar_image_link: 'first',
  avatar_action: 'map',
  avatar_edit: 'first',
  follows: 'first',
  followers: 'first'
}

exports.gives = {
  avatar_profile: true,
  mcss: true
}

exports.create = function (api) {
  return {
    avatar_profile,
    mcss: () => fs.readFileSync(__filename.replace(/js$/, 'mcss'), 'utf8')
  }

  function avatar_profile (id) {

    var rawFollows = MutantArray()
    var rawFollowers = MutantArray()
    var friends = computed([rawFollows, rawFollowers], (follows, followers) => {
      return follows.filter(follow => followers.includes(follow))
    })

    var follows = computed([rawFollows, friends], (follows, friends) => {
      return follows.filter(follow => !friends.includes(follow))
    })
    var followers = computed([rawFollowers, friends], (followers, friends) => {
      return followers.filter(follower => !friends.includes(follower))
    })

    pull(
      api.follows(id),
      unique(),
      drain(
        peer => rawFollows.push(peer),
        data => console.log('follows drain done', data)
      )
    )
    pull(
      api.followers(id),
      unique(),
      drain(
        peer => rawFollowers.push(peer),
        data => console.log('followers drain done', data)
      )
    )

    return h('Profile', [
      h('section.edit', api.avatar_edit(id)),
      h('section.relationships', [
        h('header', 'Relationships'),
        h('div.your-status', [
          h('header', 'Your status'),
          h('section.action', api.avatar_action(id))
        ]),
        h('div.friends', [
          h('header', 'Friends'),
          h('section', map(friends, id => api.avatar_image_link(id)))
        ]),
        h('div.follows', [
          h('header', 'Follows'),
          h('section', map(follows, id => api.avatar_image_link(id)))
        ]),
        h('div.followers', [
          h('header', 'Followers'),
          h('section', map(followers, id => api.avatar_image_link(id)))
        ])
      ])
    ])
  }

}
<commit_msg>correct err, data drain for profile pull-stream<commit_after>const fs = require('fs')
const h = require('../../h')
const pull = require('pull-stream')
const { unique, drain } = pull
const {
  Array: MutantArray,
  map, computed, when, dictToCollection
} = require('@mmckegg/mutant')

exports.needs = {
  avatar_image_link: 'first',
  avatar_action: 'map',
  avatar_edit: 'first',
  follows: 'first',
  followers: 'first'
}

exports.gives = {
  avatar_profile: true,
  mcss: true
}

exports.create = function (api) {
  return {
    avatar_profile,
    mcss: () => fs.readFileSync(__filename.replace(/js$/, 'mcss'), 'utf8')
  }

  function avatar_profile (id) {

    var rawFollows = MutantArray()
    var rawFollowers = MutantArray()
    var friends = computed([rawFollows, rawFollowers], (follows, followers) => {
      return follows.filter(follow => followers.includes(follow))
    })

    var follows = computed([rawFollows, friends], (follows, friends) => {
      return follows.filter(follow => !friends.includes(follow))
    })
    var followers = computed([rawFollowers, friends], (followers, friends) => {
      return followers.filter(follower => !friends.includes(follower))
    })

    pull(
      api.follows(id),
      unique(),
      drain(
        peer => rawFollows.push(peer),
        (err, data) => console.log('follows drain done', err, data)
      )
    )
    pull(
      api.followers(id),
      unique(),
      drain(
        peer => rawFollowers.push(peer),
        (err, data) => console.log('followers drain done', err, data)
      )
    )

    return h('Profile', [
      h('section.edit', api.avatar_edit(id)),
      h('section.relationships', [
        h('header', 'Relationships'),
        h('div.your-status', [
          h('header', 'Your status'),
          h('section.action', api.avatar_action(id))
        ]),
        h('div.friends', [
          h('header', 'Friends'),
          h('section', map(friends, id => api.avatar_image_link(id)))
        ]),
        h('div.follows', [
          h('header', 'Follows'),
          h('section', map(follows, id => api.avatar_image_link(id)))
        ]),
        h('div.followers', [
          h('header', 'Followers'),
          h('section', map(followers, id => api.avatar_image_link(id)))
        ])
      ])
    ])
  }

}
<|endoftext|>


<commit_before>$(document).ready(function() {
	ui.setupClickHandlers();
	api.loadBoardSpaces();
});

var ui = {
	boardSpaces: null,

	setupClickHandlers: function() {
		$('#refresh_link').click(function() {
			var callback = function(data) {
				ui.refreshGame(data);
			};

			api.getGame(callback);
		});

		$('#ownedProperties').click(function() {
			var callback = function(data) {
				ui.showOwnedPropPopup(data);
			};

			api.getGame(callback);
		});
	},

  showOwnedPropPopup: function(data) {
    var html = 'ToDo';

    //need to build for each loop over owned
    //properties to display to screen

    $('#propertyList').html(html);
    $('#ownedPropertiesDiv').popup("open");
  },

	refreshGame: function(data) {
		ui.refreshPlayers(data.players);
		ui.refreshHistory(data.history);
	},

	refreshHistory: function(history) {
		var html = '';

		for (var i = 0; i < history.length; i++) {
			html += history[i].details + '
';
		}

		$('#history').html(html);
	},

	refreshPlayers: function(players) {
		var html = '';

		for (var i = 0; i < players.length; i++) {
			html += players[i].name + ' ($' + players[i].cash + ')' + '
';
		}

		$('#players').html(html);
	}
};

var api = {

	endPoint: 'http://localhost:3000/api/v1/',

	loadBoardSpaces: function() {
		$.ajax({
			url: api.endPoint + 'board_spaces',
			success: function(data) {
				ui.boardSpaces = data;
			},
			error: function() {
				alert('ERROR');
			}
		});
	},

	getGame: function(callback) {
		var gameId = $('#gameId').val();

		$.ajax({
			url: api.endPoint + 'games/' + gameId,
			success: function(data) {
				callback(data);
			},
			error: function() {
				alert('ERROR');
			}
		});
	}
};
<commit_msg>show time in history<commit_after>$(document).ready(function() {
	ui.setupClickHandlers();
	api.loadBoardSpaces();
});

var ui = {
	boardSpaces: null,

	setupClickHandlers: function() {
		$('#refresh_link').click(function() {
			var callback = function(data) {
				ui.refreshGame(data);
			};

			api.getGame(callback);
		});

		$('#ownedProperties').click(function() {
			var callback = function(data) {
				ui.showOwnedPropPopup(data);
			};

			api.getGame(callback);
		});
	},

  showOwnedPropPopup: function(data) {
    var html = 'ToDo';

    //need to build for each loop over owned
    //properties to display to screen

    $('#propertyList').html(html);
    $('#ownedPropertiesDiv').popup("open");
  },

	refreshGame: function(data) {
		ui.refreshPlayers(data.players);
		ui.refreshHistory(data.history);
	},

	refreshHistory: function(history) {
		var html = '';

		for (var i = 0; i < history.length; i++) {
			html += '' + history[i].created_at + ': ' + history[i].details + '
';
		}

		$('#history').html(html);
	},

	refreshPlayers: function(players) {
		var html = '';

		for (var i = 0; i < players.length; i++) {
			html += players[i].name + ' ($' + players[i].cash + ')' + '
';
		}

		$('#players').html(html);
	}
};

var api = {

	endPoint: 'http://localhost:3000/api/v1/',

	loadBoardSpaces: function() {
		$.ajax({
			url: api.endPoint + 'board_spaces',
			success: function(data) {
				ui.boardSpaces = data;
			},
			error: function() {
				alert('ERROR');
			}
		});
	},

	getGame: function(callback) {
		var gameId = $('#gameId').val();

		$.ajax({
			url: api.endPoint + 'games/' + gameId,
			success: function(data) {
				callback(data);
			},
			error: function() {
				alert('ERROR');
			}
		});
	}
};
<|endoftext|>


<commit_before>var writer = require('../serializers/writer')
  , field_flags = require('../constants').field_flags
  , flags = require('../constants').flags
  , types = require('../constants').types
  , pack = require('../pack')
  , cmd = require('../command')
  , prepare = require('./prepare')
  , result = require('../result')

// TODO: too many copy-paste, cleanup
module.exports = function(q, parameters)
{
    if (this.get('auto_prepare') == true)
    {
        var cached = this.ps || this.connection.pscache[q];
        if (!cached) {
            var prepare_cmd = this.add(prepare(q));
            var execute_cmd = execPrepared(q, parameters);
            prepare_cmd
                .on('prepared', function(ps)
                {
	            execute_cmd.ps = ps;
                })
                .on('error', function(err)
                {
                    execute_cmd.emit('error', err);
                    execute_cmd.prepare_failed = true;
                });
            return execute_cmd;
        } else {
            var execute_cmd = execPrepared(q, parameters);
            execute_cmd.ps = cached;
            return execute_cmd;
        }
    }
    return execPrepared(q, parameters);
}

function execPrepared(sql, parameters)
{
  var exec = new cmd(
  {
      start: function()
      {
        this.stmt = sql
        this.params = parameters

        // don't execute if prepare failed
        // don't emit more errors - everything is in the prepare error
        if (this.prepare_failed)
          return 'done';

        // TODO: optimise
        // there is two lookups of ps object by query key
        // first one is in execute()
        if (!this.ps && this.connection.pscache)
          this.ps = this.connection.pscache[sql];

        if (!this.ps)
        {
          var error = { message: 'Prepared statement \"' + sql + '\" not found', errno: 0 };
          this.emit('error', error);
          return 'error';
        }

        // TODO: use packet codes from constants
        var packet = new writer().add("\u0017").add(this.ps.statement_handler_id).add("\u0000\u0001\u0000\u0000\u0000");

        if ( parameters && parameters.length > 0)
        {
          nb = calc_null_bitmap(parameters)
          nb.forEach(function(entry, i, nd) {
            packet.add(entry);
          })

          // todo: set types only on first call
          packet.add('\u0001');

          // todo: add numeric/datetime serialisers
          for (var i = 0; i < parameters.length; i++)
          {
            if (parameters[i] != null && parameters[i] != undefined)
            {
              packet.int2(types.MYSQL_TYPE_VAR_STRING);
            }
            else
            {
              packet.int2(types.MYSQL_TYPE_NULL)
            }
          }

          for (var i = 0; i < parameters.length; i++)
          {
            if (parameters[i] !== null && parameters[i] !== undefined)
            {
              if(typeof parameters[i] == "boolean" || (parameters[i] instanceof Array && parameters[i].every(function(x){return typeof x == 'boolean';}))){
                packet.lcbits(parameters[i]);
              }
              packet.lcstring(parameters[i].toString())
            }
          }
        }

        this.write( packet );
        return 'execute_ok';
      },
      execute_ok: function(r)
      {
        if (!r)
            return 'error'

        // todo: remove 'result' module
        this.result = new result();
        var ok = r.readOKpacket();
        this.result.insert_id = ok.insert_id;
        this.result.affected_rows = ok.affected_rows;
        this.emit('resultset_start', this.result)

        if (this.ps.field_count == 0)
        {
          this.result.insert_id = ok.insert_id;
          this.result.affected_rows = ok.affected_rows;

          this.emit('result', this.result)
          return 'done';
        }

        return 'fields';
      },
      fields: function( r )
      {
        if (r.isEOFpacket())
        {
            this.emit('fields_eof');
            return 'binrow';
        }
        var f = r.field();
        this.emit('field', f);
      },
      binrow: function( r )
      {
        if (r.isEOFpacket())
        {
          this.emit('result', this.result)
          var eof = r.readOKpacket();
          if (eof.server_status & 8)
              return 'execute_ok';
          return 'done';
        }

        var null_bit_map = [];
        r.num(1); // first octet always 0
        var bit = 4;
        var bitmap_byte;
        if (this.ps.field_count > 0)
            bitmap_byte = r.num(1);
        var numfields = this.ps.field_count;
        for (var f=0; f < numfields; ++f)
        {
            null_bit_map.push( (bitmap_byte & bit) != 0);
            if (!((bit<<=1) & 255) && f + 1 < numfields)
            {
                bit= 1;
                bitmap_byte = r.num(1);
            }
        }

        var use_hash = this.client.get('row_as_hash');
        var row = use_hash ? {} : [];
        for (var f=0; f < this.ps.field_count; ++f)
        {
            var field = this.ps.fields[f];
            if (!null_bit_map[f])
            {
                var value = r.unpackBinary(field.type, field.flags & field_flags.UNSIGNED);
                this.store_column(row, field, value, use_hash);
            } else {
                this.store_column(row, field, null, use_hash);
            }
        }

        this.result.rows.push(row)
        this.emit('row', row);
      }
  });
  exec.command_name = 'execute_prepared';
  return exec;
}

// this code hijacked from https://github.com/masuidrive/node-mysql/blob/master/lib/mysql/pack.js
function calc_null_bitmap(values) {
    var val = 0, len = 0, bitmap = [];
    values.map(function(v) {
        val += (v == null || v == undefined ? 1 << len : 0);
        len += 1;

        if(len == 8) {
          bitmap.push(val);
          len = val = 0;
        }
        return val;
    });

    if(len > 0) {
      bitmap.push(val);
    }

    var packed = []
    bitmap.forEach(function(entry, i, bitmap) {
      packed[i] = pack.pack("C*", entry)
    })

    return packed
}
<commit_msg>extra fix for #75<commit_after>var writer = require('../serializers/writer')
  , field_flags = require('../constants').field_flags
  , flags = require('../constants').flags
  , types = require('../constants').types
  , pack = require('../pack')
  , cmd = require('../command')
  , prepare = require('./prepare')
  , result = require('../result')

// TODO: too many copy-paste, cleanup
module.exports = function(q, parameters)
{
    if (this.get('auto_prepare') == true)
    {
        var cached = this.ps || this.connection.pscache[q];
        if (!cached) {
            var prepare_cmd = this.add(prepare(q));
            var execute_cmd = execPrepared(q, parameters);
            prepare_cmd
                .on('prepared', function(ps)
                {
	            execute_cmd.ps = ps;
                })
                .on('error', function(err)
                {
                    execute_cmd.emit('error', err);
                    execute_cmd.prepare_failed = true;
                });
            return execute_cmd;
        } else {
            var execute_cmd = execPrepared(q, parameters);
            execute_cmd.ps = cached;
            return execute_cmd;
        }
    }
    return execPrepared(q, parameters);
}

function execPrepared(sql, parameters)
{
  var exec = new cmd(
  {
      start: function()
      {
        this.stmt = sql
        this.params = parameters

        // don't execute if prepare failed
        // don't emit more errors - everything is in the prepare error
        if (this.prepare_failed)
          return 'done';

        // TODO: optimise
        // there is two lookups of ps object by query key
        // first one is in execute()
        if (!this.ps && this.connection.pscache)
          this.ps = this.connection.pscache[sql];

        if (!this.ps)
        {
          var error = { message: 'Prepared statement \"' + sql + '\" not found', errno: 0 };
          this.emit('error', error);
          return 'error';
        }

        // TODO: use packet codes from constants
        var packet = new writer().add("\u0017").add(this.ps.statement_handler_id).add("\u0000\u0001\u0000\u0000\u0000");

        if ( parameters && parameters.length > 0)
        {
          var nb = calc_null_bitmap(parameters)
          nb.forEach(function(entry, i, nd) {
            packet.add(entry);
          })

          // todo: set types only on first call
          packet.add('\u0001');

          // todo: add numeric/datetime serialisers
          for (var i = 0; i < parameters.length; i++)
          {
            if (parameters[i] != null && parameters[i] != undefined)
            {
              packet.int2(types.MYSQL_TYPE_VAR_STRING);
            }
            else
            {
              packet.int2(types.MYSQL_TYPE_NULL)
            }
          }

          for (var i = 0; i < parameters.length; i++)
          {
            if (parameters[i] !== null && parameters[i] !== undefined)
            {
              if(typeof parameters[i] == "boolean" || (parameters[i] instanceof Array && parameters[i].every(function(x){return typeof x == 'boolean';}))){
                packet.lcbits(parameters[i]);
              }
              packet.lcstring(parameters[i].toString())
            }
          }
        }

        this.write( packet );
        return 'execute_ok';
      },
      execute_ok: function(r)
      {
        if (!r)
            return 'error'

        // todo: remove 'result' module
        this.result = new result();
        var ok = r.readOKpacket();
        this.result.insert_id = ok.insert_id;
        this.result.affected_rows = ok.affected_rows;
        this.emit('resultset_start', this.result)

        if (this.ps.field_count == 0)
        {
          this.result.insert_id = ok.insert_id;
          this.result.affected_rows = ok.affected_rows;

          this.emit('result', this.result)
          return 'done';
        }

        return 'fields';
      },
      fields: function( r )
      {
        if (r.isEOFpacket())
        {
            this.emit('fields_eof');
            return 'binrow';
        }
        var f = r.field();
        this.emit('field', f);
      },
      binrow: function( r )
      {
        if (r.isEOFpacket())
        {
          this.emit('result', this.result)
          var eof = r.readOKpacket();
          if (eof.server_status & 8)
              return 'execute_ok';
          return 'done';
        }

        var null_bit_map = [];
        r.num(1); // first octet always 0
        var bit = 4;
        var bitmap_byte;
        if (this.ps.field_count > 0)
            bitmap_byte = r.num(1);
        var numfields = this.ps.field_count;
        for (var f=0; f < numfields; ++f)
        {
            null_bit_map.push( (bitmap_byte & bit) != 0);
            if (!((bit<<=1) & 255) && f + 1 < numfields)
            {
                bit= 1;
                bitmap_byte = r.num(1);
            }
        }

        var use_hash = this.client.get('row_as_hash');
        var row = use_hash ? {} : [];
        for (var f=0; f < this.ps.field_count; ++f)
        {
            var field = this.ps.fields[f];
            if (!null_bit_map[f])
            {
                var value = r.unpackBinary(field.type, field.flags & field_flags.UNSIGNED);
                this.store_column(row, field, value, use_hash);
            } else {
                this.store_column(row, field, null, use_hash);
            }
        }

        this.result.rows.push(row)
        this.emit('row', row);
      }
  });
  exec.command_name = 'execute_prepared';
  return exec;
}

// this code hijacked from https://github.com/masuidrive/node-mysql/blob/master/lib/mysql/pack.js
function calc_null_bitmap(values) {
    var val = 0, len = 0, bitmap = [];
    values.map(function(v) {
        val += (v == null || v == undefined ? 1 << len : 0);
        len += 1;

        if(len == 8) {
          bitmap.push(val);
          len = val = 0;
        }
        return val;
    });

    if(len > 0) {
      bitmap.push(val);
    }

    var packed = []
    bitmap.forEach(function(entry, i, bitmap) {
      packed[i] = pack.pack("C*", entry)
    })

    return packed
}
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var util = require('util')
  , OAuthStrategy = require('passport-oauth').OAuthStrategy;

/**
 * `Strategy` constructor.
 *
 * The Yahoo authentication strategy authenticates requests by delegating to
 * Yahoo using the OAuth protocol.
 *
 * Applications must supply a `verify` callback which accepts a `token`,
 * `tokenSecret` and service-specific `profile`, and then calls the `done`
 * callback supplying a `user`, which should be set to `false` if the
 * credentials are not valid.  If an exception occured, `err` should be set.
 *
 * Options:
 *   - `consumerKey`     identifies client to Yahoo
 *   - `consumerSecret`  secret used to establish ownership of the consumer key
 *   - `callbackURL`     URL to which Yahoo will redirect the user after obtaining authorization
 *
 * Examples:
 *
 *     passport.use(new YahooStrategy({
 *         consumerKey: '123-456-789',
 *         consumerSecret: 'shhh-its-a-secret'
 *         callbackURL: 'https://www.example.net/auth/yahoo/callback'
 *       },
 *       function(token, tokenSecret, profile, done) {
 *         User.findOrCreate(..., function (err, user) {
 *           done(err, user);
 *         });
 *       }
 *     ));
 *
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function Strategy(options, verify) {
  options = options || {};
  options.requestTokenURL = options.requestTokenURL || 'https://api.login.yahoo.com/oauth/v2/get_request_token';
  options.accessTokenURL = options.accessTokenURL || 'https://api.login.yahoo.com/oauth/v2/get_token';
  options.userAuthorizationURL = options.userAuthorizationURL || 'https://api.login.yahoo.com/oauth/v2/request_auth';
  options.sessionKey = options.sessionKey || 'oauth:yahoo';

  OAuthStrategy.call(this, options, verify);
  this.name = 'yahoo';
}

/**
 * Inherit from `OAuthStrategy`.
 */
util.inherits(Strategy, OAuthStrategy);

/**
 * Retrieve user profile from Yahoo.
 *
 * This function constructs a normalized profile, with the following properties:
 *
 *   - `id`
 *   - `displayName`
 *
 * @param {String} token
 * @param {String} tokenSecret
 * @param {Object} params
 * @param {Function} done
 * @api protected
 */
Strategy.prototype.userProfile = function(token, tokenSecret, params, done) {
  this._oauth.get('http://social.yahooapis.com/v1/user/' + params.xoauth_yahoo_guid + '/profile?format=json', token, tokenSecret, function (err, body, res) {
    if (err) { return done(err); }

    try {
      var json = JSON.parse(body);

      var profile = { provider: 'yahoo' };
      profile.id = json.profile.guid;
      profile.displayName = json.profile.givenName + ' ' + json.profile.familyName;
      profile.name = { familyName: json.profile.familyName,
                       givenName: json.profile.givenName };

      done(null, profile);
    } catch(e) {
      done(e);
    }
  });
}

/**
 * Expose `Strategy`.
 */
module.exports = Strategy;
<commit_msg>Add raw and parsed JSON properties to profile.<commit_after>/**
 * Module dependencies.
 */
var util = require('util')
  , OAuthStrategy = require('passport-oauth').OAuthStrategy;

/**
 * `Strategy` constructor.
 *
 * The Yahoo authentication strategy authenticates requests by delegating to
 * Yahoo using the OAuth protocol.
 *
 * Applications must supply a `verify` callback which accepts a `token`,
 * `tokenSecret` and service-specific `profile`, and then calls the `done`
 * callback supplying a `user`, which should be set to `false` if the
 * credentials are not valid.  If an exception occured, `err` should be set.
 *
 * Options:
 *   - `consumerKey`     identifies client to Yahoo
 *   - `consumerSecret`  secret used to establish ownership of the consumer key
 *   - `callbackURL`     URL to which Yahoo will redirect the user after obtaining authorization
 *
 * Examples:
 *
 *     passport.use(new YahooStrategy({
 *         consumerKey: '123-456-789',
 *         consumerSecret: 'shhh-its-a-secret'
 *         callbackURL: 'https://www.example.net/auth/yahoo/callback'
 *       },
 *       function(token, tokenSecret, profile, done) {
 *         User.findOrCreate(..., function (err, user) {
 *           done(err, user);
 *         });
 *       }
 *     ));
 *
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function Strategy(options, verify) {
  options = options || {};
  options.requestTokenURL = options.requestTokenURL || 'https://api.login.yahoo.com/oauth/v2/get_request_token';
  options.accessTokenURL = options.accessTokenURL || 'https://api.login.yahoo.com/oauth/v2/get_token';
  options.userAuthorizationURL = options.userAuthorizationURL || 'https://api.login.yahoo.com/oauth/v2/request_auth';
  options.sessionKey = options.sessionKey || 'oauth:yahoo';

  OAuthStrategy.call(this, options, verify);
  this.name = 'yahoo';
}

/**
 * Inherit from `OAuthStrategy`.
 */
util.inherits(Strategy, OAuthStrategy);

/**
 * Retrieve user profile from Yahoo.
 *
 * This function constructs a normalized profile, with the following properties:
 *
 *   - `id`
 *   - `displayName`
 *
 * @param {String} token
 * @param {String} tokenSecret
 * @param {Object} params
 * @param {Function} done
 * @api protected
 */
Strategy.prototype.userProfile = function(token, tokenSecret, params, done) {
  this._oauth.get('http://social.yahooapis.com/v1/user/' + params.xoauth_yahoo_guid + '/profile?format=json', token, tokenSecret, function (err, body, res) {
    if (err) { return done(err); }

    try {
      var json = JSON.parse(body);

      var profile = { provider: 'yahoo' };
      profile.id = json.profile.guid;
      profile.displayName = json.profile.givenName + ' ' + json.profile.familyName;
      profile.name = { familyName: json.profile.familyName,
                       givenName: json.profile.givenName };

      profile._raw = body;
      profile._json = json;

      done(null, profile);
    } catch(e) {
      done(e);
    }
  });
}

/**
 * Expose `Strategy`.
 */
module.exports = Strategy;
<|endoftext|>


<commit_before>const es_ES = {}

es_ES.strings = {
  addMoreFiles: 'Agregar más archivos',
  addingMoreFiles: 'Agregando más archivos',
  allowAccessDescription: 'Para tomar fotos o grabar video con tu cámara, por favor permite a este sitio el acceso a la cámara.',
  allowAccessTitle: 'Por favor permite el acceso a tu cámara',
  authenticateWith: 'Conectar a %{pluginName}',
  authenticateWithTitle: 'Por favor autentícate con %{pluginName} para seleccionar archivos',
  back: 'Atrás',
  addMore: 'Agregar más',
  browse: 'navegar',
  browseFiles: 'navegar',
  cancel: 'Cancelar',
  cancelUpload: 'Cancelar subida',
  chooseFiles: 'Seleccionar archivos',
  closeModal: 'Cerrar ventana flotante',
  companionError: 'Conexión con Companion falló',
  complete: 'Completado',
  connectedToInternet: 'Conectado a Internet',
  copyLink: 'Copiar enlace',
  copyLinkToClipboardFallback: 'Copia la siguiente URL',
  copyLinkToClipboardSuccess: 'Enlace copiado al portapapeles',
  creatingAssembly: 'Preparando subida...',
  creatingAssemblyFailed: 'Transloadit: No se pudo crear un Assembly',
  dashboardTitle: 'Cargador de archivos',
  dashboardWindowTitle: 'Ventana para cargar archivos (Presiona escape para cerrar)',
  dataUploadedOfTotal: '%{complete} de %{total}',
  done: 'Hecho',
  dropHereOr: 'Soltar archivos aquí o %{browse}',
  dropHint: 'Suelta tus archivos aquí',
  dropPasteBoth: 'Soltar archivos aquí, pegar o %{browse}',
  dropPasteFiles: 'Soltar archivos aquí, pegar o %{browse}',
  dropPasteFolders: 'Soltar archivos aquí, pegar o %{browse}',
  dropPasteImportBoth: 'Soltar archivos aquí, pegar, %{browse} o importar desde',
  dropPasteImportFiles: 'Soltar archivos aquí, pegar, %{browse} o importar desde',
  dropPasteImportFolders: 'Soltar archivos aquí, pegar, %{browse} o importar desde',
  editFile: 'Editar archivo',
  editing: 'Editando %{file}',
  emptyFolderAdded: 'Ningún archivo fue agregado desde la carpeta vacía',
  encoding: 'Codificando...',
  enterCorrectUrl: 'URL incorrecta: Por favor asegúrate que estás ingresando un enlace a un archivo',
  enterUrlToImport: 'Ingresa una URL para importar un archivo',
  exceedsSize: 'Este archivo excede el tamaño máximo de %{size}',
  failedToFetch: 'Companion no ha podido recuperar esta URL, por favor asegúrate que sea correcta',
  failedToUpload: 'Error al subir %{file}',
  fileSource: 'Fuente de archivo: %{name}',
  filesUploadedOfTotal: {
    '0': '%{complete} de %{smart_count} archivo subido',
    '1': '%{complete} de %{smart_count} archivos subidos',
    '2': '%{complete} de %{smart_count} archivos subidos',
  },
  filter: 'Filtrar',
  finishEditingFile: 'Terminar edición de archivo',
  folderAdded: {
    '0': 'Agregado %{smart_count} archivo desde %{folder}',
    '1': 'Agregados %{smart_count} archivos desde %{folder}',
    '2': 'Agregados %{smart_count} archivos desde %{folder}',
  },
  import: 'Importar',
  importFrom: 'Importar desde %{name}',
  loading: 'Cargando...',
  logOut: 'Cerrar sesión',
  missingRequiredMetaField: 'Faltan metacampos obligatorios',
  missingRequiredMetaFieldOnFile: 'Faltan metacampos obligatorios en %{fileName}',
  myDevice: 'Mi Dispositivo',
  noFilesFound: 'No existen archivos o carpetas aquí',
  noInternetConnection: 'Sin conexión a Internet',
  pause: 'Pausar',
  pauseUpload: 'Pausar subida',
  paused: 'En pausa',
  poweredBy: 'Soportado por %{uppy}',
  processingXFiles: {
    '0': 'Procesando %{smart_count} archivo',
    '1': 'Procesando %{smart_count} archivos',
    '2': 'Procesando %{smart_count} archivos',
  },
  recordingLength: 'Duración de grabación %{recording_length}',
  removeFile: 'Eliminar archivo',
  resetFilter: 'Limpiar filtro',
  resume: 'Reanudar',
  resumeUpload: 'Reanudar subida',
  retry: 'Intentar nuevamente',
  retryUpload: 'Intentar subida nuevamente',
  saveChanges: 'Guardar cambios',
  selectX: {
    '0': 'Seleccionar %{smart_count}',
    '1': 'Seleccionar %{smart_count}',
    '2': 'Seleccionar %{smart_count}',
  },
  smile: 'Sonríe!',
  startRecording: 'Comenzar la grabación de video',
  stopRecording: 'Detener la grabación de video',
  takePicture: 'Tomar una foto',
  timedOut: 'Subida estancada por %{seconds} segundos, anulando.',
  upload: 'Subir',
  uploadComplete: 'Subida terminada',
  uploadFailed: 'Subida falló',
  uploadPaused: 'Subida pausada',
  uploadXFiles: {
    '0': 'Subir %{smart_count} archivo',
    '1': 'Subir %{smart_count} archivos',
    '2': 'Subir %{smart_count} archivos',
  },
  uploadXNewFiles: {
    '0': 'Subir +%{smart_count} archivo',
    '1': 'Subir +%{smart_count} archivos',
    '2': 'Subir +%{smart_count} archivos',
  },
  uploading: 'Subiendo',
  uploadingXFiles: {
    '0': 'Subiendo %{smart_count} archivo',
    '1': 'Subiendo %{smart_count} archivos',
    '2': 'Subiendo %{smart_count} archivos',
  },
  xFilesSelected: {
    '0': '%{smart_count} archivo seleccionado',
    '1': '%{smart_count} archivos seleccionados',
    '2': '%{smart_count} archivos seleccionados',
  },
  xMoreFilesAdded: {
    '0': '%{smart_count} archivo más agregado',
    '1': '%{smart_count} archivos más agregados',
    '2': '%{smart_count} archivos más agregados',
  },
  xTimeLeft: '%{time} restantes',
  youCanOnlyUploadFileTypes: 'Solo puedes subir: %{types}',
  youCanOnlyUploadX: {
    '0': 'Solo puedes subir %{smart_count} archivo',
    '1': 'Solo puedes subir %{smart_count} archivos',
    '2': 'Solo puedes subir %{smart_count} archivos',
  },
  youHaveToAtLeastSelectX: {
    '0': 'Tienes que seleccionar al menos %{smart_count} archivo',
    '1': 'Tienes que seleccionar al menos %{smart_count} archivos',
    '2': 'Tienes que seleccionar al menos %{smart_count} archivos',
  },
  selectFileNamed: 'Seleccione archivo %{name}',
  unselectFileNamed: 'Deseleccionar archivo %{name}',
  openFolderNamed: 'Carpeta abierta %{name}',
}

es_ES.pluralize = function pluralize (n) {
  if (n === 1) {
    return 0
  }
  return 1
}

if (typeof window !== 'undefined' && typeof window.Uppy !== 'undefined') {
  window.Uppy.locales.es_ES = es_ES
}

module.exports = es_ES
<commit_msg>Add `save` translation to Spanish locale (#3678)<commit_after>const es_ES = {}

es_ES.strings = {
  addMoreFiles: 'Agregar más archivos',
  addingMoreFiles: 'Agregando más archivos',
  allowAccessDescription: 'Para tomar fotos o grabar video con tu cámara, por favor permite a este sitio el acceso a la cámara.',
  allowAccessTitle: 'Por favor permite el acceso a tu cámara',
  authenticateWith: 'Conectar a %{pluginName}',
  authenticateWithTitle: 'Por favor autentícate con %{pluginName} para seleccionar archivos',
  back: 'Atrás',
  addMore: 'Agregar más',
  browse: 'navegar',
  browseFiles: 'navegar',
  cancel: 'Cancelar',
  cancelUpload: 'Cancelar subida',
  chooseFiles: 'Seleccionar archivos',
  closeModal: 'Cerrar ventana flotante',
  companionError: 'Conexión con Companion falló',
  complete: 'Completado',
  connectedToInternet: 'Conectado a Internet',
  copyLink: 'Copiar enlace',
  copyLinkToClipboardFallback: 'Copia la siguiente URL',
  copyLinkToClipboardSuccess: 'Enlace copiado al portapapeles',
  creatingAssembly: 'Preparando subida...',
  creatingAssemblyFailed: 'Transloadit: No se pudo crear un Assembly',
  dashboardTitle: 'Cargador de archivos',
  dashboardWindowTitle: 'Ventana para cargar archivos (Presiona escape para cerrar)',
  dataUploadedOfTotal: '%{complete} de %{total}',
  done: 'Hecho',
  dropHereOr: 'Soltar archivos aquí o %{browse}',
  dropHint: 'Suelta tus archivos aquí',
  dropPasteBoth: 'Soltar archivos aquí, pegar o %{browse}',
  dropPasteFiles: 'Soltar archivos aquí, pegar o %{browse}',
  dropPasteFolders: 'Soltar archivos aquí, pegar o %{browse}',
  dropPasteImportBoth: 'Soltar archivos aquí, pegar, %{browse} o importar desde',
  dropPasteImportFiles: 'Soltar archivos aquí, pegar, %{browse} o importar desde',
  dropPasteImportFolders: 'Soltar archivos aquí, pegar, %{browse} o importar desde',
  editFile: 'Editar archivo',
  editing: 'Editando %{file}',
  emptyFolderAdded: 'Ningún archivo fue agregado desde la carpeta vacía',
  encoding: 'Codificando...',
  enterCorrectUrl: 'URL incorrecta: Por favor asegúrate que estás ingresando un enlace a un archivo',
  enterUrlToImport: 'Ingresa una URL para importar un archivo',
  exceedsSize: 'Este archivo excede el tamaño máximo de %{size}',
  failedToFetch: 'Companion no ha podido recuperar esta URL, por favor asegúrate que sea correcta',
  failedToUpload: 'Error al subir %{file}',
  fileSource: 'Fuente de archivo: %{name}',
  filesUploadedOfTotal: {
    '0': '%{complete} de %{smart_count} archivo subido',
    '1': '%{complete} de %{smart_count} archivos subidos',
    '2': '%{complete} de %{smart_count} archivos subidos',
  },
  filter: 'Filtrar',
  finishEditingFile: 'Terminar edición de archivo',
  folderAdded: {
    '0': 'Agregado %{smart_count} archivo desde %{folder}',
    '1': 'Agregados %{smart_count} archivos desde %{folder}',
    '2': 'Agregados %{smart_count} archivos desde %{folder}',
  },
  import: 'Importar',
  importFrom: 'Importar desde %{name}',
  loading: 'Cargando...',
  logOut: 'Cerrar sesión',
  missingRequiredMetaField: 'Faltan metacampos obligatorios',
  missingRequiredMetaFieldOnFile: 'Faltan metacampos obligatorios en %{fileName}',
  myDevice: 'Mi Dispositivo',
  noFilesFound: 'No existen archivos o carpetas aquí',
  noInternetConnection: 'Sin conexión a Internet',
  pause: 'Pausar',
  pauseUpload: 'Pausar subida',
  paused: 'En pausa',
  poweredBy: 'Soportado por %{uppy}',
  processingXFiles: {
    '0': 'Procesando %{smart_count} archivo',
    '1': 'Procesando %{smart_count} archivos',
    '2': 'Procesando %{smart_count} archivos',
  },
  recordingLength: 'Duración de grabación %{recording_length}',
  removeFile: 'Eliminar archivo',
  resetFilter: 'Limpiar filtro',
  resume: 'Reanudar',
  resumeUpload: 'Reanudar subida',
  retry: 'Intentar nuevamente',
  retryUpload: 'Intentar subida nuevamente',
  save: 'Guardar',
  saveChanges: 'Guardar cambios',
  selectX: {
    '0': 'Seleccionar %{smart_count}',
    '1': 'Seleccionar %{smart_count}',
    '2': 'Seleccionar %{smart_count}',
  },
  smile: 'Sonríe!',
  startRecording: 'Comenzar la grabación de video',
  stopRecording: 'Detener la grabación de video',
  takePicture: 'Tomar una foto',
  timedOut: 'Subida estancada por %{seconds} segundos, anulando.',
  upload: 'Subir',
  uploadComplete: 'Subida terminada',
  uploadFailed: 'Subida falló',
  uploadPaused: 'Subida pausada',
  uploadXFiles: {
    '0': 'Subir %{smart_count} archivo',
    '1': 'Subir %{smart_count} archivos',
    '2': 'Subir %{smart_count} archivos',
  },
  uploadXNewFiles: {
    '0': 'Subir +%{smart_count} archivo',
    '1': 'Subir +%{smart_count} archivos',
    '2': 'Subir +%{smart_count} archivos',
  },
  uploading: 'Subiendo',
  uploadingXFiles: {
    '0': 'Subiendo %{smart_count} archivo',
    '1': 'Subiendo %{smart_count} archivos',
    '2': 'Subiendo %{smart_count} archivos',
  },
  xFilesSelected: {
    '0': '%{smart_count} archivo seleccionado',
    '1': '%{smart_count} archivos seleccionados',
    '2': '%{smart_count} archivos seleccionados',
  },
  xMoreFilesAdded: {
    '0': '%{smart_count} archivo más agregado',
    '1': '%{smart_count} archivos más agregados',
    '2': '%{smart_count} archivos más agregados',
  },
  xTimeLeft: '%{time} restantes',
  youCanOnlyUploadFileTypes: 'Solo puedes subir: %{types}',
  youCanOnlyUploadX: {
    '0': 'Solo puedes subir %{smart_count} archivo',
    '1': 'Solo puedes subir %{smart_count} archivos',
    '2': 'Solo puedes subir %{smart_count} archivos',
  },
  youHaveToAtLeastSelectX: {
    '0': 'Tienes que seleccionar al menos %{smart_count} archivo',
    '1': 'Tienes que seleccionar al menos %{smart_count} archivos',
    '2': 'Tienes que seleccionar al menos %{smart_count} archivos',
  },
  selectFileNamed: 'Seleccione archivo %{name}',
  unselectFileNamed: 'Deseleccionar archivo %{name}',
  openFolderNamed: 'Carpeta abierta %{name}',
}

es_ES.pluralize = function pluralize (n) {
  if (n === 1) {
    return 0
  }
  return 1
}

if (typeof window !== 'undefined' && typeof window.Uppy !== 'undefined') {
  window.Uppy.locales.es_ES = es_ES
}

module.exports = es_ES
<|endoftext|>


<commit_before>var PluginDependency = require('../../models/pluginDependency');
var sortPlugins = require('../sortPlugins');
var listAll = require('../listAll');

describe('sortPlugins', function() {
    it('must load themes after plugins', function() {
        var deps = PluginDependency.listFromString('theme-faq'),
            allPlugins = listAll(deps);

        var sorted = sortPlugins(allPlugins, []);

        var plugins = sorted.slice(0, -2),
            themes = sorted.slice(-2);

        var pluginsOk = plugins.every(function(plugin) {
            return !plugin.isTheme();
        });

        var themesOk = themes.every(function(theme) {
            return theme.isTheme();
        });

        expect(pluginsOk).toBe(true);
        expect(plugins.has('search')).toBe(true);

        expect(themesOk).toBe(true);
        expect(themes.size).toBe(2);
        expect(themes.has('theme-faq')).toBe(true);
        expect(themes.has('theme-default')).toBe(true);

        // theme-default should be last
        expect(themes.last().getName()).toBe('theme-default');
    });

    it('must load themes after plugins with a complex dependencies list', function() {
        var deps = PluginDependency.listFromString('comment,theme-faq,-search,ga'),
            allPlugins = listAll(deps);

        var sorted = sortPlugins(allPlugins, []);

        var plugins = sorted.slice(0, -2),
            themes = sorted.slice(-2);

        var pluginsOk = plugins.every(function(plugin) {
            return !plugin.isTheme();
        });

        var themesOk = themes.every(function(theme) {
            return theme.isTheme();
        });

        expect(pluginsOk).toBe(true);
        expect(plugins.has('search')).toBe(false);

        expect(themesOk).toBe(true);
        expect(themes.size).toBe(2);
        expect(themes.has('theme-faq')).toBe(true);
        expect(themes.has('theme-default')).toBe(true);
    });
});<commit_msg>Compare list of plugins sorted to array of names in tests<commit_after>var PluginDependency = require('../../models/pluginDependency');
var sortPlugins = require('../sortPlugins');
var listAll = require('../listAll');

describe('sortPlugins', function() {
    it('must load themes after plugins', function() {
        var deps = PluginDependency.listFromString('theme-faq'),
            allPlugins = listAll(deps);

        var sorted = sortPlugins(allPlugins, []);
        var names = sorted
            .map(function(plugin) {
                return plugin.getName();
            })
            .toArray();

        expect(names).toEqual([
            'fontsettings',
            'sharing',
            'lunr',
            'search',
            'highlight',
            'theme-faq',
            'theme-default'
        ]);
    });

    it('must load themes after plugins with a complex dependencies list', function() {
        var deps = PluginDependency.listFromString('comment,theme-faq,-search,ga'),
            allPlugins = listAll(deps);

        var sorted = sortPlugins(allPlugins, []);
        var names = sorted
            .map(function(plugin) {
                return plugin.getName();
            })
            .toArray();

        expect(names).toEqual([
            'ga',
            'comment',
            'fontsettings',
            'sharing',
            'lunr',
            'highlight',
            'theme-faq',
            'theme-default'
        ]);
    });
});<|endoftext|>


<commit_before>/*! @license
 * Shaka Player
 * Copyright 2016 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

goog.provide('shaka.polyfill.VideoPlaybackQuality');

goog.require('shaka.polyfill');

/**
 * @summary A polyfill to provide MSE VideoPlaybackQuality metrics.
 * Many browsers do not yet provide this API, and Chrome currently provides
 * similar data through individual prefixed attributes on HTMLVideoElement.
 * @export
 */
shaka.polyfill.VideoPlaybackQuality = class {
  /**
   * Install the polyfill if needed.
   * @export
   */
  static install() {
    if (!window.HTMLVideoElement) {
      // Avoid errors on very old browsers.
      return;
    }

    // eslint-disable-next-line no-restricted-syntax
    const proto = HTMLVideoElement.prototype;
    if (proto.getVideoPlaybackQuality) {
      // No polyfill needed.
      return;
    }

    if ('webkitDroppedFrameCount' in proto) {
      proto.getVideoPlaybackQuality =
          shaka.polyfill.VideoPlaybackQuality.webkit_;
    }
  }

  /**
   * @this {HTMLVideoElement}
   * @return {!VideoPlaybackQuality}
   * @private
   */
  static webkit_() {
    return {
      'droppedVideoFrames': this.webkitDroppedFrameCount,
      'totalVideoFrames': this.webkitDecodedFrameCount,
      // Not provided by this polyfill:
      'corruptedVideoFrames': 0,
      'creationTime': NaN,
      'totalFrameDelay': 0,
    };
  }
};

shaka.polyfill.register(shaka.polyfill.VideoPlaybackQuality.install);
<commit_msg>fix: Fix getVideoPlaybackQuality in WebOS 3 (#4316)<commit_after>/*! @license
 * Shaka Player
 * Copyright 2016 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

goog.provide('shaka.polyfill.VideoPlaybackQuality');

goog.require('shaka.polyfill');
goog.require('shaka.util.Platform');

/**
 * @summary A polyfill to provide MSE VideoPlaybackQuality metrics.
 * Many browsers do not yet provide this API, and Chrome currently provides
 * similar data through individual prefixed attributes on HTMLVideoElement.
 * @export
 */
shaka.polyfill.VideoPlaybackQuality = class {
  /**
   * Install the polyfill if needed.
   * @export
   */
  static install() {
    if (!window.HTMLVideoElement) {
      // Avoid errors on very old browsers.
      return;
    }

    // eslint-disable-next-line no-restricted-syntax
    const proto = HTMLVideoElement.prototype;
    if (proto.getVideoPlaybackQuality) {
      // No polyfill needed.
      return;
    }

    if ('webkitDroppedFrameCount' in proto ||
        shaka.util.Platform.isWebOS3()) {
      proto.getVideoPlaybackQuality =
          shaka.polyfill.VideoPlaybackQuality.webkit_;
    }
  }

  /**
   * @this {HTMLVideoElement}
   * @return {!VideoPlaybackQuality}
   * @private
   */
  static webkit_() {
    return {
      'droppedVideoFrames': this.webkitDroppedFrameCount,
      'totalVideoFrames': this.webkitDecodedFrameCount,
      // Not provided by this polyfill:
      'corruptedVideoFrames': 0,
      'creationTime': NaN,
      'totalFrameDelay': 0,
    };
  }
};

shaka.polyfill.register(shaka.polyfill.VideoPlaybackQuality.install);
<|endoftext|>


<commit_before>import React, { useState } from "react";
import PropTypes from "prop-types";
import { cx, css } from "emotion";
import { ThemeContext } from "@hig/theme-context";
import { ControlBehavior } from "@hig/behaviors";

import {
  indicators,
  indicatorPositions,
  AVAILABLE_INDICATORS,
  AVAILABLE_INDICATOR_POSITIONS
} from "./constants";
import stylesheet from "./stylesheet";
import HeaderPresenter from "./presenters/HeaderPresenter";
import ContentPresenter from "./presenters/ContentPresenter";

const Accordion = props => {
  const [collapsed, setCollapsed] = useState(props.defaultCollapsed);

  const isCollapsedControlled = () => props.collapsed !== undefined;

  const isCollapsed = () =>
    isCollapsedControlled() ? props.collapsed : collapsed;

  const onClick = () => {
    if (!isCollapsedControlled()) {
      setCollapsed(!collapsed);
    }
    props.onClick(isCollapsed());
  };

  const {
    children,
    label,
    indicator,
    indicatorPosition,
    disabled,
    stylesheet: customStylesheet,
    ...otherProps
  } = props;

  const {
    className,
    onBlur,
    onFocus,
    onMouseDown,
    onMouseEnter,
    onMouseLeave,
    onMouseUp,
    onHover
  } = otherProps;

  return (
    <ThemeContext.Consumer>
      {({ resolvedRoles, metadata }) => {
        const styles = stylesheet(
          {
            indicator,
            indicatorPosition,
            collapsed: isCollapsed(),
            stylesheet: customStylesheet
          },
          resolvedRoles,
          metadata
        );

        return (

            <ControlBehavior
              onBlur={onBlur}
              onFocus={onFocus}
              onMouseDown={onMouseDown}
              onMouseEnter={onMouseEnter}
              onMouseLeave={onMouseLeave}
              onMouseUp={onMouseUp}
            >
              {({
                hasFocus,
                hasHover,
                isPressed,
                onBlur: handleBlur,
                onFocus: handleFocus,
                onMouseDown: handleMouseDown,
                onMouseEnter: handleMouseEnter,
                onMouseLeave: handleMouseLeave,
                onMouseUp: handleMouseUp
              }) => (
                <HeaderPresenter
                  {...otherProps}
                  hasFocus={hasFocus}
                  hasHover={hasHover}
                  isPressed={isPressed}
                  onBlur={handleBlur}
                  onClick={onClick}
                  onFocus={handleFocus}
                  onHover={onHover}
                  onMouseDown={handleMouseDown}
                  onMouseEnter={handleMouseEnter}
                  onMouseLeave={handleMouseLeave}
                  onMouseUp={handleMouseUp}
                  stylesheet={customStylesheet}
                  label={label}
                  indicator={indicator}
                  indicatorPosition={indicatorPosition}
                  collapsed={isCollapsed()}
                  disabled={disabled}
                />
              )}
            </ControlBehavior>
            <ContentPresenter
              collapsed={isCollapsed()}
              stylesheet={customStylesheet}
              className={className}
            >
              {children}
            </ContentPresenter>

        );
      }}
    </ThemeContext.Consumer>
  );
};

Accordion.displayName = "Accordion";

Accordion.propTypes = {
  /** Content of the accordion */
  children: PropTypes.node,
  /** Controlled value, specifies whether the accordion is collapsed or not
   * When provided, it overrides the accordion's collapsed state
   */
  collapsed: PropTypes.bool,
  /** Specifies whether the accordion is default collapsed or not */
  defaultCollapsed: PropTypes.bool,
  /** Specifies whether the accordion is disabled or not */
  disabled: PropTypes.bool,
  /** Indicator icon */
  indicator: PropTypes.oneOf(AVAILABLE_INDICATORS),
  /** Indicator's position */
  indicatorPosition: PropTypes.oneOf(AVAILABLE_INDICATOR_POSITIONS),
  /** Text label for the accordion header */
  label: PropTypes.node.isRequired,
  /** Function called when clicks the accordion's header */
  onClick: PropTypes.func,
  /** Function to modify the component's styles */
  stylesheet: PropTypes.func
};

Accordion.defaultProps = {
  indicator: indicators.CARET,
  indicatorPosition: indicatorPositions.LEFT,
  defaultCollapsed: true,
  disabled: false,
  onClick: () => {}
};

export default Accordion;
<commit_msg>fix: remove space blank lint<commit_after>import React, { useState } from "react";
import PropTypes from "prop-types";
import { cx, css } from "emotion";
import { ThemeContext } from "@hig/theme-context";
import { ControlBehavior } from "@hig/behaviors";

import {
  indicators,
  indicatorPositions,
  AVAILABLE_INDICATORS,
  AVAILABLE_INDICATOR_POSITIONS
} from "./constants";
import stylesheet from "./stylesheet";
import HeaderPresenter from "./presenters/HeaderPresenter";
import ContentPresenter from "./presenters/ContentPresenter";

const Accordion = props => {
  const [collapsed, setCollapsed] = useState(props.defaultCollapsed);

  const isCollapsedControlled = () => props.collapsed !== undefined;

  const isCollapsed = () =>
    isCollapsedControlled() ? props.collapsed : collapsed;

  const onClick = () => {
    if (!isCollapsedControlled()) {
      setCollapsed(!collapsed);
    }
    props.onClick(isCollapsed());
  };

  const {
    children,
    label,
    indicator,
    indicatorPosition,
    disabled,
    stylesheet: customStylesheet,
    ...otherProps
  } = props;

  const {
    className,
    onBlur,
    onFocus,
    onMouseDown,
    onMouseEnter,
    onMouseLeave,
    onMouseUp,
    onHover
  } = otherProps;

  return (
    <ThemeContext.Consumer>
      {({ resolvedRoles, metadata }) => {
        const styles = stylesheet(
          {
            indicator,
            indicatorPosition,
            collapsed: isCollapsed(),
            stylesheet: customStylesheet
          },
          resolvedRoles,
          metadata
        );

        return (

            <ControlBehavior
              onBlur={onBlur}
              onFocus={onFocus}
              onMouseDown={onMouseDown}
              onMouseEnter={onMouseEnter}
              onMouseLeave={onMouseLeave}
              onMouseUp={onMouseUp}
            >
              {({
                hasFocus,
                hasHover,
                isPressed,
                onBlur: handleBlur,
                onFocus: handleFocus,
                onMouseDown: handleMouseDown,
                onMouseEnter: handleMouseEnter,
                onMouseLeave: handleMouseLeave,
                onMouseUp: handleMouseUp
              }) => (
                <HeaderPresenter
                  {...otherProps}
                  hasFocus={hasFocus}
                  hasHover={hasHover}
                  isPressed={isPressed}
                  onBlur={handleBlur}
                  onClick={onClick}
                  onFocus={handleFocus}
                  onHover={onHover}
                  onMouseDown={handleMouseDown}
                  onMouseEnter={handleMouseEnter}
                  onMouseLeave={handleMouseLeave}
                  onMouseUp={handleMouseUp}
                  stylesheet={customStylesheet}
                  label={label}
                  indicator={indicator}
                  indicatorPosition={indicatorPosition}
                  collapsed={isCollapsed()}
                  disabled={disabled}
                />
              )}
            </ControlBehavior>
            <ContentPresenter
              collapsed={isCollapsed()}
              stylesheet={customStylesheet}
              className={className}
            >
              {children}
            </ContentPresenter>

        );
      }}
    </ThemeContext.Consumer>
  );
};

Accordion.displayName = "Accordion";

Accordion.propTypes = {
  /** Content of the accordion */
  children: PropTypes.node,
  /** Controlled value, specifies whether the accordion is collapsed or not
   * When provided, it overrides the accordion's collapsed state
   */
  collapsed: PropTypes.bool,
  /** Specifies whether the accordion is default collapsed or not */
  defaultCollapsed: PropTypes.bool,
  /** Specifies whether the accordion is disabled or not */
  disabled: PropTypes.bool,
  /** Indicator icon */
  indicator: PropTypes.oneOf(AVAILABLE_INDICATORS),
  /** Indicator's position */
  indicatorPosition: PropTypes.oneOf(AVAILABLE_INDICATOR_POSITIONS),
  /** Text label for the accordion header */
  label: PropTypes.node.isRequired,
  /** Function called when clicks the accordion's header */
  onClick: PropTypes.func,
  /** Function to modify the component's styles */
  stylesheet: PropTypes.func
};

Accordion.defaultProps = {
  indicator: indicators.CARET,
  indicatorPosition: indicatorPositions.LEFT,
  defaultCollapsed: true,
  disabled: false,
  onClick: () => {}
};

export default Accordion;
<|endoftext|>


<commit_before>"use strict";

var exec = require("cordova/exec");

var InvitePlugin = {

    sendInvite: function (s, f) {
        exec(s, f, "InvitePlugin", "invite", []);

        console.log("js function procced");
    }
};

module.exports = InvitePlugin;<commit_msg>js fix<commit_after>var exec = require("cordova/exec");

var InvitePlugin = {

    sendInvite: function (s, f) {
        exec(s, f, "InvitePlugin", "invite", []);

        console.log("js function procced");
    }
};

module.exports = InvitePlugin;<|endoftext|>


<commit_before>'use strict'
var Connection = require('../connection')
var WsClient = require('websocket').w3cwebsocket

// var cache = {}
// clear once in a while

module.exports = new Connection({
  upstream: {
    $type: 'url',
    on: {
      data: {
        protocol (data, event) {
          var val = this.val
          if (!val) {
            return
          }
          if (data === null) {
            // console.warn('removing connection dont worry about it for now! -- add more here later')
            return
          }

          if (this.parent.internal) {
            // probably something here
            this.parent.internal.close()
          }

          let wsClient = this.parent.internal = new WsClient(val, 'hubs')
          wsClient.onerror = (err) => {
            this.parent.emit('error', err)
          }
          wsClient.onmessage = (data) => {
            // ok so fix data right here
            this.parent.emit('message', JSON.parse(data.data))
          }
          wsClient.onopen = () => {
            this.parent.emit('connect')
          }
          // on remove wsClient.close()
          wsClient.onclose = () => {
            wsClient.close()
            this.parent.emit('close')
          }
        }
      }
    }
  },
  define: {
    send (data) {
      var payload
      payload = JSON.stringify(data)
      this.internal.send(payload)
    }
  },
  on: {
    remove: {
      protocol () {
        if (this.internal) {
          this.internal.close()
        }
      }
    }
  }
}).Constructor
<commit_msg>update<commit_after>'use strict'
var Connection = require('../connection')
var WsClient = require('websocket').w3cwebsocket

// var cache = {}
// clear once in a while

module.exports = new Connection({
  upstream: {
    $type: 'url',
    on: {
      data: {
        protocol (data, event) {
          var val = this.val
          if (!val) {
            return
          }
          if (data === null) {
            // console.warn('removing connection dont worry about it for now! -- add more here later')
            return
          }

          if (this.parent.internal) {
            // probably something here
            this.parent.internal.close()
          }

          let wsClient = this.parent.internal = new WsClient(val, 'hubs')
          wsClient.onerror = (err) => {
            this.parent.emit('error', err)
          }
          wsClient.onmessage = (data) => {
            // ok so fix data right here
            this.parent.emit('message', JSON.parse(data.data))
          }
          wsClient.onopen = () => {
            this.parent.emit('connect')
          }
          // on remove wsClient.close()
          wsClient.onclose = () => {
            wsClient.close()
            this.parent.emit('close')
          }
        }
      }
    }
  },
  define: {
    send (data) {
      var payload
      payload = JSON.stringify(data)
      // console.log(this._input)
      if (this.internal) {
        this.internal.send(payload)
      } else {
        console.log('somethign wrong trying to fire send on removed client!', data, this.path)
      }
    }
  },
  on: {
    remove: {
      protocol () {
        if (this.internal) {
          this.internal.close()
        }
      }
    }
  }
}).Constructor
<|endoftext|>